okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3dcdb99a7
main
1"""Drive each entry point for one (machine class, model set) and return what the engine would be started with, normalized. 2 3A record has the same shape for every entry point: 4 5entry which one 6command what the person (or the app) asked for, in words 7fetches what the drafter fetch was asked to download: file name, variant, backend (nothing is downloaded) 8setup_args what the entry point hands to setup.py (Terminal launch only) 9config_file the run config the entry point leaves on disk (normalized) 10engine {exe, argv, env_set, notes}: what serve/server.py would start: engine_args(cfg, exe) and the variables child_env(cfg) adds 11not_driven (setup only) present instead of the above for a class whose setup is another script (Intel Arc, Mac), with the reason 12""" 13 14from __future__import annotations 15 16import contextlib 17import io 18import json 19import os 20import subprocess 21import sys 22from pathlib import Path 23from unittest import mock 24 25from .matrix import ModelSet 26from .normalize import normalize 27from .world import ROOT ,World ,context_for 28 29HERE = Path (__file__ ).resolve ().parent 30 31 32def run_cli (argv :list [str ])-> tuple [int ,str ,str ]: 33from strata_cli .cli import main 34out ,err = io .StringIO (),io .StringIO () 35saved = dict (os .environ )# main() sets variables on its own process for the programs it starts (GGML_NO_BACKTRACE, strata_control/childenv.py): that is 36try :# the command's doing, not the machine's, so it must not become the baseline the engine's environment is compared with 37with contextlib .redirect_stdout (out ),contextlib .redirect_stderr (err ): 38try : 39code = main (argv ) 40except SystemExit as e : 41code = int (e .code or 0 )if not isinstance (e .code ,str )else 1 42finally : 43os .environ .clear () 44os .environ .update (saved ) 45return code ,out .getvalue (),err .getvalue () 46 47def engine_start (world :World ,cfg :dict )-> dict : 48"""What serve/server.py hands to the engine for this run config: the arguments (engine_args) and the variables child_env adds to the environment.""" 49from serve import server 50baseline = dict (os .environ ) 51notes = io .StringIO () 52with contextlib .redirect_stdout (notes ): 53argv = server .engine_args (dict (cfg ),cfg ["exe" ]) 54env = server .child_env (dict (cfg )) 55env_set = {k :v for k ,v in sorted (env .items ())if baseline .get (k )!= v } 56return {"exe" :cfg ["exe" ],"argv" : [str (a )for a in argv ],"env_set" :env_set , 57"notes" : [l for l in notes .getvalue ().splitlines ()if l .strip ()]} 58 59 60def setup_fetches_layer (world :World ,args :list [str ])-> None : 61"""setup.py's step 6 on a computer without the draft layer: fetched unless setup is told "--mtp off" or "--drafter dflash2" (setup.py ~10327).""" 62word = args [args .index ("--mtp" )+ 1 ]if "--mtp" in args else None 63drafter = args [args .index ("--drafter" )+ 1 ]if "--drafter" in args else None 64if word == "off" or drafter == "dflash2" or (world .mtp / "experts.bin" ).exists (): 65return 66world .mtp .mkdir (parents = True ,exist_ok = True ) 67 (world .mtp / "experts.bin" ).write_bytes (b"e" ) 68 (world .mtp / "draft_vocab.bin" ).write_bytes (b"v" ) 69 (world .data / "mtp" / "mtp-q2_0.gguf" ).write_bytes (b"m" ) 70world .fetches .append ({"call" :"setup_mtp_layer" }) 71 72 73def drive_launch (world :World ,extra :tuple [str , ...]= (),setup_runs :bool | str = False ,fresh :bool = False )-> dict : 74"""`strata launch --model <set> --yes --no-tui` through the real command, with the engine start, the model download and the tuning replaced. 75`extra`: more words for the command (`--drafting off`), for the tests that launch several times in one world. `setup_runs`: setup runs at this launch 76(as it does at every launch whose --model-path or data folder the installed copy does not match, runner.installed_serves_request) and leaves the 77draft-layer word in the installed config as strata_control/setup_config.py writes it: the stand-in config afresh, "--mtp off" -> "mtp": false (and no --mtp 78in the args), "--mtp on" -> true, no word -> the earlier value kept (setup.carry_over). 79"when_needed": only when ensure_model would not reuse the installed copy (the record then says "setup_ran"). 80`fresh`: a computer without the draft layer (World.fresh): setup's step 6 is simulated too (setup_fetches_layer), and the record has the plan's parts 81(`plan_parts`, Runner.model_state() before setup) and its drafting line (`plan_drafting`).""" 82from strata_cli .launch import catalog as C ,runner as R 83seen :dict = {} 84cat = C .Catalog (root = world .install ,hardware = world .hardware_report ()) 85 86def ensure_model (self ): 87if fresh : 88seen ["plan_parts" ]= [p .kind for p in self .model_state ().parts ] 89seen ["plan_drafting" ]= self .drafting_plan_line () 90seen ["setup_args" ]= args = self .setup_args () 91runs = setup_runs 92if runs == "when_needed" :# ensure_model's own test for reusing the installed copy 93path ,desc = self .installed_state () 94runs = not (path is not None and desc is not None and R .desc_matches (desc ,self .s )and not R .files_present (R .read_config (path )) 95and not self .layer_back (path )and self .installed_serves_request (path )) 96seen ["setup_ran" ]= bool (runs ) 97if runs :# setup writes the config afresh and carries an earlier "mtp" over unless --mtp is given 98from strata_control import draft_layer 99if fresh : 100setup_fetches_layer (world ,args ) 101self .note_setup_lines (getattr (world ,"setup_said" , []))# what setup printed (a test sets it: mtp_fetch's offline line) 102old = json .loads (world .config_path .read_text (encoding = "utf-8" ))if world .config_path .exists ()else {} 103cfg = world .base_config () 104word = args [args .index ("--mtp" )+ 1 ]if "--mtp" in args else None 105if word is not None : 106cfg ["mtp" ]= word != "off" 107elif "mtp" in old : 108cfg ["mtp" ]= old ["mtp" ] 109draft_layer .apply (cfg ) 110world .config_path .write_text (json .dumps (cfg ,indent = 1 ),encoding = "utf-8" ) 111return world .config_path 112 113with mock .patch .object (C ,"Catalog" ,lambda * a ,** k :cat ), \ 114mock .patch .object (R .Runner ,"ensure_engine" ,lambda self :None ), \ 115mock .patch .object (R .Runner ,"ensure_model" ,ensure_model ), \ 116mock .patch .object (R .Runner ,"tune" ,lambda self :None ), \ 117mock .patch .object (R .Runner ,"start" ,lambda self :seen .setdefault ("started" ,True )and None ), \ 118mock .patch .object (R .Runner ,"open_access" ,lambda self :None ), \ 119mock .patch .object (R .Runner ,"check_serving" ,lambda self :None ): 120command = ["launch" ,"--model" ,world .mset .model ,"--yes" ,"--no-tui" ,"--context" ,str (context_for (world .machine ,world .mset )),* extra ] 121orig_run = R .Runner .run 122 123def run (self ,** kw ): 124seen ["runner" ]= self 125return orig_run (self ,** kw ) 126 127with mock .patch .object (R .Runner ,"run" ,run ): 128code ,out ,err = run_cli (command ) 129runner = seen .get ("runner" ) 130if code != 0 or runner is None or runner .config_path is None : 131return {"entry" :"launch" ,"command" :"strata " + " " .join (command ),"failed" : {"exit" :code ,"stderr" :err [- 400 :],"stdout" :out [- 400 :]}} 132cfg = json .loads (Path (runner .config_path ).read_text (encoding = "utf-8" )) 133return {"entry" :"launch" ,"command" :"strata " + " " .join (command ),"fetches" :list (world .fetches ), 134"setup_args" :seen .get ("setup_args" ),"config_file" :cfg ,"engine" :engine_start (world ,cfg ), 135** ({"setup_ran" :seen .get ("setup_ran" )}if setup_runs else {}), 136** ({"plan_parts" :seen .get ("plan_parts" ),"plan_drafting" :seen .get ("plan_drafting" ),"notices" :list (runner .notices )}if fresh else {})} 137 138 139def drive_app (world :World ,which :str )-> dict : 140"""The app's Load, in a Node process: the host's own createNativeControl with a fake Control for everything but the Drafting calls, which go through the 141real strata_control (python -m tests.snapshot.control_shim) on the same simulated machine. Returns the run config the host wrote and the Python side's 142engine start for it.""" 143node = os .environ .get ("STRATA_SNAPSHOT_NODE" )or "node" 144world_file = world .root / "world.json" 145world_file .write_text (json .dumps ({"machine" :world .machine .key ,"set" :world .mset .key ,"root" :str (world .root )}),encoding = "utf-8" ) 146env = {** os .environ ,"STRATA_SNAPSHOT_PYTHON" :sys .executable ,"STRATA_SNAPSHOT_REPO" :str (ROOT )} 147proc = subprocess .run ([node ,str (HERE / "app_driver.mjs" ),str (world_file ),which ],cwd = str (ROOT ),env = env ,capture_output = True ,text = True ,timeout = 240 ) 148last = [l for l in proc .stdout .splitlines ()if l .startswith ("SNAPSHOT-RESULT " )] 149if proc .returncode != 0 or not last : 150return {"entry" :"app_" + which ,"failed" : {"exit" :proc .returncode ,"stderr" :proc .stderr [- 1500 :],"stdout" :proc .stdout [- 800 :]}} 151got = json .loads (last [- 1 ][len ("SNAPSHOT-RESULT " ):]) 152cfg = got .get ("config_file" ) 153out = {"entry" :"app_" + which ,"command" :got .get ("command" ),"fetches" :got .get ("fetches" ),"control_calls" :got .get ("control_calls" ),"config_file" :cfg } 154if cfg : 155with world .patched (): 156out ["engine" ]= engine_start (world ,cfg ) 157return out 158 159 160def drive (machine_key :str ,set_key :str ,entry :str ,root :Path | None = None )-> dict : 161"""One record, normalized. A fresh scratch world every time.""" 162from .matrix import machine as get_machine ,model_set as get_set 163world = World (get_machine (machine_key ),get_set (set_key ),root ).build () 164try : 165if entry == "setup" : 166from .setup_driver import drive_setup 167rec = drive_setup (world ) 168elif entry == "launch" : 169with world .patched (): 170rec = drive_launch (world ) 171elif entry in ("app_plain" ,"app_models" ): 172rec = drive_app (world ,entry [4 :]) 173else : 174raise ValueError (entry ) 175return normalize (rec ,world ) 176finally : 177world .close ()