okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
20.0 KiB413 linesraw
1"""Getting the picture files (the mmproj, about 0.9 GB) onto this computer for a model that is already installed, and nothing else.
2
3A model whose run config has no ``vision`` section reads no pictures. The person turns "Read pictures" on (it is on by default), presses
4Load, and this module does the one thing that is missing: it finds the picture file (or downloads it once, pinned, size and SHA-256
5checked) and works out the run config's ``vision`` section for the engine in use. It never looks at the model's own files, never prepares
6the pack or the draft layer again, never changes the data folder, and never writes the run config: the caller does (apps/host).
7
8    pictures.fetch(config_path, ...)        the whole step; returns {"mmproj", "vision", "fetched", "note"}
9
10The file lives in ``<data folder>/models/`` beside the model files of that data folder (the place setup uses), shared by every model of
11the folder. The data folder is the one the model's own run config names (``--pack <data>/packs/<tag>``, strata_control/discovery.py
12``data_dir_of``), not the app's models folder. A copy that is already on this computer is used where it is: in that data folder, in the
13model's own folder, or one folder up from it (the layout of the Hugging Face repository).
14
15Only an explicit command reaches the network (strata_control/acquisition.py). With no internet the answer is the plain sentence of
16``PicturesError`` (code ``offline``) after one short probe, never a stalled bar. The apps/host caller then loads the model without
17pictures and says so.
18
19``python -c "...; pictures.main(sys.argv[1:])"`` is how the app runs it: ``fetch --config FILE --engine-dir DIR --vision yes ...``
20with ``--output jsonl`` (one JSON line per progress step, a last line ``{"ok": true, "event": "result", ...}`` or ``{"ok": false, "error": ...}``).
21"""
22
23from __future__ import annotations
24
25import argparse
26import json
27import os
28import re
29import shutil
30import sys
31import threading
32from dataclasses import dataclass
33from pathlib import Path
34from typing import Callable
35
36from strata_control import acquisition, discovery, transfer, vision_reader
37
38Progress = Callable[[str, int, int], None]    # (step in plain words, bytes done, bytes total)
39
40HF_DEFAULT = "https://huggingface.co"
41#: What a card of this kind needs for the picture reader (setup.py VISION): the images one picture becomes, and the CPU reader's thread cap.
42MAX_TOKENS = {"gpu": 1024, "cpu": 300}
43THREADS_CAP = 16
44#: Room kept beyond the file itself: the download is written next to its final place and then renamed.
45SPARE_BYTES = 256 * 1024 * 1024
46
47
48class PicturesError(RuntimeError):
49    """The picture files could not be had. ``code`` is for the caller, the message is plain words for the person."""
50
51    def __init__(self, code: str, message: str, details: str = ""):
52        super().__init__(message)
53        self.code = code
54        self.details = details                        # the technical cause, for a "Details" area; never the message
55
56
57@dataclass(frozen=True)
58class Projector:
59    """One pinned picture-reader file: the repository revision it comes from, its exact size and SHA-256."""
60
61    name: str
62    size: int
63    sha256: str
64    repo: str
65    revision: str
66
67    def url(self, endpoint: str | None = None) -> str:
68        base = (endpoint if endpoint is not None else (os.environ.get("HF_ENDPOINT") or "").strip().rstrip("/") or HF_DEFAULT)
69        return f"{base}/{self.repo}/resolve/{self.revision}/{self.name}"
70
71
72#: The same files and revisions as setup.py (ISTA_FILES, SWIFT_FILES, HF_REVISIONS); tests/terminal/test_pictures.py keeps the two the same.
73QWEN = Projector("mmproj-Qwen3.8-Flash-Next-BF16.gguf", 907543008, "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0",
74                 "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "ed59f92082b1e93c0e96d60a8b11aab089b52f09")
75SWIFT = Projector("mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf", 907543520, "cd1140f4abba943ce8d9fa92fed8407e389954d26907efde7b72153c75bd8a60",
76                  "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "99bb8f7f95c7aa7b24a36a7786a4f657b30f5d3d")
77#: The families whose weights are a GGUF shard set read by the Flash-Next engine: the original, its Coder, Unsloth's and Gyro's files all use the
78#: original's picture reader. NVFP4 ready-made packs, Qwen3.6 (its own engine path) and DeepSeek (its own picture tower) are not handled here.
79PROJECTOR_BY_FAMILY = {"qwen": QWEN, "coder": QWEN, "unsloth": QWEN, "gyro": QWEN, "swift": SWIFT}
80FAMILIES = tuple(PROJECTOR_BY_FAMILY)
81
82WORDS = {
83    "offline": "There is no internet connection, so the picture files can't be downloaded now.",
84    "disk": "There is not enough free disk space for the picture files (about 1 GB).",
85    "failed": "The picture files could not be downloaded.",
86    "checksum": "The downloaded picture files did not pass the safety check, so they were deleted.",
87    "unsupported": "This model's picture files are not downloaded by this step.",
88    "no_reader": "This engine has no picture reader.",
89    "no_folder": "Strata could not tell which folder this model's files are in.",
90    "no_config": "The model's settings file could not be read.",
91}
92
93
94# -------------------------------------------------------------------------------------------------------- what and where
95
96def family_of(cfg: dict, gguf: Path | None, asked: str | None = None) -> str | None:
97    """The family whose picture file this model uses; None for one this step does not handle. ``asked`` is the catalog's family (the app knows it);
98    without it the model's own file name and name decide (Swift's files are called Swift-..., Qwen3.6's start with Qwen3.6)."""
99    if asked:
100        return asked.lower() if asked.lower() in PROJECTOR_BY_FAMILY else None
101    arch = str(cfg.get("arch") or "").lower()
102    names = [str(cfg.get("model_name") or "").lower(), (gguf.name.lower() if gguf else "")]
103    from strata_control import retired
104    if retired.config_reason(cfg) or any("deepseek" in n for n in names):      # never a DeepSeek config (retired.py)
105        return None
106    if any(n.startswith("qwen3.6") or "qwen3.6-35b" in n for n in names):
107        return None
108    if any(n.startswith("swift") for n in names):
109        return "swift"
110    return "qwen"
111
112
113def run_folder(foot: "discovery.Footprint") -> Path | None:
114    """The data folder the model really lives in, from its own run config: the folder that holds its ``packs/<tag>`` (or its ``mtp/rt``, or the
115    ``models/<tag>`` its files are in). A pack or draft layer in a folder of another shape says nothing about it."""
116    def above(path: Path | None, child: str, name: str | None = None) -> Path | None:
117        if path is None:
118            return None
119        if name is not None and path.name.lower() != name:
120            return None
121        return path.parent.parent if path.parent.name.lower() == child else None
122    found = above(foot.pack, "packs") or above(foot.mtp, "mtp", "rt")
123    if found is not None:
124        return found
125    for w in foot.weights:
126        for parent in w.parents:
127            if parent.name.lower() == "models":
128                return parent.parent
129    return None
130
131
132def models_root(data: Path) -> Path:
133    """``<data>/models`` (``Models`` where that is what the folder has, as on Linux with an older install)."""
134    for name in ("models", "Models"):
135        if (data / name).is_dir():
136            return data / name
137    return data / "models"
138
139
140def places(data: Path | None, gguf: Path | None, named: str | None, projector: Projector) -> list[Path]:
141    """Where a copy of the file may already be: the path the run config names, the data folder's models folder, the model's own folder and the
142    folder above it (the Hugging Face repository layout keeps the picture file beside the size folders)."""
143    out: list[Path] = []
144    if named:
145        out.append(Path(named))
146    if data is not None:
147        out.append(models_root(data) / projector.name)
148    if gguf is not None:
149        out += [gguf.parent / projector.name, gguf.parent.parent / projector.name]
150    seen: set[str] = set()
151    unique = []
152    for p in out:
153        key = os.path.normcase(str(p))
154        if key not in seen:
155            seen.add(key)
156            unique.append(p)
157    return unique
158
159
160def _mark(path: Path) -> Path:
161    return path.with_name(path.name + ".done")
162
163
164def _marked(path: Path, projector: Projector) -> bool:
165    try:
166        return f"sha256 {projector.sha256}" in _mark(path).read_text(encoding="utf-8", errors="replace")
167    except OSError:
168        return False
169
170
171def whole(path: Path, projector: Projector, report: Progress | None = None) -> bool:
172    """Is this the pinned file, whole? Size first, then the finish mark setup leaves, else the hash (a few seconds; the file is not changed)."""
173    try:
174        if not path.is_file() or path.stat().st_size != projector.size:
175            return False
176        if _marked(path, projector):
177            return True
178        if report:
179            report("Checking the picture files…", 0, projector.size)
180        return transfer.sha256_file(path) == projector.sha256
181    except OSError:
182        return False
183
184
185def find(candidates: list[Path], projector: Projector, report: Progress | None = None) -> Path | None:
186    for path in candidates:
187        if whole(path, projector, report):
188            return path
189    return None
190
191
192def target_for(data: Path | None, named: str | None, projector: Projector) -> Path:
193    """Where a download goes: the place the run config already names when its folder is there, else the data folder's models folder."""
194    if named:
195        p = Path(named)
196        if p.parent.is_dir():
197            return p
198    if data is None:
199        raise PicturesError("no_folder", WORDS["no_folder"])
200    return models_root(data) / projector.name
201
202
203def _room(folder: Path, need: int) -> None:
204    above = folder
205    while not above.exists() and above.parent != above:
206        above = above.parent
207    try:
208        free = shutil.disk_usage(above).free
209    except OSError:
210        return                                            # cannot tell: go on, the download reports a real failure
211    if free < need + SPARE_BYTES:
212        raise PicturesError("disk", WORDS["disk"], f"{free / 1e9:.1f} GB are free in {above}")
213
214
215# ----------------------------------------------------------------------------------------------------------- the reader
216
217def _numbers(value) -> list[int]:
218    if value is None or value == "":
219        return []
220    parts = list(value) if isinstance(value, (list, tuple, set)) else re.split(r"[;,\s]+", str(value))
221    out = []
222    for part in parts:
223        m = re.search(r"\d+", str(part))
224        if m:
225            out.append(int(m.group(0)))
226    return sorted(set(out))
227
228
229def _build(engine_dir: Path) -> dict:
230    try:
231        data = json.loads((engine_dir / "BUILD.json").read_text(encoding="utf-8-sig"))
232        return data if isinstance(data, dict) else {}
233    except (OSError, ValueError):
234        return {}
235
236
237def _reader_archs(engine_dir: Path) -> list[str]:
238    for name, keys in (("BUILD.json", ("vision_archs", "archs")), ("engine-component.json", ("archs",))):
239        try:
240            data = json.loads((engine_dir / name).read_text(encoding="utf-8-sig"))
241        except (OSError, ValueError):
242            continue
243        for key in keys:
244            if isinstance(data, dict) and data.get(key):
245                value = data[key]
246                parts = list(value) if isinstance(value, (list, tuple, set)) else re.split(r"[;,\s]+", str(value))
247                names = [str(p) for p in parts if str(p)]
248                if names:
249                    return names
250    return []
251
252
253def threads(logical: int | None = None) -> int:
254    return max(1, min((logical if logical is not None else (os.cpu_count() or 8)) // 2, THREADS_CAP))
255
256
257def reader_section(engine_dir: Path, mmproj: Path, gguf: Path, asked: str, hardware: dict | None = None, previous: dict | None = None) -> tuple[dict | None, str]:
258    """The run config's ``vision`` section for this engine folder and card, and one plain note when it is not what was asked for.
259    The same rule as setup (strata_control/vision_reader.py is the one place): the CPU reader under 24 GB of VRAM, the GPU reader from 24 GB; AMD and
260    Intel Arc get their GPU reader with the CPU one behind it; a Mac has one program for both. (None, note) when the folder has no reader at all."""
261    hw = hardware or {}
262    make = str(hw.get("make") or "").lower()
263    mac = make == "apple" or sys.platform == "darwin"
264    windows = os.name == "nt"
265    wanted = vision_reader.wanted(asked, hw.get("vram_gb"), make, unified=mac)
266    if wanted == "none":
267        return None, ""
268    have = vision_reader.find(engine_dir, windows, mac=mac)
269    arch = hw.get("arch")
270    if mac:
271        reader = vision_reader.choose(engine_dir, wanted, windows=False, mac=True)
272    elif have["gpu"] is not None:
273        reader = vision_reader.choose(engine_dir, wanted, windows=windows, gpu_arch=str(arch or ""), archs=_reader_archs(engine_dir))
274    elif have["cpu"] is not None:
275        mode, note = wanted, ""
276        if mode == "gpu":                                        # the ready-made reader may cover fewer cards than the engine (setup.py prebuilt_vision)
277            build = _build(engine_dir)
278            built = _numbers(build.get("vision_archs", build.get("archs")))
279            try:
280                sm = int(arch)
281            except (TypeError, ValueError):
282                sm = None
283            if built and sm is not None and sm not in built and not (build.get("ptx") and sm > max(built)):
284                mode, note = "cpu", f"the picture reader has no code for your card (sm_{sm}): pictures are read on the CPU (a few seconds each)"
285        reader = vision_reader.Reader(mode, have["cpu"], note=note)
286    else:
287        reader = vision_reader.Reader("none", note="this engine has no picture reader: pictures off")
288    if reader.mode == "none" or reader.exe is None:
289        return None, reader.note or WORDS["no_reader"]
290    earlier = (previous or {}).get("max_tokens")
291    same_device = bool((previous or {}).get("gpu")) == (reader.mode == "gpu")
292    tokens = int(earlier) if isinstance(earlier, int) and earlier > 0 and same_device else MAX_TOKENS[reader.mode]
293    base = {"exe": str(reader.exe), "mmproj": str(mmproj), "model": str(gguf), "gpu": reader.mode == "gpu", "max_tokens": tokens}
294    section = vision_reader.vision_section(reader, base)
295    if reader.mode == "cpu":
296        section["threads"] = threads()
297    return section, reader.note
298
299
300# ------------------------------------------------------------------------------------------------------------- the step
301
302def fetch(config_path: str | Path, *, engine_dir: str | Path, asked: str = "yes", data_dir: str | Path | None = None, family: str | None = None,
303          hardware: dict | None = None, progress: Progress | None = None, cancel: threading.Event | None = None,
304          endpoint: str | None = None, online: Callable[[str], bool] | None = None) -> dict:
305    """Make sure this model has its picture file and say what its ``vision`` section is.
306
307    Returns {"mmproj": path, "vision": section | None, "fetched": bool, "note": str, "data_dir": path, "family": name}. Raises PicturesError. Nothing of the
308    model changes; the only file written is the picture file (and its finish mark) when it was downloaded."""
309    report = progress or (lambda *_: None)
310    config = Path(config_path)
311    try:
312        cfg = json.loads(config.read_text(encoding="utf-8-sig"))
313        if not isinstance(cfg, dict):
314            raise ValueError("not an object")
315    except (OSError, ValueError):
316        raise PicturesError("no_config", WORDS["no_config"]) from None
317    foot = discovery.footprint(cfg, config)
318    gguf = foot.weights[0] if foot.weights else None
319    name = family_of(cfg, gguf, family)
320    projector = PROJECTOR_BY_FAMILY.get(name) if name else None
321    if projector is None or gguf is None:
322        raise PicturesError("unsupported", WORDS["unsupported"])
323    data = run_folder(foot) or (Path(data_dir) if data_dir else None)
324    if data is None and gguf is not None:
325        data = discovery.prepared_beside(gguf).get("data_dir")
326    vision_now = cfg.get("vision") if isinstance(cfg.get("vision"), dict) else None
327    named = str(vision_now["mmproj"]) if vision_now and vision_now.get("mmproj") else None
328    found = find(places(data, gguf, named, projector), projector, report)
329    fetched = False
330    if found is None:
331        out = target_for(data, named, projector)
332        acquisition.require("the picture files", "Load in the app, or strata install")
333        url = projector.url(endpoint)
334        _room(out.parent, projector.size)
335        if not (online or _online)(url):
336            raise PicturesError("offline", WORDS["offline"])
337        out.parent.mkdir(parents=True, exist_ok=True)
338        partial = out.with_name(out.name + ".part")
339        try:
340            transfer.download(url, partial, size=projector.size, sha256=projector.sha256, cancel=cancel, what="the picture reader",
341                              progress=lambda d, s: report("Downloading the picture files…", d, s))
342        except transfer.ChecksumMismatch:
343            raise PicturesError("checksum", f"{WORDS['checksum']} Try again.") from None
344        except transfer.Cancelled:
345            raise
346        except (transfer.TransferError, OSError) as exc:
347            raise PicturesError("failed", f"{WORDS['failed']} Try again; it continues where it stopped.", str(exc)) from None
348        os.replace(partial, out)
349        try:
350            _mark(out).write_text(f"sha256 {projector.sha256}", encoding="utf-8")
351        except OSError:
352            pass                                                  # the mark only saves a second hashing
353        found, fetched = out, True
354    section, note = reader_section(Path(engine_dir), found, gguf, asked, hardware, vision_now)
355    if section is None:
356        raise PicturesError("no_reader", note or WORDS["no_reader"])
357    report("The picture files are ready.", projector.size, projector.size)
358    return {"mmproj": str(found), "vision": section, "fetched": fetched, "note": note, "data_dir": str(data) if data else None, "family": name}
359
360
361def _online(url: str) -> bool:
362    from strata_control import drafting_fetch                    # here: it pulls in the network code
363    return drafting_fetch.online(url)
364
365
366# ------------------------------------------------------------------------------------------------------------ the command
367
368def main(argv: list[str]) -> int:
369    ap = argparse.ArgumentParser(prog="pictures")
370    sub = ap.add_subparsers(dest="command", required=True)
371    one = sub.add_parser("fetch")
372    one.add_argument("--config", required=True)
373    one.add_argument("--engine-dir", required=True)
374    one.add_argument("--vision", default="yes", choices=("yes", "gpu", "cpu"))
375    one.add_argument("--data-dir")
376    one.add_argument("--family")
377    one.add_argument("--vram-gb", type=float)
378    one.add_argument("--make")
379    one.add_argument("--arch")
380    a = ap.parse_args(argv)
381    cancel = threading.Event()
382
383    def emit(obj: dict) -> None:
384        sys.stdout.write(json.dumps(obj) + "\n")
385        sys.stdout.flush()
386
387    last = {"step": "", "pct": -1}
388
389    def show(step: str, done: int, total: int) -> None:
390        pct = int(100 * done / total) if total else 0
391        if step == last["step"] and pct == last["pct"]:
392            return
393        last["step"], last["pct"] = step, pct
394        emit({"event": "progress", "step": step, "done": done, "total": total})
395
396    hardware = {"vram_gb": a.vram_gb, "make": a.make, "arch": a.arch}
397    try:
398        result = fetch(a.config, engine_dir=a.engine_dir, asked=a.vision, data_dir=a.data_dir, family=a.family, hardware=hardware, progress=show, cancel=cancel)
399    except PicturesError as exc:
400        emit({"ok": False, "error": {"code": exc.code, "message": str(exc), "details": exc.details}})
401        return 5
402    except acquisition.AcquisitionRefused as exc:
403        emit({"ok": False, "error": {"code": "acquisition_refused", "message": str(exc)}})
404        return 5
405    except transfer.Cancelled:
406        emit({"ok": False, "error": {"code": "cancelled", "message": "Stopped. The part that was downloaded is kept."}})
407        return 130
408    emit({"ok": True, "event": "result", **result})
409    return 0
410
411
412if __name__ == "__main__":                                       # pragma: no cover
413    sys.exit(main(sys.argv[1:]))