okami.mom/strata

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

Niko1221drafting: the tuned-drafter lookup applies the update's accepted feed sequence1637559fd

main
24.8 KiB397 linesraw
1"""Getting the DFlash2 drafter onto this computer: a pinned download, checked against the repository's own SHA-256, packed for the engine.
2
3    strata drafting plan  [--data-dir DIR]      what it would download (nothing is changed)
4    strata drafting fetch [--data-dir DIR]      download, check, pack; progress in plain words
5
6Only an explicit command reaches the network (strata_control/acquisition.py): a start never downloads. The drafter is
7incoai/Qwen3.8-Flash-Next-DFlash2 at one revision (strata_control/drafting.py has the revision, the file sizes and hashes). The 1.2 GB
8safetensors file is packed (tools/dflash2_pack.py --q4_0, numpy only) into the engine's 0.52 GB runtime file, which is checked against its pinned size and
9SHA-256, and the download is then removed. A Q8 pack from an earlier Strata is used as it is.
10"""
11
12from __future__ import annotations
13
14import importlib.util
15import os
16import sys
17import threading
18import time
19import urllib.error
20import urllib.request
21from pathlib import Path
22from typing import Callable
23
24from strata_control import acquisition, drafting, transfer
25from strata_control import feed as feedmod
26
27Progress = Callable[[str, int, int], None]    # (step in plain words, bytes done, bytes total)
28
29
30class DraftingError(RuntimeError):
31    """The drafter could not be fetched or packed. The message is plain words and says what to do."""
32
33
34class OfflineError(DraftingError):
35    """The download address did not answer (no internet, or a host that is down). Setup skips this one silently: the model keeps the MTP (strata-offline-users)."""
36
37
38def plan(data_dir: str | Path, engine: str | os.PathLike[str] | None = None, *, model_name: str | None = None, backend: str | None = None, archs=None,
39         args: list | None = None, vram_mib: float | None = None) -> dict:
40    """What fetching would do, in numbers and words. ``gb`` is 0 when the drafter is already here. ``engine``: the installed engine program (None: not known); ``vram_gb`` is
41    the graphics memory DFlash2 alone takes on this computer (0.72 with the Q4_0 selector, which the engine reads and setup makes, else 0.89) and ``selq4`` says which.
42    For a set with a tuned drafter (drafting.SET_DEFAULTS) the download is that 0.34 GB file, and it counts as missing until it is here."""
43    tuned = drafting.tuned_applies(backend, model_name, archs, args=args, vram_mib=vram_mib)
44    variant = drafting.tuned_variant(backend, model_name)
45    pin = drafting.tuned_pack(variant)
46    ready = drafting.tuned_ok(data_dir, variant) if tuned else drafting.pack_ready(data_dir)
47    gb = 0.0 if ready else (pin.gb if tuned else drafting.DOWNLOAD_GB)
48    if ready:
49        text = "The DFlash2 drafter is already on this computer."
50    elif tuned:
51        text = (f"The DFlash2 drafter is {pin.gb:.2f} GB to download, from Strata's signed update feed, Apache-2.0 (a copy of {drafting.REPO} that Strata tuned). "
52                f"It needs about {drafting.vram_gb(data_dir, engine):.1f} GB of graphics memory, less than the MTP's layer, which is not loaded beside it.")
53    else:
54        text = (f"The DFlash2 drafter is {drafting.DOWNLOAD_GB:.1f} GB to download (it is packed to {drafting.PACK_GB:.2f} GB for the engine and the "
55                f"download is removed), from {drafting.REPO}, {drafting.LICENSE}. It needs about {drafting.vram_gb(data_dir, engine):.1f} GB of graphics memory, "
56                "less than the MTP's layer, which is not loaded beside it.")
57    return {"ready": ready, "gb": gb, "drafter_gb": pin.gb if tuned else drafting.DOWNLOAD_GB, "tuned": tuned, "file": pin.name if tuned else drafting.PACK_NAME,
58            "vram_gb": drafting.vram_gb(data_dir, engine), "selq4": drafting.uses_selector_q4(data_dir, engine), "pack": str(drafting.pack_path(data_dir, model_name=model_name, backend=backend)), "repo": drafting.REPO, "revision": drafting.REVISION, "text": text}
59
60
61def _packer():
62    """tools/dflash2_pack.py as a module: beside strata_control in a source checkout and in the packaged Control (TOOLS_SUBSET)."""
63    path = Path(__file__).resolve().parents[1] / "tools" / "dflash2_pack.py"
64    if not path.is_file():
65        raise DraftingError("The packing tool is missing from this installation. Update Strata, then try again.")
66    spec = importlib.util.spec_from_file_location("strata_dflash2_pack", path)
67    module = importlib.util.module_from_spec(spec)
68    sys.modules.setdefault("strata_dflash2_pack", module)
69    spec.loader.exec_module(module)
70    return module
71
72
73REACH_SECONDS = 6.0
74
75
76def online(url: str, timeout: float = REACH_SECONDS) -> bool:
77    """Does the download address answer at all? One short HEAD request, no retry: with no internet (or a connection that hangs) the person gets a plain
78    sentence in a few seconds instead of a stalled progress bar. Any answer from the server counts, even an error page."""
79    try:
80        transfer.check_url_policy(url)
81        request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-drafting/1"})
82        with transfer._opener.open(request, timeout=timeout):     # the download's own opener: same certificates, same redirect policy, same proxy settings
83            return True
84    except urllib.error.HTTPError:
85        return True
86    except (urllib.error.URLError, OSError, TimeoutError, ValueError, transfer.TransferError) as exc:
87        from strata_control import tls
88        return bool(tls.is_certificate_error(exc))        # a certificate problem is an answer: the download explains it in its own words
89
90
91def _hub_snapshots() -> list[Path]:
92    """Where the Hugging Face tools keep this repository's pinned revision, if the person already has it from them (nothing is created or changed)."""
93    roots: list[Path] = []
94    for name in ("HF_HUB_CACHE", "HUGGINGFACE_HUB_CACHE"):
95        if os.environ.get(name):
96            roots.append(Path(os.environ[name]))
97    if os.environ.get("HF_HOME"):
98        roots.append(Path(os.environ["HF_HOME"]) / "hub")
99    roots.append(Path.home() / ".cache" / "huggingface" / "hub")
100    return [r / ("models--" + drafting.REPO.replace("/", "--")) / "snapshots" / drafting.REVISION for r in roots]
101
102
103def _present(folders: list[Path], spec) -> dict[str, Path]:
104    """The pinned files that are already on this computer, found in these folders and checked against the repository's size and SHA-256."""
105    found: dict[str, Path] = {}
106    for name, size, sha in spec:
107        for folder in folders:
108            candidate = folder / name
109            try:
110                if candidate.is_file() and candidate.stat().st_size == size and transfer.sha256_file(candidate) == sha:
111                    found[name] = candidate
112                    break
113            except OSError:
114                continue
115    return found
116
117
118def convert_selector(data_dir: str | Path, *, progress: Progress | None = None, source_bytes: int | None = None, source_sha256: str | None = None,
119                     size: int | None = None, sha256: str | None = None) -> Path | None:
120    """Make the pack with the Q4_0 selector (drafting.CONVERTED_NAME, 174 MiB less in graphics memory) from the verified Q4_0 pack, on this computer. No network, a second
121    or two on a fast machine, about 120 MB of memory. Called only by setup, `strata drafting fetch` and Load (launch), never by a start or a serve. The Q4_0 pack must be
122    the pinned bytes (PACK_BYTES / PACK_SHA256) and the result the pinned bytes (CONVERTED_BYTES / CONVERTED_SHA256); anything else is deleted and None is returned:
123    the Q4_0 pack with the bf16 selector keeps being used, nothing is reported as an error. The idea and the bytes are nazeshinjite's
124    (https://huggingface.co/nazeshinjite/Qwen3.8-Flash-Next-DFlash2-GGUF). The keyword arguments are for tests, which convert a small synthetic pack."""
125    report = progress or (lambda *_: None)
126    want_size = drafting.CONVERTED_BYTES if size is None else size
127    want_sha = drafting.CONVERTED_SHA256 if sha256 is None else sha256
128    if drafting.converted_ok(data_dir, size=want_size, sha256=want_sha):
129        return drafting.converted_path(data_dir)
130    src = drafting.target_path(data_dir)
131    out = drafting.converted_path(data_dir)
132    tmp = out.with_suffix(".tmp")
133    try:
134        if not src.is_file():
135            return None
136        pinned_bytes = drafting.PACK_BYTES if source_bytes is None else source_bytes
137        pinned_sha = drafting.PACK_SHA256 if source_sha256 is None else source_sha256
138        if src.stat().st_size != pinned_bytes or transfer.sha256_file(src) != pinned_sha:
139            return None                                  # not the pack we measured: leave it as it is
140        report("Preparing the DFlash2 drafter's smaller selector…", 0, 1)
141        _packer().convert_selector_q4(str(src), str(tmp), say=lambda *_: None)
142        if tmp.stat().st_size != want_size or transfer.sha256_file(tmp) != want_sha:
143            tmp.unlink(missing_ok=True)
144            return None
145        os.replace(tmp, out)
146        out.with_name(out.name + ".ok").unlink(missing_ok=True)
147        if not drafting.converted_ok(data_dir, size=want_size, sha256=want_sha):        # writes the marker
148            return None
149        report("The DFlash2 drafter's smaller selector is ready.", 1, 1)
150        return out
151    except Exception:                                    # noqa: BLE001 - never a reason to stop a setup or a launch: the bf16-selector pack runs
152        try:
153            tmp.unlink(missing_ok=True)
154        except OSError:
155            pass
156        return None
157
158
159FEED_TIMEOUT = 8.0
160RETRY_AFTER_S = drafting.RETRY_AFTER_S          # Load (strata launch) asks the feed for the tuned drafter at most this often when the answer was "nothing"; setup and `strata drafting fetch` always ask
161MISS_MARK = drafting.MISS_MARK
162_recent_miss = drafting.recent_miss              # (the start's "Run strata drafting fetch" line reads the same mark: strata_control/drafting.py fetch_hint)
163
164
165def _note_miss(data_dir: str | Path, missed: bool) -> None:
166    mark = Path(data_dir) / drafting.FOLDER / MISS_MARK
167    try:
168        if missed:
169            mark.parent.mkdir(parents=True, exist_ok=True)
170            mark.write_text(time.strftime("%Y-%m-%d %H:%M"), encoding="utf-8")
171        else:
172            mark.unlink(missing_ok=True)
173    except OSError:
174        pass
175
176
177def _feed_source(feed: str | None = None) -> str:
178    """The signed feed to read: the one named, STRATA_UPDATE_FEED, else the project's release feed (strata_cli/update_cmd.py default_feed)."""
179    if feed:
180        return feed
181    from strata_cli import update_cmd
182    return os.environ.get(update_cmd.ENV_FEED) or update_cmd.default_feed()
183
184
185def _accepted_sequence(components: str | Path | None = None) -> tuple[int | None, Path | None]:
186    """(the last feed sequence this computer accepted, the file that remembers it): what `strata update` refuses to go below
187    (updater.open_feed, ``<components>/.updates/state.json``). (None, None) when nothing was accepted yet or the file cannot be read."""
188    try:
189        from strata_cli import update_cmd
190        from strata_control import engine_component as ec, updater
191        root = Path(components) if components else update_cmd.default_components_dir(ec)
192        state = updater.State(root)
193        value = (state.data.get("feed") or {}).get("sequence")
194        return (int(value), state.path) if isinstance(value, int) and not isinstance(value, bool) else (None, None)
195    except Exception:                                     # noqa: BLE001 - a state file that cannot be read accepts nothing, as for the update
196        return None, None
197
198
199def tuned_from_feed(*, feed: str | None = None, backend: str | None = None, size: int | None = None, sha256: str | None = None, name: str | None = None,
200                    variant: str | None = None, components: str | Path | None = None) -> tuple[str, int, str] | None:
201    """(address, size, sha256) of the tuned drafter as the signed feed lists it (member ``drafters``), or None: the feed cannot be read (offline, the host is down: silent), has no
202    such entry for this engine family, or lists other bytes than the ones this Strata was measured with (pinned size and SHA-256: then it is another drafter, not ours).
203    A feed that does not verify is DraftingError: a bad signature, an expired feed, or a feed older than the one `strata update` already accepted on this computer
204    (the update's own rule, updater.open_feed: a replayed older feed could name a drafter file the newer one no longer lists). Only the update moves the
205    accepted sequence; this lookup reads it. A build that trusts no key (a source checkout from before the keys) is silent."""
206    from strata_control import signing, updater
207    pin = drafting.tuned_pack(variant)
208    want_size = pin.size if size is None else size
209    want_sha = pin.sha256 if sha256 is None else sha256
210    want_name = name or pin.name
211    source = _feed_source(feed)
212    last, state_file = _accepted_sequence(components)
213    try:
214        loaded = feedmod.fetch(source, signing.load_trusted_keys(), timeout=FEED_TIMEOUT, channel="stable", last_sequence=last)
215    except feedmod.FeedDowngrade as exc:
216        words = updater.downgrade_words(exc.sequence, exc.accepted, state_file) if state_file is not None else str(exc)
217        raise DraftingError(f"The update feed could not be trusted: {words}") from None
218    except feedmod.FeedError as exc:
219        if isinstance(exc, feedmod.FeedUnreachable) or exc.exit_code == 6 or "trusts no update key" in str(exc):
220            return None
221        raise DraftingError(f"The update feed could not be trusted: {exc}") from None
222    for entry in loaded.drafters:
223        if entry.name == want_name and (backend or drafting.TUNED_BACKEND) in entry.backends:
224            if entry.size != want_size or entry.sha256 != want_sha:
225                return None
226            return loaded.url(entry.url), entry.size, entry.sha256
227    return None
228
229
230def _reachable(location: str) -> bool:
231    """A local source (a file: address or a path) is always there to try; a web address must answer one short HEAD request."""
232    return transfer.kind_of(location) in ("path", "file") or online(location)
233
234
235def provide_licence(data_dir: str | Path) -> bool:
236    """Copy the Apache-2.0 text and the 'modified by Strata' notice (data/dflash2-tuned/) next to the tuned drafter file. False when Strata's copy is missing."""
237    source = Path(__file__).resolve().parents[1] / drafting.TUNED_LICENCE_FOLDER
238    target = Path(data_dir) / drafting.FOLDER
239    try:
240        for name, out in (("LICENSE", "LICENSE-dflash2-tuned"), ("NOTICE.md", "NOTICE-dflash2-tuned.md")):
241            text = (source / name).read_bytes()
242            target.mkdir(parents=True, exist_ok=True)
243            if not (target / out).is_file() or (target / out).read_bytes() != text:
244                (target / out).write_bytes(text)
245        return True
246    except OSError:
247        return False
248
249
250def ensure_tuned(data_dir: str | Path, *, progress: Progress | None = None, cancel: threading.Event | None = None, url: str | None = None,
251                 size: int | None = None, sha256: str | None = None, name: str | None = None, feed: str | None = None, throttle: bool = False, backend: str | None = None, variant: str | None = None) -> Path | None:
252    """Make the tuned drafter (drafting.TUNED_NAME, 340 MB) exist under ``data_dir`` and return its path. It is found in the signed feed (``feed``: a URL or folder; default
253    STRATA_UPDATE_FEED or the project's release feed), unless ``url`` or STRATA_DFLASH2_TUNED_URL names the file directly. None when it cannot be had without anything being wrong:
254    the feed or the address does not answer (no internet, the host is down), the feed does not list the file, or it answers with an error page. Resumable (transfer.download continues a kept partial file). A complete
255    file that is not the pinned bytes is deleted and DraftingError says so; an interrupted download keeps its partial file and raises DraftingError. The licence text and the
256    notice are copied beside it. The stock pack is never touched. The keyword arguments are for tests."""
257    report = progress or (lambda *_: None)
258    pin = drafting.tuned_pack(variant)
259    want_size = pin.size if size is None else size
260    want_sha = pin.sha256 if sha256 is None else sha256
261    file_name = name or pin.name
262    out = Path(data_dir) / drafting.FOLDER / file_name
263    if drafting.converted_ok(data_dir, size=want_size, sha256=want_sha, name=file_name):
264        provide_licence(data_dir)
265        return out
266    acquisition.require("the tuned DFlash2 drafter", "strata drafting fetch")
267    location = url or os.environ.get(drafting.TUNED_URL_ENV, "").strip()
268    if location:                                          # a direct address (tests, a mirror): the pinned size and SHA-256 still decide
269        if not _reachable(location):
270            return None
271    else:                                                 # the normal way: the signed feed names the file; nothing answers offline
272        if throttle and _recent_miss(data_dir):           # a launch asked a short while ago and got nothing: no wait, no second try
273            return None
274        found = tuned_from_feed(feed=feed, backend=backend, size=want_size, sha256=want_sha, name=file_name, variant=variant)
275        _note_miss(data_dir, found is None)
276        if found is None:
277            return None
278        location = found[0]
279    out.parent.mkdir(parents=True, exist_ok=True)
280    partial = out.with_name(out.name + ".part")
281    try:
282        transfer.download(location, partial, size=want_size, sha256=want_sha, cancel=cancel, what="the tuned DFlash2 drafter",
283                          progress=lambda d, _s: report("Downloading the tuned DFlash2 drafter…", d, want_size))
284    except transfer.Unreachable as exc:
285        raise DraftingError(str(exc)) from None          # the network rule's sentence: the host, what to check, what still works
286    except transfer.ChecksumMismatch:
287        raise DraftingError("The tuned DFlash2 drafter did not pass the safety check, so it was deleted.") from None
288    except transfer.Cancelled:
289        raise
290    except transfer.TransferError as exc:
291        if exc.resumable:
292            raise DraftingError(f"The tuned DFlash2 download did not finish: {exc}. Try again; it continues where it stopped.") from None
293        return None                                      # an error page from the host (not published yet, moved): nothing to report, the standard drafter runs
294    os.replace(partial, out)
295    out.with_name(out.name + ".ok").unlink(missing_ok=True)
296    if not drafting.converted_ok(data_dir, size=want_size, sha256=want_sha, name=file_name):       # writes the marker
297        out.unlink(missing_ok=True)
298        raise DraftingError("The tuned DFlash2 drafter did not pass the safety check, so it was deleted.")
299    provide_licence(data_dir)
300    drafting.provide_vocab(data_dir)
301    report("The tuned DFlash2 drafter is ready.", want_size, want_size)
302    return out
303
304
305def ensure_for(data_dir: str | Path, *, model_name: str | None, backend: str | None, progress: Progress | None = None,
306               cancel: threading.Event | None = None, feed: str | None = None, throttle: bool = False, archs=None, args: list | None = None,
307               vram_mib: float | None = None) -> Path | None:
308    """The drafter a set should start with, fetched if needed: the tuned pack where the set has one (drafting.SET_DEFAULTS), else, or when the tuned one cannot be had, the
309    stock drafter (ensure). For such a set: None when nothing could be fetched because the network did not answer (the MTP runs: silent for the caller); DraftingError for a
310    real fault (a safety check that failed, an interrupted download). A set with no tuned entry gets ensure() unchanged."""
311    if drafting.tuned_applies(backend, model_name, archs, args=args, vram_mib=vram_mib):
312        tuned_error: DraftingError | None = None
313        try:
314            got = ensure_tuned(data_dir, progress=progress, cancel=cancel, feed=feed, throttle=throttle, backend=backend, variant=drafting.tuned_variant(backend, model_name))
315        except DraftingError as exc:
316            got, tuned_error = None, exc
317        if got is not None:
318            return got
319        if drafting.pack_ready(data_dir):
320            if tuned_error is not None:
321                raise tuned_error
322            return drafting.pack_path(data_dir)
323        try:
324            return ensure(data_dir, progress=progress, cancel=cancel)
325        except OfflineError:
326            if tuned_error is not None:
327                raise tuned_error from None
328            return None
329    return ensure(data_dir, progress=progress, cancel=cancel)       # a set with no tuned entry: the stock drafter exactly as before
330
331
332def ensure(data_dir: str | Path, *, progress: Progress | None = None, cancel: threading.Event | None = None,
333           base_url: str | None = None, files=None) -> Path:
334    """Make the packed drafter exist under ``data_dir`` and return its path. A pack that is there is kept. Resumable: an interrupted
335    download is continued, a file whose hash differs is deleted and the person is told. ``base_url`` / ``files`` are for tests."""
336    report = progress or (lambda *_: None)
337    out = drafting.target_path(data_dir)
338    if drafting.pack_ready(data_dir):
339        drafting.provide_vocab(data_dir)
340        if files is None and drafting.engine_has_selector_q4():
341            convert_selector(data_dir, progress=report)
342        report("The DFlash2 drafter is ready.", 1, 1)
343        return drafting.pack_path(data_dir)
344    acquisition.require("the DFlash2 drafter", "strata drafting fetch")
345    folder = out.parent
346    src = folder / "src"
347    spec = tuple(files if files is not None else drafting.FILES)
348    have = _present([src, *(_hub_snapshots() if files is None else [])], spec)       # already here and checked: used where it is, never fetched again
349    if len(have) < len(spec) and not online(base_url or drafting.BASE_URL):
350        raise OfflineError("There is no internet connection, so the DFlash2 drafter can't be downloaded now.")
351    src.mkdir(parents=True, exist_ok=True)
352    total = sum(size for _n, size, _h in spec)
353    done_before = 0
354    for name, size, sha in spec:
355        if name not in have:
356            base = done_before
357            partial = src / (name + ".part")
358            try:
359                transfer.download((base_url or drafting.BASE_URL) + name, partial, size=size, sha256=sha, cancel=cancel, what="the DFlash2 drafter",
360                                  progress=lambda d, _s, base=base: report("Downloading the DFlash2 drafter…", base + d, total))
361            except transfer.Unreachable as exc:
362                raise DraftingError(str(exc)) from None  # the network rule's sentence: the host, what to check, what still works
363            except transfer.ChecksumMismatch:
364                raise DraftingError("The downloaded DFlash2 file did not pass the safety check, so it was deleted. Try again; if it keeps "
365                                    "happening, use MTP for now.") from None
366            except transfer.TransferError as exc:
367                raise DraftingError(f"The DFlash2 download did not finish: {exc}. Try again; it continues where it stopped.") from None
368            os.replace(partial, src / name)
369            have[name] = src / name
370        done_before += size
371    report("Packing the DFlash2 drafter for the engine…", total, total)
372    tmp = out.with_suffix(".tmp")
373    try:
374        _packer().pack(str(have["model.safetensors"]), str(have["config.json"]), str(tmp), say=lambda *_: None, q4=True)
375        if files is None:                                # the real pinned files: the pack must be the exact bytes we measured (tests pack a small synthetic file)
376            if tmp.stat().st_size != drafting.PACK_BYTES or transfer.sha256_file(tmp) != drafting.PACK_SHA256:
377                tmp.unlink(missing_ok=True)
378                raise DraftingError("The DFlash2 drafter was prepared but did not pass the safety check, so it was deleted. The model keeps using the MTP. "
379                                    "Try again; if it keeps happening, update Strata.")
380        os.replace(tmp, out)
381    except DraftingError:
382        raise
383    except Exception as exc:                         # noqa: BLE001 - a plain sentence for any packing failure; the cause stays in the chain
384        tmp.unlink(missing_ok=True)
385        raise DraftingError("The DFlash2 drafter could not be prepared on this computer. The model keeps using the MTP.") from exc
386    for name, _size, _sha in spec:                   # the source files are 1.2 GB of nothing the engine reads (a copy kept by the Hugging Face tools is theirs: left alone)
387        if have[name].parent == src:
388            have[name].unlink(missing_ok=True)
389    try:
390        src.rmdir()
391    except OSError:
392        pass
393    drafting.provide_vocab(data_dir)                 # the draft vocabulary comes with the pack: an install that never had the MTP layer needs it
394    if files is None and drafting.engine_has_selector_q4():
395        convert_selector(data_dir, progress=report)  # the smaller selector (174 MiB), made here from the pack just checked; the bf16-selector pack stays beside it
396    report("The DFlash2 drafter is ready.", total, total)
397    return out