okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1637559fd
main
1"""Getting the DFlash2 drafter onto this computer: a pinned download, checked against the repository's own SHA-256, packed for the engine. 2 3strata drafting plan [--data-dir DIR] what it would download (nothing is changed) 4strata 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 , 39args :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 41the 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. 42For 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.""" 43tuned = drafting .tuned_applies (backend ,model_name ,archs ,args = args ,vram_mib = vram_mib ) 44variant = drafting .tuned_variant (backend ,model_name ) 45pin = drafting .tuned_pack (variant ) 46ready = drafting .tuned_ok (data_dir ,variant )if tuned else drafting .pack_ready (data_dir ) 47gb = 0.0 if ready else (pin .gb if tuned else drafting .DOWNLOAD_GB ) 48if ready : 49text = "The DFlash2 drafter is already on this computer." 50elif tuned : 51text = (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). " 52f"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." ) 53else : 54text = (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 " 55f"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." ) 57return {"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).""" 63path = Path (__file__ ).resolve ().parents [1 ]/ "tools" / "dflash2_pack.py" 64if not path .is_file (): 65raise DraftingError ("The packing tool is missing from this installation. Update Strata, then try again." ) 66spec = importlib .util .spec_from_file_location ("strata_dflash2_pack" ,path ) 67module = importlib .util .module_from_spec (spec ) 68sys .modules .setdefault ("strata_dflash2_pack" ,module ) 69spec .loader .exec_module (module ) 70return 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 78sentence in a few seconds instead of a stalled progress bar. Any answer from the server counts, even an error page.""" 79try : 80transfer .check_url_policy (url ) 81request = urllib .request .Request (url ,method = "HEAD" ,headers = {"User-Agent" :"strata-drafting/1" }) 82with transfer ._opener .open (request ,timeout = timeout ):# the download's own opener: same certificates, same redirect policy, same proxy settings 83return True 84except urllib .error .HTTPError : 85return True 86except (urllib .error .URLError ,OSError ,TimeoutError ,ValueError ,transfer .TransferError )as exc : 87from strata_control import tls 88return 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).""" 93roots :list [Path ]= [] 94for name in ("HF_HUB_CACHE" ,"HUGGINGFACE_HUB_CACHE" ): 95if os .environ .get (name ): 96roots .append (Path (os .environ [name ])) 97if os .environ .get ("HF_HOME" ): 98roots .append (Path (os .environ ["HF_HOME" ])/ "hub" ) 99roots .append (Path .home ()/ ".cache" / "huggingface" / "hub" ) 100return [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.""" 105found :dict [str ,Path ]= {} 106for name ,size ,sha in spec : 107for folder in folders : 108candidate = folder / name 109try : 110if candidate .is_file ()and candidate .stat ().st_size == size and transfer .sha256_file (candidate )== sha : 111found [name ]= candidate 112break 113except OSError : 114continue 115return found 116 117 118def convert_selector (data_dir :str | Path ,* ,progress :Progress | None = None ,source_bytes :int | None = None ,source_sha256 :str | None = None , 119size :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 121or 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 122the pinned bytes (PACK_BYTES / PACK_SHA256) and the result the pinned bytes (CONVERTED_BYTES / CONVERTED_SHA256); anything else is deleted and None is returned: 123the 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.""" 125report = progress or (lambda * _ :None ) 126want_size = drafting .CONVERTED_BYTES if size is None else size 127want_sha = drafting .CONVERTED_SHA256 if sha256 is None else sha256 128if drafting .converted_ok (data_dir ,size = want_size ,sha256 = want_sha ): 129return drafting .converted_path (data_dir ) 130src = drafting .target_path (data_dir ) 131out = drafting .converted_path (data_dir ) 132tmp = out .with_suffix (".tmp" ) 133try : 134if not src .is_file (): 135return None 136pinned_bytes = drafting .PACK_BYTES if source_bytes is None else source_bytes 137pinned_sha = drafting .PACK_SHA256 if source_sha256 is None else source_sha256 138if src .stat ().st_size != pinned_bytes or transfer .sha256_file (src )!= pinned_sha : 139return None # not the pack we measured: leave it as it is 140report ("Preparing the DFlash2 drafter's smaller selector…" ,0 ,1 ) 141_packer ().convert_selector_q4 (str (src ),str (tmp ),say = lambda * _ :None ) 142if tmp .stat ().st_size != want_size or transfer .sha256_file (tmp )!= want_sha : 143tmp .unlink (missing_ok = True ) 144return None 145os .replace (tmp ,out ) 146out .with_name (out .name + ".ok" ).unlink (missing_ok = True ) 147if not drafting .converted_ok (data_dir ,size = want_size ,sha256 = want_sha ):# writes the marker 148return None 149report ("The DFlash2 drafter's smaller selector is ready." ,1 ,1 ) 150return out 151except Exception :# noqa: BLE001 - never a reason to stop a setup or a launch: the bf16-selector pack runs 152try : 153tmp .unlink (missing_ok = True ) 154except OSError : 155pass 156return 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 : 166mark = Path (data_dir )/ drafting .FOLDER / MISS_MARK 167try : 168if missed : 169mark .parent .mkdir (parents = True ,exist_ok = True ) 170mark .write_text (time .strftime ("%Y-%m-%d %H:%M" ),encoding = "utf-8" ) 171else : 172mark .unlink (missing_ok = True ) 173except OSError : 174pass 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).""" 179if feed : 180return feed 181from strata_cli import update_cmd 182return 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.""" 188try : 189from strata_cli import update_cmd 190from strata_control import engine_component as ec ,updater 191root = Path (components )if components else update_cmd .default_components_dir (ec ) 192state = updater .State (root ) 193value = (state .data .get ("feed" )or {}).get ("sequence" ) 194return (int (value ),state .path )if isinstance (value ,int )and not isinstance (value ,bool )else (None ,None ) 195except Exception :# noqa: BLE001 - a state file that cannot be read accepts nothing, as for the update 196return 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 , 200variant :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 202such 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). 203A 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 205accepted sequence; this lookup reads it. A build that trusts no key (a source checkout from before the keys) is silent.""" 206from strata_control import signing ,updater 207pin = drafting .tuned_pack (variant ) 208want_size = pin .size if size is None else size 209want_sha = pin .sha256 if sha256 is None else sha256 210want_name = name or pin .name 211source = _feed_source (feed ) 212last ,state_file = _accepted_sequence (components ) 213try : 214loaded = feedmod .fetch (source ,signing .load_trusted_keys (),timeout = FEED_TIMEOUT ,channel = "stable" ,last_sequence = last ) 215except feedmod .FeedDowngrade as exc : 216words = updater .downgrade_words (exc .sequence ,exc .accepted ,state_file )if state_file is not None else str (exc ) 217raise DraftingError (f"The update feed could not be trusted: { words } " )from None 218except feedmod .FeedError as exc : 219if isinstance (exc ,feedmod .FeedUnreachable )or exc .exit_code == 6 or "trusts no update key" in str (exc ): 220return None 221raise DraftingError (f"The update feed could not be trusted: { exc } " )from None 222for entry in loaded .drafters : 223if entry .name == want_name and (backend or drafting .TUNED_BACKEND )in entry .backends : 224if entry .size != want_size or entry .sha256 != want_sha : 225return None 226return loaded .url (entry .url ),entry .size ,entry .sha256 227return 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.""" 232return 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.""" 237source = Path (__file__ ).resolve ().parents [1 ]/ drafting .TUNED_LICENCE_FOLDER 238target = Path (data_dir )/ drafting .FOLDER 239try : 240for name ,out in (("LICENSE" ,"LICENSE-dflash2-tuned" ), ("NOTICE.md" ,"NOTICE-dflash2-tuned.md" )): 241text = (source / name ).read_bytes () 242target .mkdir (parents = True ,exist_ok = True ) 243if not (target / out ).is_file ()or (target / out ).read_bytes ()!= text : 244 (target / out ).write_bytes (text ) 245return True 246except OSError : 247return False 248 249 250def ensure_tuned (data_dir :str | Path ,* ,progress :Progress | None = None ,cancel :threading .Event | None = None ,url :str | None = None , 251size :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 253STRATA_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: 254the 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 255file 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 256notice are copied beside it. The stock pack is never touched. The keyword arguments are for tests.""" 257report = progress or (lambda * _ :None ) 258pin = drafting .tuned_pack (variant ) 259want_size = pin .size if size is None else size 260want_sha = pin .sha256 if sha256 is None else sha256 261file_name = name or pin .name 262out = Path (data_dir )/ drafting .FOLDER / file_name 263if drafting .converted_ok (data_dir ,size = want_size ,sha256 = want_sha ,name = file_name ): 264provide_licence (data_dir ) 265return out 266acquisition .require ("the tuned DFlash2 drafter" ,"strata drafting fetch" ) 267location = url or os .environ .get (drafting .TUNED_URL_ENV ,"" ).strip () 268if location :# a direct address (tests, a mirror): the pinned size and SHA-256 still decide 269if not _reachable (location ): 270return None 271else :# the normal way: the signed feed names the file; nothing answers offline 272if throttle and _recent_miss (data_dir ):# a launch asked a short while ago and got nothing: no wait, no second try 273return None 274found = 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 ) 276if found is None : 277return None 278location = found [0 ] 279out .parent .mkdir (parents = True ,exist_ok = True ) 280partial = out .with_name (out .name + ".part" ) 281try : 282transfer .download (location ,partial ,size = want_size ,sha256 = want_sha ,cancel = cancel ,what = "the tuned DFlash2 drafter" , 283progress = lambda d ,_s :report ("Downloading the tuned DFlash2 drafter…" ,d ,want_size )) 284except transfer .Unreachable as exc : 285raise DraftingError (str (exc ))from None # the network rule's sentence: the host, what to check, what still works 286except transfer .ChecksumMismatch : 287raise DraftingError ("The tuned DFlash2 drafter did not pass the safety check, so it was deleted." )from None 288except transfer .Cancelled : 289raise 290except transfer .TransferError as exc : 291if exc .resumable : 292raise DraftingError (f"The tuned DFlash2 download did not finish: { exc } . Try again; it continues where it stopped." )from None 293return None # an error page from the host (not published yet, moved): nothing to report, the standard drafter runs 294os .replace (partial ,out ) 295out .with_name (out .name + ".ok" ).unlink (missing_ok = True ) 296if not drafting .converted_ok (data_dir ,size = want_size ,sha256 = want_sha ,name = file_name ):# writes the marker 297out .unlink (missing_ok = True ) 298raise DraftingError ("The tuned DFlash2 drafter did not pass the safety check, so it was deleted." ) 299provide_licence (data_dir ) 300drafting .provide_vocab (data_dir ) 301report ("The tuned DFlash2 drafter is ready." ,want_size ,want_size ) 302return out 303 304 305def ensure_for (data_dir :str | Path ,* ,model_name :str | None ,backend :str | None ,progress :Progress | None = None , 306cancel :threading .Event | None = None ,feed :str | None = None ,throttle :bool = False ,archs = None ,args :list | None = None , 307vram_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 309stock 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 310real fault (a safety check that failed, an interrupted download). A set with no tuned entry gets ensure() unchanged.""" 311if drafting .tuned_applies (backend ,model_name ,archs ,args = args ,vram_mib = vram_mib ): 312tuned_error :DraftingError | None = None 313try : 314got = ensure_tuned (data_dir ,progress = progress ,cancel = cancel ,feed = feed ,throttle = throttle ,backend = backend ,variant = drafting .tuned_variant (backend ,model_name )) 315except DraftingError as exc : 316got ,tuned_error = None ,exc 317if got is not None : 318return got 319if drafting .pack_ready (data_dir ): 320if tuned_error is not None : 321raise tuned_error 322return drafting .pack_path (data_dir ) 323try : 324return ensure (data_dir ,progress = progress ,cancel = cancel ) 325except OfflineError : 326if tuned_error is not None : 327raise tuned_error from None 328return None 329return 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 , 333base_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 335download is continued, a file whose hash differs is deleted and the person is told. ``base_url`` / ``files`` are for tests.""" 336report = progress or (lambda * _ :None ) 337out = drafting .target_path (data_dir ) 338if drafting .pack_ready (data_dir ): 339drafting .provide_vocab (data_dir ) 340if files is None and drafting .engine_has_selector_q4 (): 341convert_selector (data_dir ,progress = report ) 342report ("The DFlash2 drafter is ready." ,1 ,1 ) 343return drafting .pack_path (data_dir ) 344acquisition .require ("the DFlash2 drafter" ,"strata drafting fetch" ) 345folder = out .parent 346src = folder / "src" 347spec = tuple (files if files is not None else drafting .FILES ) 348have = _present ([src ,* (_hub_snapshots ()if files is None else [])],spec )# already here and checked: used where it is, never fetched again 349if len (have )< len (spec )and not online (base_url or drafting .BASE_URL ): 350raise OfflineError ("There is no internet connection, so the DFlash2 drafter can't be downloaded now." ) 351src .mkdir (parents = True ,exist_ok = True ) 352total = sum (size for _n ,size ,_h in spec ) 353done_before = 0 354for name ,size ,sha in spec : 355if name not in have : 356base = done_before 357partial = src / (name + ".part" ) 358try : 359transfer .download ((base_url or drafting .BASE_URL )+ name ,partial ,size = size ,sha256 = sha ,cancel = cancel ,what = "the DFlash2 drafter" , 360progress = lambda d ,_s ,base = base :report ("Downloading the DFlash2 drafter…" ,base + d ,total )) 361except transfer .Unreachable as exc : 362raise DraftingError (str (exc ))from None # the network rule's sentence: the host, what to check, what still works 363except transfer .ChecksumMismatch : 364raise 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 366except transfer .TransferError as exc : 367raise DraftingError (f"The DFlash2 download did not finish: { exc } . Try again; it continues where it stopped." )from None 368os .replace (partial ,src / name ) 369have [name ]= src / name 370done_before += size 371report ("Packing the DFlash2 drafter for the engine…" ,total ,total ) 372tmp = out .with_suffix (".tmp" ) 373try : 374_packer ().pack (str (have ["model.safetensors" ]),str (have ["config.json" ]),str (tmp ),say = lambda * _ :None ,q4 = True ) 375if files is None :# the real pinned files: the pack must be the exact bytes we measured (tests pack a small synthetic file) 376if tmp .stat ().st_size != drafting .PACK_BYTES or transfer .sha256_file (tmp )!= drafting .PACK_SHA256 : 377tmp .unlink (missing_ok = True ) 378raise 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." ) 380os .replace (tmp ,out ) 381except DraftingError : 382raise 383except Exception as exc :# noqa: BLE001 - a plain sentence for any packing failure; the cause stays in the chain 384tmp .unlink (missing_ok = True ) 385raise DraftingError ("The DFlash2 drafter could not be prepared on this computer. The model keeps using the MTP." )from exc 386for 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) 387if have [name ].parent == src : 388have [name ].unlink (missing_ok = True ) 389try : 390src .rmdir () 391except OSError : 392pass 393drafting .provide_vocab (data_dir )# the draft vocabulary comes with the pack: an install that never had the MTP layer needs it 394if files is None and drafting .engine_has_selector_q4 (): 395convert_selector (data_dir ,progress = report )# the smaller selector (174 MiB), made here from the pack just checked; the bf16-selector pack stays beside it 396report ("The DFlash2 drafter is ready." ,total ,total ) 397return out