okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b749503db
main
1#!/usr/bin/env python3 2"""Release gate: install a model of the signed feed from REAL FILES, through setup.py, the way a person's Terminal or the app does. 3 4Why: the feed-model install path had only mock tests until the Qwen4 release-day rehearsal (RESULTS-Q4-P8.md, 2026-11-08), which then found three bugs 5(F2 `KeyError: 'mmproj'` for a model with no picture reader, F3 the Flash-Next draft layer fetched for a model whose entry says `drafter: none`, F5 no RAM 6budget so a 64 GB PC began writing a second 77 GB copy of the experts) and a fourth one for a model of another shape (F4, the shipped expert profile). 7Each of them only shows with a real file of the model's kind, not with the few bytes of the mock tests. 8 9What it does, in a scratch folder (nothing of the real install, %APPDATA% or the data folder is touched, no network beyond 127.0.0.1): 101. writes a small synthetic qwen4exp GGUF with tools/q4geo_synth.py (random weights; `--tokenizer-from` gives it a real tokenizer); 112. builds a models-only feed signed with a THROW-AWAY key (packaging/feed_tool.py's own build_feed) whose entry says `drafter: none`, has no picture reader 12and a shape that is not the shipped Flash-Next one; 133. serves the file from a tiny Hugging Face stand-in on 127.0.0.1 and runs `setup.py` in the app's mode (STRATA_CONTROL_INSTALL=1: no engine, no pip, no build) 14with the feed as the model list: download, SHA-256 check, preparation (the pack), run config; 154. checks: setup exits 0 and prints neither a Traceback nor `KeyError`; the Flash-Next draft layer was not asked for (the stand-in saw only the model file); 16the owner's two lines are there; the run config reads the file in place with a RAM budget and no second copy of the experts was written; a neutral expert 17profile for the file's own layers x experts is in the pack folder and the config names it; a second run changes nothing and downloads nothing. 185. with --engine <folder of an engine built for the file's shape>: starts that engine from the run config, sends ONE chat request and checks the answer 19is finite (the file has random weights: the text is empty or noise, the usage numbers and `finish_reason` are what counts). 20 21python tools/feed_model_install_gate.py 22python tools/feed_model_install_gate.py --tokenizer-from <a real Flash-Next shard 1> --engine <engine folder> --full 23 24`tools/test_feed_model_install_realfile.py` runs step 1 to 4 as a test in `python tools/check` (py-tools). The preparation tools read GGUF files with the vendored 25their own GGUF code (tools/strata_gguf.py), so no gguf-py, no llama.cpp checkout, no STRATA_TEST_LLAMA_CPP and no network are needed; the check also fails if setup says it 26fetched llama.cpp. Without numpy it is SKIPPED with that reason (never a pass). 27Exit codes: 0 pass, 1 a check failed, 2 not run (no numpy, no NVIDIA card on a Windows box), 3 the engine phase failed. 28""" 29from __future__import annotations 30 31import argparse 32import hashlib 33import http .server 34import json 35import os 36import re 37import shutil 38import signal 39import socket 40import subprocess 41import sys 42import tempfile 43import threading 44import time 45import urllib .request 46from pathlib import Path 47 48ROOT = Path (__file__ ).resolve ().parents [1 ] 49sys .path .insert (0 ,str (ROOT )) 50sys .path .insert (0 ,str (ROOT / "packaging" )) 51 52REV = "0123456789abcdef0123456789abcdef01234567" 53REPO = "gate-test/Qwen4-Gate-GGUF" 54MODEL_ID = "qwen4-gate" 55QUANT = "GATE-Q4" 56FILE_NAME = "Qwen4-Gate-GATE-Q4.gguf" 57SETUP_TIMEOUT = int (os .environ .get ("STRATA_GATE_SETUP_TIMEOUT" ,"300" ))# seconds for one setup run (the 0.2 GB file takes about 6) 58NEUTRAL_LINE = "This model's shape differs from Flash-Next, so a neutral expert profile is used." 59NO_DRAFT_LINE = "The model list says this model has no draft layer (MTP), so none is fetched or used." 60 61# the shape of the small file: a q4_lite model cut down to 1 layer of 8 experts, so a run takes seconds and the file is 0.2 GB. --full: the case-B stand-in of the rehearsal 62# (4 layers of q4_lite, the shape a `-DSTRATA_GEOMETRY_FILE` engine of that rehearsal was built for) 63TINY = dict (layers = 1 ,vocab = 2048 ,set = "n_expert=8,n_expert_used=2,n_ff=64" ) 64FULL = dict (layers = 4 ,vocab = None ,set = "" ) 65 66 67class NotRun (Exception ): 68pass 69 70 71def check_gguf_tools ()-> None : 72"""The preparation tools read and write GGUF files with their own code (tools/strata_gguf.py, tools/strata_quants.py): nothing to find, nothing to 73fetch, and no gguf-py needed (this gate also runs on a copy of the tree without third_party/strata-gguf-py).""" 74for f in ("strata_gguf.py" ,"strata_quants.py" ,"strata_quant_tables.py" ): 75if not (ROOT / "tools" / f ).is_file (): 76raise NotRun ("tools/%s is missing from this checkout" % f ) 77 78 79def free_port ()-> int : 80with socket .socket ()as s : 81s .bind (("127.0.0.1" ,0 )) 82return s .getsockname ()[1 ] 83 84 85class Mirror : 86"""GET/HEAD/Range for /<repo>/resolve/<rev>/<path> out of one folder, on 127.0.0.1; keeps the list of what was asked for.""" 87 88def __init__ (self ,root :Path ): 89self .root ,self .seen = Path (root ).resolve (), [] 90outer = self 91 92class H (http .server .BaseHTTPRequestHandler ): 93protocol_version = "HTTP/1.1" 94 95def log_message (self ,* a ): 96pass 97 98def _serve (self ,head ): 99outer .seen .append (self .path ) 100m = re .match (r"^/([^/]+/[^/]+)/resolve/[^/]+/(.+?)(\?.*)?$" ,self .path ) 101p = (outer .root / m .group (1 )/ m .group (2 )).resolve ()if m else None 102if p is None or outer .root not in p .parents or not p .is_file (): 103self .send_response (404 ) 104self .send_header ("Content-Length" ,"0" ) 105self .end_headers () 106return 107size = p .stat ().st_size 108start ,end ,code = 0 ,size - 1 ,200 109rng = re .match (r"bytes=(\d*)-(\d*)" ,self .headers .get ("Range" )or "" ) 110if rng : 111a ,b = rng .groups () 112start = max (0 ,size - int (b ))if (a == "" and b != "" )else int (a or 0 ) 113end = min (int (b ),size - 1 )if (b and a != "" )else size - 1 114code = 206 115n = end - start + 1 116self .send_response (code ) 117self .send_header ("Content-Type" ,"application/octet-stream" ) 118self .send_header ("Accept-Ranges" ,"bytes" ) 119self .send_header ("Content-Length" ,str (n )) 120self .send_header ("X-Linked-Size" ,str (size )) 121if code == 206 : 122self .send_header ("Content-Range" ,"bytes %d-%d/%d" % (start ,end ,size )) 123self .end_headers () 124if head : 125return 126with p .open ("rb" )as f : 127f .seek (start ) 128left = n 129while left > 0 : 130chunk = f .read (min (1 << 20 ,left )) 131if not chunk : 132break 133try : 134self .wfile .write (chunk ) 135except OSError : 136return 137left -= len (chunk ) 138 139def do_GET (self ): 140self ._serve (False ) 141 142def do_HEAD (self ): 143self ._serve (True ) 144 145self .server = http .server .ThreadingHTTPServer (("127.0.0.1" ,0 ),H ) 146self .port = self .server .server_address [1 ] 147self .thread = threading .Thread (target = self .server .serve_forever ,daemon = True ) 148 149def __enter__ (self ): 150self .thread .start () 151return self 152 153def __exit__ (self ,* exc ): 154self .server .shutdown () 155self .server .server_close () 156 157 158def sha256_of (path :Path )-> str : 159h = hashlib .sha256 () 160with path .open ("rb" )as f : 161for chunk in iter (lambda :f .read (1 << 20 ),b"" ): 162h .update (chunk ) 163return h .hexdigest () 164 165 166def make_synthetic (out :Path ,shape :dict ,tokenizer_from :str | None )-> None : 167cmd = [sys .executable ,"-I" ,str (ROOT / "tools" / "q4geo_synth.py" ),"--shape" ,"q4_lite" ,"--layers" ,str (shape ["layers" ]),"--recipe" ,"ud-q4k" , 168"--exact-bf16" ,"--small-ple" ,"--out" ,str (out )] 169if shape ["vocab" ]and not tokenizer_from : 170cmd += ["--vocab" ,str (shape ["vocab" ])] 171if shape ["set" ]: 172cmd += ["--set" ,shape ["set" ]] 173if tokenizer_from : 174cmd += ["--tokenizer-from" ,tokenizer_from ] 175r = subprocess .run (cmd ,capture_output = True ,text = True ) 176if r .returncode != 0 : 177if "numpy" in (r .stderr or "" ): 178raise NotRun ("tools/q4geo_synth.py needs numpy" ) 179raise RuntimeError ("q4geo_synth failed: " + (r .stderr or r .stdout )[- 600 :]) 180 181 182def build_feed (feed :Path ,entry :dict ,work :Path )-> Path : 183"""A models-only feed signed with a throw-away key; returns the file of trusted keys for STRATA_UPDATE_TRUSTED_KEYS.""" 184import feed_tool 185from strata_control import signing 186key = signing .generate_key () 187models = work / "models" 188models .mkdir () 189 (models / (MODEL_ID + ".entry.json" )).write_text (json .dumps (entry ,indent = 1 ),encoding = "utf-8" ) 190feed_tool .build_feed (feed ,key = key ,sequence = 1 ,models_dir = models ) 191trust = work / "trust.json" 192trust .write_text (json .dumps ({"keys" : [signing .public_part (key )]}),encoding = "utf-8" ) 193return trust 194 195 196def make_entry (model :Path )-> dict : 197return {"id" :MODEL_ID ,"title" :"Qwen4 Gate" ,"by" :"the release gate" ,"about" :"a synthetic model with random weights, for the install gate" , 198"licence" :"Apache 2.0" ,"licence_url" :"https://example.org/licence" ,"family" :"qwen4exp" ,"repo" :REPO ,"revision" :REV , 199"pictures" :False ,"drafter" :"none" ,"context" :32768 ,"min_engine" :"0.1.46" , 200# ram_gb and arena_gb are far above any test machine's RAM on purpose: setup must pick the RAM-budget mode (the GGUF read in place) and not the low-RAM mode that 201# writes a second copy of the experts (F5); the 0.2 GB file is all there is to read 202"quants" : [{"name" :QUANT ,"about" :"random weights" ,"ram_gb" :2048 ,"arena_gb" :2000 , 203"files" : [{"name" :FILE_NAME ,"size" :model .stat ().st_size ,"sha256" :sha256_of (model )}]}]} 204 205 206STUB_SMI = """#!/bin/sh 207# the gate's stand-in for nvidia-smi on a box with no NVIDIA card (setup stops at step 1 without one): one 24 GB Ada card, every other question unanswered 208case "$*" in 209*memory.total*) echo "0, NVIDIA GeForce RTX 4090, 24564, 8.9, 570.86.16" ;; 210esac 211exit 0 212""" 213 214 215def nvidia_stub_if_needed (env :dict ,work :Path ,log )-> None : 216"""Setup's step 1 needs an NVIDIA card: nvidia-smi answers on the real boxes (used as it is); on a box without one a POSIX stand-in is put first on PATH.""" 217try : 218ok = subprocess .run (["nvidia-smi" ,"-L" ],env = env ,capture_output = True ,timeout = 30 ).returncode == 0 219except (OSError ,subprocess .TimeoutExpired ): 220ok = False 221if ok : 222return 223if os .name == "nt" : 224raise NotRun ("no NVIDIA card (nvidia-smi does not answer) and the stand-in is POSIX only: setup stops at its step 1" ) 225d = work / "bin" 226d .mkdir (exist_ok = True ) 227f = d / "nvidia-smi" 228f .write_bytes (STUB_SMI .encode ("utf-8" )) 229f .chmod (0o755 ) 230env ["PATH" ]= str (d )+ os .pathsep + env .get ("PATH" ,"" ) 231log ("no NVIDIA card here: a stand-in nvidia-smi (one 24 GB card) is used for setup's step 1" ) 232 233 234def sandbox_env (work :Path ,install :Path ,feed :Path ,trust :Path ,port :int )-> dict : 235env = {k :v for k ,v in os .environ .items ()if not k .startswith (("STRATA_" ,"HF_" ))and k not in ("PYTHONPATH" ,"PYTHONHOME" )} 236home = work / "home" 237home .mkdir (exist_ok = True ) 238env .update ({"HOME" :str (home ),"USERPROFILE" :str (home ),"APPDATA" :str (home / "AppData" / "Roaming" ),"LOCALAPPDATA" :str (home / "AppData" / "Local" ), 239"XDG_DATA_HOME" :str (home / ".local" / "share" ),"XDG_CONFIG_HOME" :str (home / ".config" ),"XDG_STATE_HOME" :str (home / ".local" / "state" ), 240"XDG_CACHE_HOME" :str (home / ".cache" ),"STRATA_CONTROL_INSTALL" :"1" ,"STRATA_INSTALL_DIR" :str (install ),"STRATA_COMPONENTS_DIR" :str (work / "comp" ), 241"STRATA_UPDATE_FEED" :str (feed ),"STRATA_UPDATE_TRUSTED_KEYS" :str (trust ),"STRATA_NO_PATH" :"1" ,"HF_ENDPOINT" :f"http://127.0.0.1: { port } " , 242"PYTHONUTF8" :"1" ,"PYTHONNOUSERSITE" :"1" ,"STRATA_ALLOW_UNPINNED" :"1" }) 243return env 244 245 246def kill_tree (proc :subprocess .Popen )-> None : 247"""Only the process this script started and its children.""" 248if os .name == "nt" : 249subprocess .run (["taskkill" ,"/T" ,"/F" ,"/PID" ,str (proc .pid )],capture_output = True ) 250else : 251try : 252os .killpg (proc .pid ,signal .SIGKILL ) 253except OSError : 254proc .kill () 255 256 257def run_setup (env :dict ,data :Path ,extra :list [str ],timeout :int = SETUP_TIMEOUT )-> tuple [int ,str ]: 258"""setup.py in the app's mode. A run that does not end in `timeout` seconds (a fetch of something the model list did not name keeps retrying) is killed and reported.""" 259cmd = [sys .executable ,str (ROOT / "setup.py" ),"--family" ,MODEL_ID ,"--model" ,QUANT ,"--data-dir" ,str (data ),"--feed" ,env ["STRATA_UPDATE_FEED" ], 260"--yes" ,"--no-start" ,"--vision" ,"no" ,"--context" ,"32768" ,"--no-browser" ,* extra ] 261proc = subprocess .Popen (cmd ,cwd = str (ROOT ),env = env ,stdout = subprocess .PIPE ,stderr = subprocess .STDOUT ,text = True ,errors = "replace" , 262start_new_session = (os .name != "nt" )) 263try : 264out ,_ = proc .communicate (timeout = timeout ) 265return proc .returncode ,out or "" 266except subprocess .TimeoutExpired : 267kill_tree (proc ) 268out ,_ = proc .communicate () 269return 124 , (out or "" )+ f"\n[the gate stopped setup after { timeout } s]\n" 270 271 272def newest (path :Path ,pattern :str )-> list [Path ]: 273return sorted (path .rglob (pattern ),key = lambda p :p .stat ().st_mtime )if path .is_dir ()else [] 274 275 276def check (work :Path ,tokenizer_from :str | None ,shape :dict ,log )-> dict : 277"""Steps 1 to 4. Returns {"problems": [...], "config": path or None, "out": setup's text}.""" 278problems :list [str ]= [] 279model_dir = work / "mirror" / REPO 280model_dir .mkdir (parents = True ) 281model = model_dir / FILE_NAME 282t = time .time () 283make_synthetic (model ,shape ,tokenizer_from ) 284log (f"synthetic file { model . stat (). st_size / 1e9 :.2f } GB in { time . time () - t :.1f } s" ) 285feed = work / "feed" 286trust = build_feed (feed ,make_entry (model ),work ) 287install ,data = work / "install" ,work / "data" 288install .mkdir () 289with Mirror (work / "mirror" )as mirror : 290env = sandbox_env (work ,install ,feed ,trust ,mirror .port ) 291nvidia_stub_if_needed (env ,work ,log ) 292t = time .time () 293code ,out = run_setup (env ,data , []) 294log (f"setup run 1: exit { code } in { time . time () - t :.0f } s" ) 295asked = [p for p in mirror .seen if "/resolve/" in p ] 296if code != 0 : 297problems .append (f"setup exited { code } " ) 298for bad in ("Traceback" ,"KeyError" ): 299if bad in out : 300problems .append (f"setup printed { bad !r } " ) 301if "llama.cpp source" in out or any ("llama.cpp" in p or "ggml-org" in p for p in mirror .seen ): 302problems .append ("setup fetched llama.cpp (the preparation tools have their own GGUF code: tools/strata_gguf.py)" ) 303if (install / "third_party" / "llama.cpp" ).exists (): 304problems .append ("setup wrote third_party/llama.cpp into the install folder" ) 305wrong = sorted ({p for p in asked if FILE_NAME not in p }) 306if wrong :# F3: the Flash-Next draft layer (or anything else of another repository) was asked for 307problems .append ("setup asked the model host for more than the model's file: " + ", " .join (wrong [:4 ])) 308if NO_DRAFT_LINE not in out : 309problems .append ("setup did not say that the model list has no draft layer" ) 310if "Downloading the draft layer" in out : 311problems .append ("setup announced a draft layer download for a model with `drafter: none`" ) 312if shape is TINY or shape ["layers" ]!= 48 : 313if NEUTRAL_LINE not in out : 314problems .append ("setup did not say it made a neutral expert profile (F4)" ) 315cfgs = [p for p in newest (install ,"*.json" )if "run" in p .name .lower ()or p .parent .name in ("configs" ,"run" )]or newest (install ,"config*.json" ) 316configs = [p for p in newest (install ,"*.json" )if _is_run_config (p )] 317config = configs [- 1 ]if configs else None 318if config is None : 319problems .append ("no run config was written" ) 320else : 321problems += config_problems (config ,data ,install ,out ) 322extra = sorted (str (p .relative_to (work ))for p in work .rglob ("experts.bin*" )) 323if extra :# F5: the low-RAM mode copies the experts into a second file 324problems .append ("a second copy of the experts was written: " + ", " .join (extra [:3 ])) 325# run 2: a finished install is left alone and downloads nothing 326before = len (mirror .seen ) 327mtime = config .stat ().st_mtime if config else None 328t = time .time () 329code2 ,out2 = run_setup (env ,data , []) 330log (f"setup run 2: exit { code2 } in { time . time () - t :.0f } s" ) 331if code2 != 0 : 332problems .append (f"the second setup run exited { code2 } " ) 333if len ([p for p in mirror .seen [before :]if "/resolve/" in p and "Range" not in p ])and ("Downloading" in out2 ): 334problems .append ("the second run downloaded the model again" ) 335for bad in ("Traceback" ,"KeyError" ): 336if bad in out2 : 337problems .append (f"the second run printed { bad !r } " ) 338return {"problems" :problems ,"config" :config ,"out" :out ,"work" :work ,"data" :data } 339 340 341def _is_run_config (p :Path )-> bool : 342try : 343d = json .loads (p .read_text (encoding = "utf-8-sig" )) 344except (OSError ,ValueError ): 345return False 346return isinstance (d ,dict )and "args" in d and ("exe" in d or "model_name" in d ) 347 348 349def config_problems (config :Path ,data :Path ,install :Path ,out :str )-> list [str ]: 350problems = [] 351d = json .loads (config .read_text (encoding = "utf-8-sig" )) 352args = [str (a )for a in d .get ("args" , [])] 353text = " " .join (args ) 354if not any (a .endswith (".gguf" )or ".gguf" in a for a in args )and "--model" not in args : 355problems .append ("the run config names no model file" ) 356if d .get ("backend" )== "metal" :# a Mac (setup's mac_control_setup): the Metal engine maps the GGUF in place, its arena is its RAM budget 357if "--mmap-experts" not in args : 358problems .append ("the Mac run config has no --mmap-experts (the experts read in place from the GGUF)" ) 359elif "--resident-budget-gib" not in args :# F5: a feed qwen4exp size is read in place with a RAM budget of its experts 360problems .append ("the run config has no --resident-budget-gib (the RAM budget of the experts)" ) 361profiles = [a for a in args if "expert-profile" in a ] 362if not profiles : 363problems .append ("the run config names no expert profile" ) 364else : 365for pr in profiles : 366if pr .startswith ("--" ): 367continue 368if not Path (pr ).is_file (): 369problems .append (f"the expert profile { pr } is not a file" ) 370return problems 371 372 373def start_engine (config :Path ,engine :Path ,work :Path ,log )-> list [str ]: 374"""Step 5: the engine of the run config, one request. The engine folder replaces the config's `component:` engine.""" 375problems :list [str ]= [] 376d = json .loads (config .read_text (encoding = "utf-8-sig" )) 377exe = next ((p for p in (engine / "strata" ,engine / "strata.exe" ,engine / "bin" / "strata" ,engine / "bin" / "strata.exe" )if p .is_file ()),None ) 378if exe is None : 379return [f"no strata engine program in { engine } " ] 380port = free_port () 381cfg = dict (d ,exe = str (exe ),port = port ,host = "127.0.0.1" )# the config's `component:strata-engine` is this engine folder 382cfg_file = work / "engine-run.json" 383cfg_file .write_text (json .dumps (cfg ),encoding = "utf-8" ) 384env = dict (os .environ ,PYTHONUTF8 = "1" ) 385env .update ({k :str (v )for k ,v in (d .get ("env" )or {}).items ()}) 386libs = [str (engine )]+ [str (x )for x in d .get ("lib_dirs" , [])] 387env ["LD_LIBRARY_PATH" ]= os .pathsep .join (libs + [env .get ("LD_LIBRARY_PATH" ,"" )]) 388args = [sys .executable ,"-m" ,"serve.server" ,"--engine" ,"strata" ,"--config" ,str (cfg_file ),"--port" ,str (port ),"--host" ,"127.0.0.1" ] 389logfile = work / "engine.log" 390with logfile .open ("wb" )as lf : 391proc = subprocess .Popen (args ,cwd = str (ROOT ),env = env ,stdout = lf ,stderr = subprocess .STDOUT ) 392try : 393deadline ,ready = time .time ()+ 600 ,False 394while time .time ()< deadline and proc .poll ()is None : 395try : 396urllib .request .urlopen (f"http://127.0.0.1: { port } /v1/models" ,timeout = 3 ).read () 397ready = True 398break 399except OSError : 400time .sleep (2 ) 401if not ready : 402return ["the engine did not come up: " + logfile .read_text (errors = "replace" )[- 500 :]] 403models = json .loads (urllib .request .urlopen (f"http://127.0.0.1: { port } /v1/models" ,timeout = 10 ).read ()) 404body = json .dumps ({"model" :models ["data" ][0 ]["id" ],"messages" : [{"role" :"user" ,"content" :"What is the capital of France?" }],"max_tokens" :24 , 405"temperature" :0 }).encode () 406req = urllib .request .Request (f"http://127.0.0.1: { port } /v1/chat/completions" ,body , {"Content-Type" :"application/json" }) 407reply = json .loads (urllib .request .urlopen (req ,timeout = 600 ).read ()) 408usage = reply .get ("usage" )or {} 409log (f"one request: finish { reply [ 'choices' ][ 0 ]. get ( 'finish_reason' ) } , usage { usage } " ) 410if not usage .get ("completion_tokens" ): 411problems .append ("the request returned no completion tokens" ) 412if reply ["choices" ][0 ].get ("finish_reason" )not in ("length" ,"stop" ): 413problems .append ("the request did not finish normally" ) 414except Exception as e :# noqa: BLE001 415problems .append (f"the request failed: { e } " ) 416finally : 417if proc .poll ()is None : 418proc .terminate () 419try : 420proc .wait (30 ) 421except subprocess .TimeoutExpired : 422proc .kill () 423return problems 424 425 426def main (argv = None )-> int : 427ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 428ap .add_argument ("--tokenizer-from" ,help = "a real qwen4exp GGUF (shard 1): the synthetic file gets its tokenizer (needed by --engine)" ) 429ap .add_argument ("--engine" ,type = Path ,help = "an engine folder built for the file's shape: step 5 starts it and sends one request (needs --full)" ) 430ap .add_argument ("--full" ,action = "store_true" ,help = "the 4-layer q4_lite stand-in of the rehearsal instead of the small file (3.5 GB with a real tokenizer)" ) 431ap .add_argument ("--work" ,type = Path ,help = "scratch folder (default: a new temp folder, removed at the end unless --keep)" ) 432ap .add_argument ("--keep" ,action = "store_true" ) 433a = ap .parse_args (argv ) 434if a .engine and not a .full : 435"--engine needs --full: the engine is built for one shape, the small file is another" ,file = sys .stderr ) 436return 2 437log = lambda s :time .strftime ("%H:%M:%S" ),s ,flush = True )# noqa: E731 438try : 439check_gguf_tools () 440except NotRun as e : 441"NOT RUN:" ,e ) 442return 2 443work = a .work or Path (tempfile .mkdtemp (prefix = "strata-feed-install-gate-" )) 444if a .work : 445if work .exists ()and any (work .iterdir ()): 446"--work needs a new or empty folder" ,file = sys .stderr ) 447return 2 448work .mkdir (parents = True ,exist_ok = True ) 449code = 1 450try : 451res = check (work ,a .tokenizer_from ,FULL if a .full else TINY ,log ) 452problems = res ["problems" ] 453if not problems and a .engine : 454ep = start_engine (res ["config" ],a .engine ,work ,log ) 455if ep : 456problems ,code = ep ,3 457if problems : 458"FAIL:" ) 459for p in problems : 460" -" ,p ) 461"---- setup output (tail) ----" ) 462"\n" .join (res ["out" ].splitlines ()[- 40 :])) 463code = code if code == 3 else 1 464else : 465"PASS: feed model installed from a real file" + (" and answered one request" if a .engine else "" )) 466code = 0 467except NotRun as e : 468"NOT RUN:" ,e ) 469code = 2 470finally : 471if a .keep : 472"kept" ,work ) 473else : 474shutil .rmtree (work ,ignore_errors = True ) 475return code 476 477 478if __name__ == "__main__" : 479sys .exit (main ())