okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""setup.py on a Mac: Apple Silicon, the Metal engine (metal/), built from source on the Mac. 2 3./setup.sh [options] (setup.py hands a macOS run to this file; the PC paths are not used) 4 5What it does, each step skipped when it is already done: 6 71. checks the Mac: Apple Silicon, the chip, unified memory, macOS version, the Command Line Tools, free disk 82. recommends a model by memory (recommend, never force: an explicit --model is kept, with what it risks) 93. installs the Python packages into .venv (cmake and ninja come from pip, just before step 4: no Homebrew, no sudo) 104. builds the Metal engine from source: metal-cpp (Apple's headers) and the vendored ggml (third_party/strata-ggml) 115. downloads the model (setup.py's downloader: resumable, the pinned revision) 126. prepares the model: the native pack (tools/iq_pack.py) and the MTP draft layer (tools/mtp_fetch.py, mtp_pack.py) 137. writes strata-<model>.json and run-<model>.sh with the Metal defaults (--spec 2, the Q8_0 hyper-connection 14read) and starts the server (serve/server.py), the same as on a PC 15 16Everything shared - the model table, the downloader, the config and run-script writers, the server - is setup.py's. 17""" 18from __future__import annotations 19 20import argparse 21import atexit 22import hashlib 23import json 24import os 25import platform 26import shutil 27import subprocess 28import sys 29import zipfile 30from pathlib import Path 31 32ROOT = Path (__file__ ).resolve ().parent .parent 33sys .path .insert (0 ,str (ROOT )) 34import setup as S # noqa: E402 35from strata_control import mac_fit as _fit # noqa: E402 36from strata_control .mac_fit import (# noqa: E402,F401 (re-exported: the tests and callers use these names here) 37BIG_MAC_GB ,CONTEXTS ,GIB_GB ,GPU_SHARE ,MAC_ABOUT ,MAC_MODELS ,MIN_MACOS ,OVERHEAD_GB ,RECOMMENDED , 38RESIDENT_LEAVE_SHARE ,STREAM_COPY_GAIN ,STREAM_MEASURED ,STREAM_MTP_FROM_GB ,STREAM_SPEC ,TESTED_CONTEXT , 39_sysctl ,gpu_budget_gb ,mac_info ,mac_problems ,macos_tuple ,model_need_gb ,model_note ,recommend_context , 40recommend_model ,stream_mtp ,streams ) 41 42# Apple's metal-cpp headers for the macOS 26 SDK (https://developer.apple.com/metal/cpp/), pinned by SHA-256 43METAL_CPP_URL = "https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip" 44METAL_CPP_SHA256 = "4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4" 45BUILD_DIR = ROOT / "build-metal" 46EXE = BUILD_DIR / "strata" 47 48# the Unsloth files at setup.py's pinned revision: name -> (bytes, SHA-256), the Hub's LFS pointers (UD-Q4_K_XL's 49# are setup.py's UNSLOTH_SHARDS) 50UD_SHARDS = { 51"Qwen3.8-Flash-Next-UD-Q5_K_XL-00001-of-00006.gguf" : (10946618 ,"610922cdb1afe1094e95d7a3e86b12ee33317ebbf7320ac9344e21b6ae4bb69f" ), 52"Qwen3.8-Flash-Next-UD-Q5_K_XL-00002-of-00006.gguf" : (682434912 ,"494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e" ), 53"Qwen3.8-Flash-Next-UD-Q5_K_XL-00003-of-00006.gguf" : (54400261312 ,"34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20" ), 54"Qwen3.8-Flash-Next-UD-Q5_K_XL-00004-of-00006.gguf" : (49990245824 ,"9ee6bbe462e6830864382d629101490625b1c95afa15492b7ad550c7bed2dd13" ), 55"Qwen3.8-Flash-Next-UD-Q5_K_XL-00005-of-00006.gguf" : (49882416192 ,"0b2437f661f584030cb5aeb8fb1bb70f6422518a6746bfcc0304167c7b6b8beb" ), 56"Qwen3.8-Flash-Next-UD-Q5_K_XL-00006-of-00006.gguf" : (3320101792 ,"55dd96c5ad0863b06b6393151b9ad0ac727b8d58a62e02a296ca5d5ddbfee4a3" ), 57"Qwen3.8-Flash-Next-UD-Q6_K_XL-00001-of-00006.gguf" : (10946624 ,"8bdc6bad55b6699f46f60708829932ff4018d7ac9bd309c388534fa31753bdb7" ), 58"Qwen3.8-Flash-Next-UD-Q6_K_XL-00002-of-00006.gguf" : (682434912 ,"494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e" ), 59"Qwen3.8-Flash-Next-UD-Q6_K_XL-00003-of-00006.gguf" : (54400261312 ,"34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20" ), 60"Qwen3.8-Flash-Next-UD-Q6_K_XL-00004-of-00006.gguf" : (49814108512 ,"0ea4b599880a5a52fcd9c188ba1443f646c69c96571904ddbd6a79246a01a997" ), 61"Qwen3.8-Flash-Next-UD-Q6_K_XL-00005-of-00006.gguf" : (49419317344 ,"9948e81ae8368144b135a7403d8c0f2cf9a6c2f9f692313865855b2832e696c9" ), 62"Qwen3.8-Flash-Next-UD-Q6_K_XL-00006-of-00006.gguf" : (14838313984 ,"e4ae255234f42b18012f6d6eec5bf615b57479b7e0a0233c47436a321ffeec3f" ), 63} 64 65 66def model_shard_names (model :str )-> list [str ]: 67"""The model's files in order (shard 1 first).""" 68n = MAC_MODELS [model ].get ("shards" ,2 ) 69if MAC_MODELS [model ].get ("family" )== "gyro" :# agentionai's one file (the n-gram table is inside it) 70return [S .model_file (S .FAMILIES ["gyro" ],model ,1 )] 71if S .FAMILIES .get (MAC_MODELS [model ].get ("family" ,"qwen" ), {}).get ("feed" ):# a model of the signed feed: its files as the feed names them 72return [S .model_file (S .FAMILIES [MAC_MODELS [model ]["family" ]],model ,i )for i in range (1 ,n + 1 )] 73if MAC_MODELS [model ].get ("family" )== "unsloth" :# (setup.py's model_file: the v3.1 UD-IQ4_XS is named UD-IQ4_XS on the Hub) 74return [S .model_file (S .FAMILIES ["unsloth" ],model ,i )for i in range (1 ,n + 1 )] 75return [S .model_file (S .FAMILIES ["qwen" ],model ,i )for i in range (1 ,n + 1 )] 76 77 78def shard_sha (name :str ): 79return UD_SHARDS .get (name )or getattr (S ,"UNSLOTH_SHARDS" , {}).get (name )or getattr (S ,"UNSLOTH_V31_SHARDS" , {}).get (name ) 80 81 82# ------------------------------------------------------------------------------------------------ the Mac 83# ------------------------------------------------------------------------------------------------ the engine 84def metal_cpp ()-> Path : 85"""Apple's metal-cpp headers in third_party/metal-cpp (one zip, pinned).""" 86dst = ROOT / "third_party" / "metal-cpp" 87if (dst / "Metal" / "Metal.hpp" ).exists (): 88return dst 89z = ROOT / "third_party" / "metal-cpp_26.zip" 90S .download (METAL_CPP_URL ,z ,"metal-cpp (Apple's Metal headers)" ) 91S .verify_sha256 (z ,z .stat ().st_size ,METAL_CPP_SHA256 ) 92tmp = ROOT / "third_party" / "_metal_cpp" 93shutil .rmtree (tmp ,ignore_errors = True ) 94with zipfile .ZipFile (z )as f : 95f .extractall (tmp ) 96shutil .rmtree (dst ,ignore_errors = True ) 97shutil .move (str (tmp / "metal-cpp" ),str (dst )) 98shutil .rmtree (tmp ,ignore_errors = True ) 99return dst 100 101 102def tool (name :str )-> str : 103"""cmake / ninja from the venv's pip packages (no Homebrew).""" 104p = Path (sys .executable ).parent / name 105return str (p )if p .exists ()else (shutil .which (name )or name ) 106 107 108def engine_current ()-> bool : 109try : 110meta = json .loads ((BUILD_DIR / "BUILD.json" ).read_text (encoding = "utf-8" )) 111except (OSError ,ValueError ): 112return False 113return EXE .exists ()and meta .get ("version" )== S .source_version ()and meta .get ("source" )== source_digest () 114 115 116def source_digest ()-> str : 117"""What the engine is built from: every source file's path, size and modification time (src/, include/, metal/, 118third_party/ggml, third_party/strata-ggml). A git pull, an unzipped update or a local edit changes it; nothing else does.""" 119h = hashlib .sha256 () 120for d in ("src" ,"include" ,"metal" ,"third_party/ggml" ,"third_party/strata-ggml" ): 121for f in sorted ((ROOT / d ).rglob ("*" )): 122if f .is_file ()and f .suffix in (".cpp" ,".cu" ,".h" ,".hpp" ,".mm" ,".metal" ,".inc" ,".txt" ,".cuh" ): 123st = f .stat () 124h .update (f" { f . relative_to ( ROOT ). as_posix () } | { st . st_size } | { int ( st . st_mtime ) } \n" .encode ()) 125return h .hexdigest () 126 127 128def build_engine (llama :Path ,jobs :int | None = None )-> Path : 129"""The Metal engine from source: cmake + ninja (pip's), Apple's clang from the Command Line Tools.""" 130if engine_current (): 131S .ok (f"Metal engine: { EXE } (built for this source)" ) 132return EXE 133mcpp = metal_cpp () 134S .ensure_build_tools ()# cmake and ninja are in requirements-build.txt, not requirements.txt (#3403) 135S .say (" Building the Metal engine from source (5-15 minutes the first time) ..." ) 136BUILD_DIR .mkdir (exist_ok = True ) 137log = BUILD_DIR / "build.log" 138env = dict (os .environ ,PATH = str (Path (sys .executable ).parent )+ os .pathsep + os .environ .get ("PATH" ,"" )) 139cfg = [tool ("cmake" ),"-S" ,str (ROOT / "metal" ),"-B" ,str (BUILD_DIR ),"-G" ,"Ninja" ,"-DCMAKE_BUILD_TYPE=Release" , 140f"-DCMAKE_MAKE_PROGRAM= { tool ( 'ninja' ) } " ,f"-DMETAL_CPP_DIR= { mcpp } " ,* S .ggml_defs (llama )] 141build = [tool ("ninja" ),"-C" ,str (BUILD_DIR ),"strata" ]+ (["-j" ,str (jobs )]if jobs else []) 142with open (log ,"w" ,encoding = "utf-8" )as f : 143for cmd in (cfg ,build ): 144rc = subprocess .call (cmd ,stdout = f ,stderr = subprocess .STDOUT ,env = env ) 145if rc != 0 : 146S .fail (f"the Metal engine did not build (see { log } )" , 147"the last lines of the log name the problem; the Command Line Tools must be up to date " 148"(softwareupdate --list)" ) 149 (BUILD_DIR / "BUILD.json" ).write_text (json .dumps ({"version" :S .source_version (),"source" :source_digest (), 150"backend" :"metal" },indent = 1 ),encoding = "utf-8" ) 151S .ok (f"Metal engine built: { EXE } " ) 152return EXE 153 154 155# ------------------------------------------------------------------------------------------------ the config 156def engine_args (pack :Path ,shards :list ,rt :Path ,ctx :int ,stream :bool = False ,ram_gb :float = 0.0 , 157model :str = "" )-> list [str ]: 158"""The Metal defaults (strata_control/mac_fit.py), with this checkout's expert profile.""" 159return _fit .engine_args (pack ,shards ,rt ,ctx ,stream ,ram_gb ,ROOT / "data" / "expert-profile.bin" ,model ) 160 161 162# the image encoder's projector (setup.py's pinned revision): name -> (bytes, SHA-256) 163VISION_SHA256 = {"mmproj-Qwen3.8-Flash-Next-BF16.gguf" : 164 (907543008 ,"b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0" )} 165VISION_EXE = ROOT / "build-vision" / "bin" / "strata-vision" 166 167 168def build_vision (llama :Path )-> Path : 169"""strata-vision (tools/vision: llama.cpp's mtmd at the pinned commit), with ggml's Metal backend: the encoder 170runs on the GPU.""" 171stamp = ROOT / "build-vision" / "BUILD.json" 172src = source_digest () 173try : 174if VISION_EXE .exists ()and json .loads (stamp .read_text (encoding = "utf-8" )).get ("source" )== src : 175S .ok (f"image encoder: { VISION_EXE } " ) 176return VISION_EXE 177except (OSError ,ValueError ): 178pass 179S .ensure_build_tools () 180S .say (" Building the image encoder (1-3 minutes) ..." ) 181env = dict (os .environ ,PATH = str (Path (sys .executable ).parent )+ os .pathsep + os .environ .get ("PATH" ,"" )) 182log = ROOT / "build-vision.log" 183with open (log ,"w" ,encoding = "utf-8" )as f : 184for cmd in ([tool ("cmake" ),"-S" ,str (ROOT / "tools" / "vision" ),"-B" ,str (ROOT / "build-vision" ),"-G" ,"Ninja" , 185"-DCMAKE_BUILD_TYPE=Release" ,f"-DCMAKE_MAKE_PROGRAM= { tool ( 'ninja' ) } " ,f"-DLLAMA_DIR= { S . vision_llama ( llama ) } " , 186"-DSTRATA_VISION_CUDA=OFF" ,"-DSTRATA_VISION_METAL=ON" ,"-DSTRATA_PORTABLE=OFF" ], 187 [tool ("ninja" ),"-C" ,str (ROOT / "build-vision" ),"strata-vision" ]): 188if subprocess .call (cmd ,stdout = f ,stderr = subprocess .STDOUT ,env = env )!= 0 : 189S .fail (f"the image encoder did not build (see { log } )" ) 190stamp .write_text (json .dumps ({"source" :src }),encoding = "utf-8" ) 191S .ok (f"image encoder built: { VISION_EXE } " ) 192return VISION_EXE 193 194 195def ple_shard (files :list )-> Path : 196"""The shard that holds the n-gram table (per_layer_token_embd).""" 197sys .path .insert (0 ,str (ROOT / "metal" / "tools" )) 198import metal_repack as R 199for f in files : 200rd = R .Reader (f ) 201rd .f .close () 202if any (t ["name" ]== R .PLE for t in rd .tensors ): 203return f 204S .fail (f"no shard of { files [ 0 ]. name } holds the n-gram table (per_layer_token_embd)" ) 205 206 207# the experts' streaming copy (metal/tools/stream_experts.py): what stays free on the disk after it is written 208EXPERTS_MARGIN_GB = 10.0 209 210 211def experts_file_fits (need_gb :float ,free_gb :float )-> bool : 212return free_gb >= need_gb + EXPERTS_MARGIN_GB 213 214 215def experts_file (native :Path )-> None : 216"""A streaming Mac: <model>.experts beside the GPU's GGUF - every expert's rows in one piece, read with one SSD 217request per expert instead of three (the engine uses it when it is there and matches; else the GGUF). Written 218only when the disk has room for it and EXPERTS_MARGIN_GB more; otherwise setup says so and goes on.""" 219out = native .with_name (native .name + ".experts" ) 220if out .exists ()and S .done (out ): 221S .ok (f"the experts' streaming copy: { out . name } " ) 222return 223sys .path .insert (0 ,str (ROOT / "metal" / "tools" )) 224import stream_experts as X 225need = X .size_bytes (native )/ 1e9 226free = S .free_gb (native .parent ) 227if not os .access (native .parent ,os .W_OK ): 228S .warn (f" { native . parent } cannot be written: the experts' streaming copy ( { need :.0f } GB) is not written; the " 229f"engine streams from the model file ( { STREAM_COPY_GAIN } slower)" ) 230return 231if not experts_file_fits (need ,free ): 232S .warn (f"the experts' streaming copy needs { need :.0f } GB and { EXPERTS_MARGIN_GB :.0f } GB to spare on the disk " 233f"( { free :.0f } GB free): not written; the engine streams from the model file ( { STREAM_COPY_GAIN } " 234f"slower). Free some space and run ./setup.sh --setup again to add it" ) 235return 236S .say (f" Writing the experts in SSD-read order (one time, { need :.0f } GB; each expert is read with one request) ..." ) 237S .run ([sys .executable ,str (ROOT / "metal" / "tools" / "stream_experts.py" ),"--gguf" ,str (native ),"--verify" ]) 238S .mark (out ) 239S .ok (f"the experts' streaming copy: { out . name } " ) 240 241 242def mac_config (exe :Path ,args :list ,pack :Path ,model_name :str ,tag :str ,port :int )-> dict : 243return {"exe" :str (exe ),"args" :args ,"cwd" :str (ROOT ),"tokenizer" :str (pack / "tokenizer" ), 244"model_name" :model_name ,"log" :str (ROOT / f"strata- { tag . lower () } .log" ),"lib_dirs" : [],"port" :port , 245"backend" :"metal" } 246 247 248def mac_configs ()-> list [Path ]: 249out = [] 250for p in S .installed_configs (): 251try : 252if json .loads (p .read_text (encoding = "utf-8-sig" )).get ("backend" )== "metal" : 253out .append (p ) 254except (OSError ,ValueError ): 255pass 256return out 257 258 259REPACK_LOCK = ".repack.lock" # metal_repack.py: <out>.repack.lock holds the repack's pid while it runs 260PREPARE_LOCK = ".preparing.lock" # setup: beside the repacked file, holds setup's pid from the repack to the end of the pack 261 262 263def _pid_alive (pid :int )-> bool : 264try : 265os .kill (pid ,0 ) 266except PermissionError : 267return True # it exists, it is somebody else's 268except OSError : 269return False 270return True 271 272 273def repack_running (folder :Path )-> list [int ]: 274"""Pids of repacks (metal_repack.py) or setup's own model preparation (repack + pack) still running for the files in 275`folder`. A stale lock (its process gone) is removed. The repack and the pack move 100+ GB through the disk and one 276holds up to 20 GB of memory: an engine with a 70-90 GB footprint beside them is what froze the 128 GB M5 Max twice 277(watchdog panics, 2026-10-13).""" 278pids = [] 279if not folder .is_dir (): 280return pids 281for lock in [* folder .glob ("*" + REPACK_LOCK ),folder / PREPARE_LOCK ]: 282try : 283pid = int (lock .read_text ().strip ()) 284except (OSError ,ValueError ): 285continue 286if pid != os .getpid ()and _pid_alive (pid ): 287pids .append (pid ) 288elif pid != os .getpid (): 289try : 290lock .unlink () 291except OSError : 292pass 293return pids 294 295 296def engine_pids (run = subprocess .run )-> list [int ]: 297"""Pids of the running Metal engines (`strata`, the executable setup builds) that belong to THIS user. On a shared Mac 298another person's engine is theirs to stop: `pgrep -x strata` alone saw it and sent setup away with "stop the server" for a 299window the person could not close (M5 Max, 2026-10-31).""" 300cmd = ["pgrep" ,"-x" ,"strata" ] 301if hasattr (os ,"getuid" ): 302cmd [1 :1 ]= ["-u" ,str (os .getuid ())] 303try : 304out = run (cmd ,capture_output = True ,text = True ,timeout = 10 ).stdout 305except (OSError ,subprocess .SubprocessError ): 306return [] 307return [int (x )for x in out .split ()if x .isdigit ()and int (x )!= os .getpid ()] 308 309 310def start (cfg_path :Path ,port :int | None ,open_browser :bool = True )-> int : 311"""serve/server.py with this config (setup.py's start without the NVIDIA / AMD card checks).""" 312cfg = json .loads (cfg_path .read_text (encoding = "utf-8-sig" )) 313missing = [p for p in [cfg ["exe" ],* [a for a in cfg ["args" ]if a .endswith (".gguf" )]]if not Path (p ).exists ()] 314if missing : 315S .fail (f" { cfg_path . name } refers to missing files: { missing [ 0 ] } " ,"run ./setup.sh --setup to repair it" ) 316busy = [p for g in cfg ["args" ]if g .endswith (".gguf" )for p in repack_running (Path (g ).parent )] 317if busy :# never start an engine while a repack (or the pack after it) is writing: wait would hide a stuck one 318S .fail (f"a model repack is still running here (pid { busy [ 0 ] } ): the engine is not started beside it" , 319"wait for it to finish (or stop it), then start again" ) 320cfg_path .touch () 321if "--mtp" in cfg ["args" ][:- 1 ]: 322S .refresh_draft_vocab (Path (cfg ["args" ][cfg ["args" ].index ("--mtp" )+ 1 ]),cfg .get ("draft_vocab" ,"cjk" )) 323cmd = [sys .executable ,str (ROOT / "serve" / "server.py" ),"--engine" ,"strata" ,"--config" ,str (cfg_path ), 324"--port" ,str (port or cfg .get ("port" ,8080 ))] 325if open_browser and cfg .get ("open_browser" )is not False : 326cmd .append ("--open" ) 327S .say () 328S .say (f" Starting { cfg . get ( 'model_name' , 'the model' ) } on Metal: the engine maps the model file and is ready in about " 329"half a minute (longer the first time after a restart, while macOS reads the file)." ) 330S .say (" Closing this window stops the model." ) 331return subprocess .call (cmd ) 332 333 334# ------------------------------------------------------------------------------------------------ the DFlash2 drafter 335def fetch_drafter (model_name :str ,data :Path )-> Path | None : 336"""The DFlash2 drafter of a set whose Mac default is DFlash2 (strata_control/drafting.py SET_DEFAULTS: UD-Q4_K_XL and UD-IQ4_XS-v31): the tuned one (0.34 GB), else the stock one 337(1.2 GB), through the normal download path (resumable, the pinned size and SHA-256). Offline, or an address that does not answer: nothing is said and the model keeps the MTP 338(owner, strata-offline-users). A fault that is the person's to know (a file that failed its safety check) is one plain line. Never stops the setup. None when it is not here.""" 339from strata_control import acquisition ,drafting ,drafting_fetch 340if drafting .choice_of ("auto" ,model_name = model_name ,backend = "metal" )!= "dflash2" : 341return None 342said = [] 343 344def show (step :str ,done :int ,total :int )-> None : 345if not said :# the line appears when the download starts: a computer with no internet sees nothing 346said .append (True ) 347gb = drafting .TUNED_GB if "tuned" in step else drafting .DOWNLOAD_GB 348S .say (f" Downloading the DFlash2 drafter ( { gb :g } GB, once) ..." ) 349try : 350got = drafting_fetch .ensure_for (data ,model_name = model_name ,backend = "metal" ,progress = show ) 351except (drafting_fetch .DraftingError ,acquisition .AcquisitionRefused ,OSError )as exc : 352S .warn (f" { exc } This model keeps using the MTP." ) 353return None 354if got is not None : 355S .ok (f"DFlash2 drafter: { got } " ) 356return got 357 358 359# ------------------------------------------------------------------------------------------------ main 360def _feed_models (argv ,interactive :bool )-> None : 361"""The signed feed's models (setup.py feed_models_setup: the feed, else the last verified list) join MAC_MODELS / FAMILIES / MODELS. Read when a name the built-in 362tables do not know is given, or when the size menu is going to be shown; nothing happens when the feed has no models.""" 363args = list (argv or sys .argv [1 :]) 364peek = lambda flag :next ((v .split ("=" ,1 )[1 ]if v .startswith (flag + "=" )else args [i + 1 ]if i + 1 < len (args )else None # noqa: E731 365for i ,v in enumerate (args )if v == flag or v .startswith (flag + "=" )),None ) 366family ,model = peek ("--family" ),peek ("--model" ) 367if (family and family not in ("qwen" ,"unsloth" ,"gyro" ))or (model and model not in MAC_MODELS )or interactive : 368S .feed_models_setup (peek ("--feed" )) 369 370 371def main (argv = None )-> int : 372given = argv if argv is not None else sys .argv [1 :] 373_feed_models (argv ,not any (x in given for x in ("--yes" ,"--model" ,"--check" ,"--family" ))and ("--setup" in given or not mac_configs ()))# (a plain start of an installed model reads nothing) 374ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ]) 375ap .add_argument ("--family" ,choices = ["qwen" ,"unsloth" ,"gyro" ,* _fit .FEED_FAMILIES ],default = None , 376help = "qwen = Qwen3.8-Flash-Next (GSQ-RCO), unsloth = Unsloth's UD-*_K_XL, gyro = agentionai's Gyro-S / Gyro-M " 377"(follows --model)" ) 378ap .add_argument ("--model" ,choices = list (MAC_MODELS )) 379ap .add_argument ("--context" ,type = int ) 380ap .add_argument ("--port" ,type = int ) 381ap .add_argument ("--host" ) 382ap .add_argument ("--api-key" ) 383ap .add_argument ("--draft-vocab" ,choices = list (S .DRAFT_VOCABS )) 384ap .add_argument ("--no-browser" ,dest = "browser" ,action = "store_false" ,default = None ) 385ap .add_argument ("--data-dir" ) 386ap .add_argument ("--move-data" ,action = "store_true" ,help = "with --data-dir: move the model files already here into the new folder" ) 387ap .add_argument ("--set-default-data-dir" ,action = "store_true" ,help = "with --data-dir: remember the new folder without moving anything" ) 388ap .add_argument ("--models-dir" ) 389ap .add_argument ("--gguf-dir" ) 390ap .add_argument ("--yes" ,action = "store_true" ) 391ap .add_argument ("--source" ,choices = S .SOURCES ,default = None , 392help = "where model files come from: auto (huggingface), huggingface, modelscope; " 393"same as STRATA_SOURCE" ) 394ap .add_argument ("--setup" ,action = "store_true" ) 395ap .add_argument ("--no-start" ,action = "store_true" ) 396ap .add_argument ("--check" ,action = "store_true" ) 397ap .add_argument ("--update" ,action = "store_true" ) 398ap .add_argument ("--build" ,action = "store_true" ,help = "build the engine again even when it is current" ) 399ap .add_argument ("--vision" ,choices = ["yes" ,"no" ,"gpu" ,"cpu" ], 400help = "let the model read images (the image encoder, built here; yes = gpu: it reads on the Mac's GPU, cpu is ~100x " 401"slower; default: asked, yes)" ) 402a ,rest = ap .parse_known_args (argv ) 403if rest : 404S .warn ("not used on a Mac: " + " " .join (rest )) 405# setup.py hands a Mac over before its own parser runs, so --source has to be honoured here too: 406# source_hint() recommends it on every platform, and a Mac that dropped it failed the download 407# with the same unreachable host (#2363). 408if a .source : 409os .environ ["STRATA_SOURCE" ]= a .source 410S .say ("Strata on a Mac (Apple Silicon, Metal)" ) 411data ,elsewhere = S .data_folder_for (a ) 412roots = [data ,* elsewhere ] 413models_root = Path (a .models_dir )if a .models_dir else data / "models" 414 415have = mac_configs () 416if have and not (a .setup or a .model or a .check or a .no_start or a .update or a .build ): 417return start (have [0 ],a .port ,a .browser is not False ) 418 419# ---- 1. the Mac 420S .step (1 ,"checking your Mac" ) 421info = mac_info () 422S .ok (f" { info [ 'chip' ] } , { info [ 'ram_gb' ]:.0f } GB unified memory, macOS { info [ 'macos' ] or '?' } " ) 423problems = mac_problems (info ) 424for p in problems : 425S .warn (p ) 426free = S .free_gb (data if data .exists ()else ROOT ) 427S .ok (f"free disk: { free :.0f } GB at { data } " ) 428if a .check : 429return 1 if problems else 0 430if problems : 431S .fail (problems [0 ]) 432 433# ---- 2. the choices 434S .step (2 ,"your choices" ) 435rec ,notes = recommend_model (info ["ram_gb" ]) 436for n in notes : 437S .warn (n ) 438if a .model : 439model = a .model 440else : 441names = [m for m in MAC_MODELS if not MAC_MODELS [m ].get ("missing" )]# --model offers the others 442for i ,m in enumerate (names ,1 ): 443S .say (f" { i } ) { m :8 } { MAC_ABOUT [ m ] } (maps { MAC_MODELS [ m ][ 'shard1_gb' ]:.0f } GB" 444+ ("" if MAC_MODELS [m ]["tested" ]else ", not measured on a Mac" )+ ")" 445+ (" (recommended)" if m in RECOMMENDED else "" )+ (" <- default" if m == rec else "" )) 446model = names [int (S .ask ("Which size?" , [str (i )for i in range (1 ,len (names )+ 1 )], 447str (names .index (rec )+ 1 ),a .yes ))- 1 ] 448for n in model_note (model ,info ["ram_gb" ]): 449S .warn (n ) 450vision = a .vision or ("yes" if S .ask ("Should the model also read images? (the image encoder, ~1 GB more)" , 451 ["y" ,"n" ],"y" ,a .yes )== "y" else "no" )# on by default (strata_control/vision_reader.py) 452if vision == "cpu" : 453from strata_control import vision_reader as VR 454S .warn (VR .MAC_CPU_NOTE ) 455vision_gpu = vision != "cpu" 456vision = "no" if vision == "no" else "yes" 457ctx = a .context or recommend_context (info ["ram_gb" ]) 458if ctx > TESTED_CONTEXT : 459S .say (f" context { ctx } : measured on the Mac up to { TESTED_CONTEXT } (needles found at 8K-32K); longer is kept" ) 460S .ok (f" { model } , context { ctx } " ) 461family = MAC_MODELS [model ].get ("family" ,"qwen" ) 462if a .family and a .family != family : 463S .warn (f"--family { a . family } : { model } is a { family } file; using { family } " ) 464fam = S .FAMILIES [family ] 465tag = fam ["tag" ]+ model 466need = (0 if a .gguf_dir else S .MODELS [model ]["download_gb" ])+ 6 # --gguf-dir: the files are there already 467if free < need : 468S .warn (f"about { need :.0f } GB are needed on the disk ( { free :.0f } GB free): kept as you chose; it may run out" ) 469 470# ---- 3. Python packages (cmake and ninja come with the build in step 4, from requirements-build.txt) 471S .step (3 ,"Python packages" ) 472S .pip_install (S .requirement_lines ()if S .REQUIREMENTS .exists ()else S .PY_PACKAGES ,"numpy, jinja2, ..." ) 473 474# ---- 4. the engine 475S .step (4 ,"the Strata engine (Metal)" ) 476llama = S .llama_override ()# None: ggml is the vendored third_party/strata-ggml (STRATA_GGML_DIR overrides) 477S .ok (f"llama.cpp { S . LLAMA_CPP_COMMIT [: 7 ] } (ggml, gguf-py)" ) 478if a .build : 479 (BUILD_DIR / "BUILD.json" ).unlink (missing_ok = True ) 480exe = build_engine (llama ) 481if a .update : 482# update.sh's own text: "The model files are not touched". The questions are asked anyway, so when the 483# answers name a model (or an image encoder) that is not here, say it: a silent exit reads like a broken 484# download (an M1 Max chose IQ3_S in update.sh and got no model and no message). 485files = [Path (a .gguf_dir )/ n if a .gguf_dir else models_root / tag / n for n in model_shard_names (model )] 486pack = S .find_in (roots ,f"packs/ { tag . lower () } " )or data / "packs" / tag .lower () 487pack_done = (pack / "native_experts.txt" ).exists ()and (pack / "tokenizer" / "vocab.json" ).exists () 488if not (all (f .exists ()and S .done (f )for f in files )and pack_done ): 489S .warn (f" { model } is not installed here, and an update does not download model files: nothing was installed" ) 490S .say (f" to download and prepare { model } : ./setup.sh --setup" ) 491elif vision == "yes" and not (models_root / fam ["mmproj" ]).exists (): 492S .warn ("the image encoder is not downloaded here, and an update does not download model files" ) 493S .say (" to add image support: ./setup.sh --setup" ) 494return 0 495 496# ---- 5. the model 497S .step (5 ,f"downloading { fam [ 'title' ] } { model } " ) 498models_dir = Path (a .gguf_dir )if a .gguf_dir else models_root / tag 499models_dir .mkdir (parents = True ,exist_ok = True ) 500files = [models_dir / n for n in model_shard_names (model )] 501for s in files : 502if s .exists ()and S .done (s ): 503S .ok (f" { s . name } already downloaded" ) 504continue 505S .download (S .model_hf (fam ,model )+ s .name ,s ) 506S .check_shards (files ) 507for s in files :# the Unsloth files: pinned sizes and SHA-256 508if (family == "unsloth" or fam .get ("feed" ))and s .name in fam .get ("sha256" , {}):# the family's pins, and UD-Q4_K_XL's second layout by the size on the disk 509S .verify_sha256 (s ,* S .fam_pin (fam ,s ),own = bool (a .gguf_dir )) 510elif shard_sha (s .name ): 511S .verify_sha256 (s ,* shard_sha (s .name )) 512S .ok ("model files present" ) 513 514mmproj = vexe = None 515if vision == "yes" : 516mmproj = models_root / fam ["mmproj" ] 517if not (mmproj .exists ()and S .done (mmproj )): 518S .download (fam ["mmproj_hf" ]+ fam ["mmproj" ],mmproj ,"vision encoder" ) 519sha = VISION_SHA256 .get (fam ["mmproj" ]) 520if sha : 521S .verify_sha256 (mmproj ,* sha ) 522vexe = build_vision (llama ) 523 524# ---- 6. the pack and the MTP draft layer 525S .step (6 ,"preparing the model for Strata" ) 526pack = S .find_in (roots ,f"packs/ { tag . lower () } " )or data / "packs" / tag .lower () 527env = dict (os .environ ,** S .gguf_py_env ()) 528# The repack and the pack move 100+ GB through the disk and the pack's python holds up to 20 GB: no engine may run beside 529# them (an engine of 70-90 GB with a repack froze the 128 GB M5 Max twice). A lock beside the GPU's file tells the engine 530# and start() to wait; a running engine stops setup here. 531lock_dir = data / "metal" if len (files )> 2 else files [0 ].parent 532native0 = data / "metal" / f" { tag . lower () } -metal.gguf" 533work = (len (files )> 2 and not (native0 .exists ()and S .done (native0 )))or \ 534not ((pack / "native_experts.txt" ).exists ()and (pack / "tokenizer" / "vocab.json" ).exists ()) 535prep_lock = lock_dir / PREPARE_LOCK 536if work : 537running = engine_pids () 538if running : 539S .fail (f"a Strata engine is running (pid { running [ 0 ] } ): preparing a model beside it can freeze this Mac" , 540"stop the server (close its window), then run ./setup.sh --setup again" ) 541lock_dir .mkdir (parents = True ,exist_ok = True ) 542prep_lock .write_text (str (os .getpid ())) 543atexit .register (lambda :prep_lock .unlink ()if prep_lock .exists ()else None ) 544if len (files )> 2 : 545# many shards: the experts and dense tensors into one GGUF the GPU maps (or streams), the n-gram table read 546# from its own shard (every tensor checked byte for byte: --verify) 547native = data / "metal" / f" { tag . lower () } -metal.gguf" 548native .parent .mkdir (parents = True ,exist_ok = True ) 549if not (native .exists ()and S .done (native )): 550S .say (f" Writing the model's experts and weights into one file for the GPU (one time, " 551f" { MAC_MODELS [ model ][ 'shard1_gb' ]:.0f } GB) ..." ) 552S .run ([sys .executable ,str (ROOT / "metal" / "tools" / "metal_repack.py" ),"--shard1" ,str (files [0 ]), 553"--out" ,str (native ),"--verify" ]) 554S .mark (native ) 555ple = ple_shard (files ) 556shards = [native ,ple ] 557elif family == "gyro" : 558shards = [files [0 ],files [0 ]]# one file: the model and its n-gram table (--native, --ple-gguf) 559else : 560shards = files 561if not (pack / "native_experts.txt" ).exists ()or not (pack / "tokenizer" / "vocab.json" ).exists (): 562S .run ([sys .executable ,str (ROOT / "tools" / "iq_pack.py" ),"--gguf" ,str (shards [0 ]),"--out" ,str (pack ), 563* fam .get ("pack_args" , [])],env = env )# Unsloth: --compat-bf16 (the host's copies; the GPU reads the file) 564S .ok (f"model prepared: { pack } " ) 565prep_lock .unlink (missing_ok = True ) 566mtp = (S .find_in (roots ,"mtp/mtp-q2_0.gguf" )or data / "mtp" / "mtp-q2_0.gguf" ).parent 567rt = mtp / "rt" 568stream = streams (model ,info ["ram_gb" ]) 569use_mtp = stream_mtp (stream ,info ["ram_gb" ]) 570if stream and not use_mtp : 571S .ok ("the experts will stream from the SSD: no MTP draft layer (one token per step is faster there); " 572"./setup.sh --setup on a Mac with more memory adds it" ) 573elif stream : 574S .ok (f"the experts will stream from the SSD; the MTP draft layer stays on, with --spec { STREAM_SPEC } " 575"(a longer window pays when every window has a fixed cost per layer)" ) 576if stream and info ["ram_gb" ]< STREAM_MTP_FROM_GB : 577experts_file (shards [0 ])# a small Mac: its misses are many; a big Mac's arena holds most experts 578if use_mtp and not (mtp / "mtp-q2_0.gguf" ).exists (): 579S .say (" The MTP draft layer (speculative decoding) comes from the original Qwen checkpoint: only its ~5 GB of" ) 580S .say (" MTP tensors are downloaded." ) 581S .run ([sys .executable ,str (ROOT / "tools" / "mtp_fetch.py" ),"fetch" ,"--out" ,str (mtp )], 582env = {** env ,"STRATA_SOURCE" :S .model_source ()}) 583S .run ([sys .executable ,str (ROOT / "tools" / "mtp_pack.py" ),"--src" ,str (mtp ),"--experts" ,"q2_0" , 584"--out" ,str (mtp / "mtp-q2_0.gguf" )],env = env ) 585if use_mtp : 586rt .mkdir (parents = True ,exist_ok = True )# the Metal engine reads mtp-q2_0.gguf beside it (no rt pack) 587S .refresh_draft_vocab (rt ,a .draft_vocab or "cjk" ) 588S .ok (f"MTP draft layer: { mtp / 'mtp-q2_0.gguf' } " ) 589 590fetch_drafter (f" { fam [ 'name' ] } - { model . lower () } " ,pack .parent .parent )# DFlash2 is this set's default drafter (the MTP above stays as the fallback); the folder a start looks in 591 592# ---- 7. the config, the start script 593S .step (7 ,"writing the start script" ) 594port = a .port or 8080 595cfg = mac_config (exe ,engine_args (pack ,shards ,rt ,ctx ,stream ,info ["ram_gb" ],model ),pack ,f" { fam [ 'name' ] } - { model . lower () } " ,tag ,port ) 596cfg ["env" ]= {"STRATA_METAL_STREAM" :"1" if stream else "0" }# the engine follows setup's measured choice (STRATA_METAL_F16 is the engine's own default) 597if vision == "yes" : 598cfg ["args" ]+= ["--vision" ] 599cfg ["vision" ]= {"exe" :str (vexe ),"mmproj" :str (mmproj ),"model" :str (files [0 ]),"gpu" :vision_gpu , 600"max_tokens" :1024 } 601if a .host : 602cfg ["host" ]= a .host 603if a .api_key : 604cfg ["api_key" ]= a .api_key 605if a .draft_vocab : 606cfg ["draft_vocab" ]= a .draft_vocab 607if a .browser is not None : 608cfg ["open_browser" ]= a .browser 609cfg_path = ROOT / f"strata- { tag . lower () } .json" 610S .write_config (cfg_path ,cfg ) 611script = S .write_run_script (tag ,cfg_path ,port ,cfg .get ("open_browser" )is not False ) 612S .ok (f"start script: { script . name } " ) 613S .say () 614S .say ("All set." ) 615S .say (f" API (OpenAI): http://127.0.0.1: { port } /v1" ) 616S .say (f" API (Anthropic): http://127.0.0.1: { port } /v1/messages" ) 617S .say (f" Next time: just run ./setup.sh (or { script . name } ) - it starts right away" ) 618if a .no_start : 619return 0 620return start (cfg_path ,port ,a .browser is not False ) 621 622 623if __name__ == "__main__" : 624try : 625sys .exit (main ()) 626except KeyboardInterrupt : 627S .say ("\nstopped." ) 628sys .exit (1 )