okami.mom/strata

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

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

main
19.7 KiB368 linesraw
1"""The model list in the signed update feed (feed member ``models``): the cache of the last verified list, and how a feed model becomes a catalog entry.
2
3A new model can ship as a signed feed update, with no new Control package. The feed carries, for each model, the Hugging Face repository at a pinned revision,
4every file's exact size and SHA-256, the engine family, the licence and the first engine version that reads it (strata_control/feed.py ``FeedModel``). Setup, the
5Terminal's `strata launch` and the app read the SAME tables (setup.py's MODELS / FAMILIES / OWN_PATH_FAMILIES), so a feed model is added to those tables here and
6every screen shows it after the built-in ones. It then goes through the code a built-in model goes through: the same pins (REPO_PINS / REV_PINS, HF_REVISIONS), the
7same SHA-256 check after the download and the same ``.bad`` handling (setup.py ``download`` / ``verify_sha256`` / ``keep_bad``).
8
9Rules:
10
11* With no ``models`` member in the feed (and no cached one) nothing here changes anything: no table is touched, nothing is written.
12* A model whose family the installed engine does not run (``strata --families``) is listed as not available on this engine and is never offered to install.
13* Offline, the models of the last feed that verified are shown (the signature is checked again when the cache is read).
14* A model that would clash with a built-in one (an id, a tag, a file name pinned to other bytes) is left out with a log line; a built-in model is never replaced.
15"""
16
17from __future__ import annotations
18
19import base64
20import json
21import logging
22import os
23import re
24import tempfile
25from dataclasses import dataclass, field
26from pathlib import Path
27
28from strata_control import feed as feedmod, shape_engine
29
30_log = logging.getLogger("strata.feed")
31
32CACHE_NAME = "feed-models.json"
33ENV_OFF = "STRATA_FEED_MODELS"             # "0": setup and the screens do not read or fetch the feed's model list (tests, a locked-down PC)
34FETCH_TIMEOUT = 5.0
35
36# ---- the words a person can see (agreed with the coordinator before they ship)
37UNAVAILABLE_ENGINE = "needs a newer Strata engine: update Strata to use it"
38UNAVAILABLE_UNKNOWN = "this Strata version doesn't know this model yet: update Strata to use it"
39
40
41#: What happens to a model whose family the installed engine does not run (the owner decides; a one-line switch):
42#:   "not_offered": it is listed as not available and never offered to install;
43#: (owner, 11-06: "warn_allow", his standing rule: warn plainly, still allow the download, never refuse)
44#:   "warn_allow":  it is offered like any other model with the same sentence as a warning, and the install goes on (a family this Control does not know is still not offered).
45UNAVAILABLE_POLICY = "warn_allow"
46
47
48def unavailable_reason(family: str) -> str:
49    """The sentence a person sees. The family name is not part of it (support finds it in the log line)."""
50    return UNAVAILABLE_ENGINE if family in feedmod.MODEL_FAMILIES_INSTALLABLE else UNAVAILABLE_UNKNOWN
51
52
53# ---------------------------------------------------------------------------------------------------- the cache of the last verified list
54
55def cache_file(root: str | os.PathLike | None = None) -> Path:
56    """``<components>/.updates/feed-models.json``, beside the updater's state (STRATA_COMPONENTS_DIR moves both)."""
57    from strata_control import engine_component, updater
58    return updater.updates_dir(Path(root) if root else engine_component.components_dir()) / CACHE_NAME
59
60
61def remember(feed: feedmod.Feed, root: str | os.PathLike | None = None) -> None:
62    """Keep the signed feed document that carried a model list, so the list can be shown offline. A feed without models removes an older cache (the list was withdrawn);
63    when there is no cache and no models, nothing is written. Never raises: a read-only folder just means no offline list."""
64    try:
65        path = cache_file(root)
66        if not feed.models:
67            if path.is_file():
68                path.unlink()
69            return
70        if not feed.signature:
71            return
72        doc = {"schema_version": 1, "sequence": feed.sequence, "channel": feed.channel, "source": feed.source,
73               "payload": base64.b64encode(feed.raw).decode("ascii"), "signature": base64.b64encode(feed.signature).decode("ascii")}
74        path.parent.mkdir(parents=True, exist_ok=True)
75        descriptor, temp = tempfile.mkstemp(prefix=".feed-models-", suffix=".tmp", dir=path.parent)
76        try:
77            with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
78                json.dump(doc, stream)
79            os.replace(temp, path)
80        finally:
81            if os.path.exists(temp):
82                os.unlink(temp)
83    except OSError as exc:
84        _log.warning("the model list of the update feed could not be kept for offline use: %s", exc)
85
86
87def _read_cache(root, trusted: dict) -> feedmod.Feed | None:
88    """The cached feed, its signature checked again against the trusted keys (a cache file edited by hand is worth nothing). Expiry is not applied: the list of an old
89    feed is what an offline PC has. None when there is no cache or it does not verify."""
90    from strata_control import signing
91    try:
92        doc = json.loads(cache_file(root).read_text(encoding="utf-8"))
93        payload = base64.b64decode(doc["payload"], validate=True)
94        signature = base64.b64decode(doc["signature"], validate=True)
95        key_id = signing.verify_bytes(trusted, payload, json.loads(signature.decode("utf-8-sig")))
96        return feedmod.parse(payload, source="cache", key_id=key_id)
97    except (OSError, ValueError, KeyError, TypeError, signing.SignatureError, feedmod.FeedError):
98        return None
99
100
101@dataclass
102class Loaded:
103    models: tuple = ()
104    dropped: tuple = ()
105    via: str = "none"                   # "feed" (read now), "cache" (the last verified list) or "none"
106    sequence: int | None = None
107    notes: list = field(default_factory=list)
108
109
110def load(source: str | None = None, *, fetch: bool = True, root=None, trusted: dict | None = None, timeout: float = FETCH_TIMEOUT,
111         say=None) -> Loaded:
112    """The feed's models: the feed itself when it can be read now (and verifies, and is not older than the cached one), else the cache. Silent either way:
113    nothing is printed and no error is raised. ``fetch=False`` reads the cache only (the Terminal and app lists)."""
114    if os.environ.get(ENV_OFF, "").strip() == "0":
115        return Loaded()
116    from strata_control import signing
117    try:
118        trusted = trusted if trusted is not None else signing.load_trusted_keys()
119    except Exception:                                    # noqa: BLE001 - a build without keys has no verified list
120        return Loaded()
121    if not trusted:
122        return Loaded()
123    cached = _read_cache(root, trusted)
124    if fetch and source:
125        try:
126            got = feedmod.fetch(source, trusted, timeout=timeout, channel="stable", last_sequence=cached.sequence if cached else None,
127                                say=say)
128        except feedmod.FeedError as exc:                 # offline, expired, a downgrade, a bad signature: the last verified list stays
129            _log.info("the update feed's model list could not be refreshed: %s", exc)
130        except Exception as exc:                         # noqa: BLE001
131            _log.info("the update feed's model list could not be refreshed: %s", exc)
132        else:
133            remember(got, root)
134            return Loaded(models=got.models, dropped=got.models_dropped, via="feed", sequence=got.sequence)
135    if cached is not None and cached.models:
136        return Loaded(models=cached.models, dropped=cached.models_dropped, via="cache", sequence=cached.sequence)
137    return Loaded()
138
139
140# ---------------------------------------------------------------------------------------------------- feed model -> catalog entry
141
142class _ByQuant(str):
143    """A catalog string that depends on the size: ``fam["file"].format(q=quant)`` and ``fam["hf"].format(q=quant)`` are how the built-in code asks for a
144    file name or a download folder; the feed names each size's files explicitly, so the answer comes from a table."""
145
146    def __new__(cls, table: dict):
147        obj = super().__new__(cls, next(iter(table.values()), ""))
148        obj.table = dict(table)
149        return obj
150
151    def format(self, *args, **kw):                       # noqa: A003 - the override is the point
152        return self.table[kw["q"]]
153
154
155def _template(names: list[str]) -> str | None:
156    """The ``file`` template (``{i}`` the shard number, 1 to 9) that gives exactly these names in order, or None."""
157    if len(names) == 1:
158        return names[0] if not re.search(r"[{}]", names[0]) else None
159    if len(names) > 9 or any(re.search(r"[{}]", n) for n in names):
160        return None
161    first = names[0]
162    if "-00001-of-" not in first:
163        return None
164    tpl = first.replace("-00001-of-", "-0000{i}-of-")
165    return tpl if [tpl.format(i=i) for i in range(1, len(names) + 1)] == names else None
166
167
168def _engine_tuple(version: str) -> tuple | None:
169    """setup.py's engine versions are 3-tuples (0, 1, 57); a fourth number only when the feed's version has one."""
170    if not version:
171        return None
172    key = feedmod.version_key(version)
173    return key if key[3] else key[:3]
174
175
176def _endpoint(setup) -> str:
177    """The model host setup downloads from (a mirror when the person set one), read off setup's own url builder so this module names no host."""
178    repo = next(iter(setup.HF_REVISIONS))
179    return setup.hf(repo).split(f"/{repo}/resolve/")[0]
180
181
182def _urlbase(repo: str, revision: str, endpoint: str) -> str:
183    return f"{endpoint}/{repo}/resolve/{revision}/"
184
185
186@dataclass
187class Applied:
188    registered: list = field(default_factory=list)       # ids now in setup's tables
189    unavailable: dict = field(default_factory=dict)      # id -> {"title", "by", "family", "reason"}
190    skipped: list = field(default_factory=list)          # plain lines, one for each model left out (also logged)
191
192
193def _skip(result: Applied, model, why: str) -> None:
194    line = f"The update feed's model {model.id!r} is left out: {why}"
195    result.skipped.append(line)
196    _log.warning(line)
197
198
199def _taken_tags(setup) -> list[str]:
200    tags = [d.get("tag", "") for d in (*setup.FAMILIES.values(), *setup.OWN_PATH_FAMILIES.values())]
201    return [t for t in tags if t]
202
203
204def apply(setup, models, engine_families=None) -> Applied:
205    """Add the feed's models to setup's tables (``setup`` is the setup.py module). ``engine_families``: the set ``strata --families`` printed for the installed
206    engine, or None when no engine is installed to ask (then every installable family is offered and setup checks the engine when it installs, as for any model).
207    Safe to call again with the same list: a model already added is skipped quietly. Built-in entries are never replaced."""
208    result = Applied()
209    if not models:
210        return result
211    done_before = getattr(setup, "FEED_MODELS", None)
212    if done_before is None:
213        done_before = setup.FEED_MODELS = {}
214        setup.FEED_UNAVAILABLE = {}
215    for model in models:
216        if model.id in done_before:
217            if model.id not in setup.FEED_UNAVAILABLE:
218                result.registered.append(model.id)
219            continue
220        if model.id in setup.FAMILIES or model.id in setup.OWN_PATH_FAMILIES:
221            _skip(result, model, "its id is the name of a built-in model")
222            continue
223        tag = model.id + "-"
224        if any(t.startswith(tag) or tag.startswith(t) for t in _taken_tags(setup)):
225            _skip(result, model, "its name would be mistaken for a built-in model's files")
226            continue
227        shape = model.shape
228        known = model.family in feedmod.MODEL_FAMILIES_INSTALLABLE or shape is not None
229        # a model of its own shape runs on that shape's engine, which setup fetches when the model is chosen (strata_control/shape_engine.py): the Strata engine's families do not decide
230        runs = known and (shape is not None or engine_families is None or model.family in engine_families)
231        if not runs:
232            allowed = known and UNAVAILABLE_POLICY == "warn_allow"
233            reason = unavailable_reason(model.family)
234            _log.info("feed model %s: family %s is not run by the installed engine (%s); policy %s", model.id, model.family,
235                      "unknown to this Control" if not known else "engine families " + ",".join(sorted(engine_families or ())), UNAVAILABLE_POLICY)
236            setup.FEED_UNAVAILABLE[model.id] = {"title": model.title, "by": model.by, "family": model.family, "reason": reason, "allowed": allowed}
237            result.unavailable[model.id] = setup.FEED_UNAVAILABLE[model.id]
238            if not allowed:
239                done_before[model.id] = model
240                continue
241        try:
242            (_own_path if model.family == "qwen35moe" else _flash_next)(setup, model)
243        except _Unsupported as exc:
244            _skip(result, model, str(exc))
245            continue
246        done_before[model.id] = model
247        result.registered.append(model.id)
248    return result
249
250
251class _Unsupported(Exception):
252    pass
253
254
255def _check_pins(setup, model) -> dict:
256    """The model's files as setup pins them: name -> (size, sha256). A file name that setup already pins to other bytes (the picture reader is one file shared by
257    several models) refuses the model rather than replace the pin."""
258    pins: dict = {}
259    for quant in model.quants:
260        for f in quant.files:
261            pins[f.name] = (f.size, f.sha256)
262    if model.mmproj is not None:
263        pins[model.mmproj.name] = (model.mmproj.size, model.mmproj.sha256)
264        for repo_pins in setup.REPO_PINS.values():
265            known = repo_pins.get(model.mmproj.name)
266            if known and tuple(known) != pins[model.mmproj.name]:
267                raise _Unsupported("its picture reader file has the name of another model's, with other bytes")
268    return pins
269
270
271def _pin_repo(setup, model, pins: dict) -> str:
272    """Register the revision and the file pins where setup's download looks them up (file_pin: REV_PINS first), and return the download folder."""
273    setup.REV_PINS.setdefault((model.repo, model.revision), {}).update(pins)
274    setup.HF_REVISIONS.setdefault(model.repo, model.revision)
275    return _urlbase(model.repo, model.revision, _endpoint(setup))
276
277
278def _licence(model) -> str:
279    return f"{model.licence}: {model.licence_url}"
280
281
282def _dirs(model) -> set[str]:
283    return {f.repo_path.rpartition("/")[0] for q in model.quants for f in q.files}
284
285
286def _flash_next(setup, model) -> None:
287    """A qwen4exp model: the family and size tables the Unsloth sets use (GGUF shards in the repository, packed on this PC), one MODELS entry for each size."""
288    template = setup.FAMILIES.get("unsloth") or {}
289    names_by_quant = {q.name: [f.name for f in q.files] for q in model.quants}
290    files = {}
291    for qname, names in names_by_quant.items():
292        tpl = _template(names)
293        if tpl is None:
294            raise _Unsupported(f"the files of {qname} are not a single file or numbered parts 00001-of-0000N")
295        files[qname] = tpl
296    pins = _check_pins(setup, model)
297    base = _pin_repo(setup, model, pins)
298    folders = {q.name: (q.files[0].repo_path.rpartition("/")[0] + "/" if q.files[0].repo_path.rpartition("/")[0] else "") for q in model.quants}
299    keys = {}
300    for q in model.quants:
301        key = q.name if q.name not in setup.MODELS and q.name not in keys.values() else f"{q.name}-{model.id}"
302        if key in setup.MODELS or key in keys.values():
303            raise _Unsupported(f"the size name {q.name} clashes with a built-in size")
304        keys[q.name] = key
305    fam = {"title": model.title, "by": model.by, "about": model.about, "hf": _ByQuant({q: base + folders[q] for q in files}),
306           "file": _ByQuant(files), "shards": 2, "tag": model.id + "-", "name": model.id, "vision": bool(model.pictures),
307           "pack_args": list(template.get("pack_args", ["--compat-bf16"])), "sha256": dict(pins), "license": _licence(model), "feed": True,
308           "drafter": model.drafter}
309    if model.mmproj is not None:
310        fam.update(mmproj_hf=base + (model.mmproj.repo_path.rpartition("/")[0] + "/" if "/" in model.mmproj.repo_path else ""),
311                   mmproj=model.mmproj.name, mmproj_sha256=(model.mmproj.size, model.mmproj.sha256))
312    else:
313        fam.update(vision=False)
314    engine = _engine_tuple(model.min_engine)
315    # nothing is added to the shared tables until every check above has passed
316    for q in model.quants:
317        gb = round(q.download_bytes / 1e9, 1)
318        entry = {"about": q.about or f"{q.name} quantization", "download_gb": gb, "ram_gb": q.ram_gb,
319                 "arena_gb": q.arena_gb or round(gb * 0.93, 1), "families": (model.id,), "shards": len(q.files),
320                 "file": files[q.name], "quant": q.name, "vision": bool(model.pictures)}
321        entry["budget"] = True                           # the Unsloth-set install: the GGUF read in place with a RAM budget of its experts (what the built-in UD sizes do). Without it
322                                                         # setup picks the low-RAM mode on a PC with little RAM, which copies all the experts into a second file (77 GB for UD-Q4_K_XL)
323        if engine:
324            entry["engine"] = engine
325        setup.MODELS[keys[q.name]] = entry
326    if model.shape:                                      # its own engine: the run config names it, setup fetches it (strata_control/shape_engine.py)
327        fam["shape"] = model.shape
328        for key in keys.values():                        # its min_engine is about that engine, which the feed carries: the app must not compare it with the Strata engine
329            setup.MODELS[key].pop("engine", None)
330    setup.FAMILIES[model.id] = fam
331    _mac_entries(model, keys)
332
333
334def _mac_entries(model, keys: dict) -> None:
335    """The Mac (Metal) tables: a size of one or two files is offered like the Qwen GSQ-RCO sizes (no repack), "not measured on a Mac". More files: not offered on a Mac."""
336    try:
337        from strata_control import mac_fit
338    except Exception:                                    # noqa: BLE001
339        return
340    if any(len(q.files) > 2 for q in model.quants):
341        return
342    for q in model.quants:
343        key = keys[q.name]
344        mac_fit.MAC_MODELS[key] = {"shard1_gb": round(q.download_bytes / 1e9, 1), "tested": False, "family": model.id, "shards": len(q.files), "no_mtp": model.drafter == "none"}
345        mac_fit.MAC_ABOUT[key] = q.about or f"{q.name} quantization"
346    if model.id not in mac_fit.FEED_FAMILIES:
347        mac_fit.FEED_FAMILIES.append(model.id)
348
349
350def _own_path(setup, model) -> None:
351    """A qwen35moe model: the Qwen3.6-35B-A3B install path (one GGUF, read in place by the engine). One file for each size, all in one folder."""
352    if any(len(q.files) != 1 for q in model.quants):
353        raise _Unsupported("this install path takes one file for each size")
354    if len(_dirs(model)) != 1:
355        raise _Unsupported("this install path takes all sizes from one folder of the repository")
356    if model.mmproj is not None and model.mmproj.repo_path.rpartition("/")[0] != next(iter(_dirs(model))):
357        raise _Unsupported("the picture reader is not in the folder of the model files")
358    names = {q.name: q.files[0].name for q in model.quants}
359    pins = _check_pins(setup, model)
360    base = _pin_repo(setup, model, pins)
361    folder = next(iter(_dirs(model)))
362    base = base + (folder + "/" if folder else "")
363    fam = {"title": model.title, "by": model.by, "arch": "qwen35moe", "about": model.about, "hf": base, "file": _ByQuant(names), "tag": model.id + "-",
364           "mmproj_hf": base, "mmproj": model.mmproj.name if model.mmproj else "", "name": model.id, "license": _licence(model),
365           "models": {q.name: {"about": q.about or f"{q.name} quantization", "ram_gb": q.ram_gb} for q in model.quants},
366           "sha256": dict(pins), "kv_bytes_per_token": model.kv_bytes_per_token, "mtp": model.mtp_drafts,
367           "vision": bool(model.pictures), "state_gb": model.state_gb, "feed": True}
368    setup.OWN_PATH_FAMILIES[model.id] = fam