okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
361c8d94a
main
1#!/usr/bin/env python3 2"""Strata one-click setup and start (Windows and Linux, NVIDIA or AMD GPUs). 3 4START-HERE.bat (Windows) / ./setup.sh (Linux) - they install Python if needed and run this file 5 6The first time it asks four questions - which model (the original Qwen3.8-Flash-Next or the Swift 1.5 fine-tune), 7which size, how much context, and whether the model should also read images - then installs everything and starts the model on http://127.0.0.1:8080 (OpenAI- and Anthropic-compatible 8API; a small page there shows that it runs). Every later start skips straight to running the model: nothing that 9is already downloaded, installed or prepared is done again. 10 11What the first run does (each step is skipped when it is already done): 12 131. checks your PC: NVIDIA or AMD GPU and driver, RAM, CPU, free disk space 142. asks the questions 153. installs the Python packages it needs into .venv (numpy, jinja2, ..., and NVIDIA's CUDA libraries) 164. gets the Strata engine: a ready-made build for RTX 20/30/40/50 cards (no compiler needed); if none fits your PC, 17it installs the missing build tools (asks first) and compiles the engine for your GPU. AMD (--backend hip, chosen by 18itself on a PC with no usable NVIDIA card): the ready-made HIP engine on Windows, compiled here on Linux 195. downloads the model from Hugging Face (resumable), and the vision encoder if you want images 206. prepares the model for Strata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint) 217. writes run-<model>.bat / run-<model>.sh and starts the model 22 23Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --rope-scaling none|linear|yarn 24(--rope-scale F; past the trained 262144 the setup adds yarn and the factor is the final context over 262144, 25at least 1 - an explicit --rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port 268080, --yes (recommended 27answers, no questions), --setup (install another model / change settings instead of starting), --no-start, 28--host 0.0.0.0 --api-key KEY (reach it over IPv4; use --host :: for IPv6), --experimental-speed-projection on|off 29(EXPERIMENTAL, off by default), 30--models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made 31engine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's or UD-IQ4_XS's experts in RAM), 32--kv-streaming on|off|auto. 33 34Setup recommends, it never forces: the recommended answers are the defaults (--yes, or Enter), and a bigger choice 35than it recommends - a longer context, more GPUs, a bigger RAM budget, a size it thinks will not fit - is kept, with 36what it risks. With --yes, an explicit flag (--model, --gpus, ...) is the consent to a risk setup would otherwise 37stop at; --yes alone is not. 38""" 39from __future__import annotations 40 41import argparse 42import calendar 43import ctypes 44import glob 45import hashlib 46import http .client 47import json 48import math 49import os 50import platform 51import re 52import shutil 53import struct 54import subprocess 55import sys 56import textwrap 57import threading 58import time 59import urllib .error 60import urllib .parse 61import urllib .request 62import zipfile 63from pathlib import Path 64 65from strata_control import acquisition 66from strata_control import tls 67from strata_control import netpolicy 68 69tls .install ()# #3722: HTTPS checks the server against the operating system's certificates (what Chrome and curl.exe do) 70from strata_control import atomic 71from strata_control import draft_layer 72from strata_control import engine_component 73from strata_control import sysinfo 74from strata_control .discovery import in_trash 75from strata_control import user_args 76 77ROOT = Path (__file__ ).resolve ().parent 78# The desktop app runs this installer under Strata Control (its bundled Python, STRATA_CONTROL_INSTALL=1). The source 79# (tools/, data/, serve/) stays in ROOT, inside the app; everything the install writes (run configs, logs, third_party, 80# the data folder beside it) goes to home(), a per-user folder (STRATA_INSTALL_DIR). In that mode it installs no Python 81# package and no engine and compiles nothing: it downloads the model files, prepares them with the bundled tools and 82# writes a run config whose engine is "component:strata-engine". Outside that mode home() is ROOT and nothing changes. 83CONTROL = os .environ .get ("STRATA_CONTROL_INSTALL" )== "1" 84_CONTROL_HOME = Path (os .environ ["STRATA_INSTALL_DIR" ]).resolve ()if CONTROL and os .environ .get ("STRATA_INSTALL_DIR" )else None 85 86 87def home ()-> Path : 88"""Where an install writes (see above). A function, not a constant, so ROOT stays the one thing a caller can point elsewhere.""" 89return _CONTROL_HOME or ROOT 90 91 92WIN = os .name == "nt" 93# #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of 94# https://huggingface.co/api/models/<repo> when this was pinned), so a checkout installs the same files on any 95# day. Every file has a fixed size and SHA-256 too (REPO_PINS); a revision the repository no longer has stops the 96# download (download()), unless a tester sets STRATA_ALLOW_UNPINNED=1. 97HF_REVISIONS = { 98"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" :"ed59f92082b1e93c0e96d60a8b11aab089b52f09" ,# 2026-09-29 99"ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" :"99bb8f7f95c7aa7b24a36a7786a4f657b30f5d3d" ,# 2026-10-07 (adds IQ3_S) 100"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF" :"5348543e0147355ac9cbcb031184a3546350988e" ,# 2026-09-29 101"unsloth/Qwen3.8-Flash-Next-GGUF" :"38bb39ee97821de2c9009abb7e93950eec396e66" ,# 2026-09-30 102"unsloth/Qwen3.6-35B-A3B-MTP-GGUF" :"5bc3e238d916f48a861bac2f8a1990a0e9b7e98d" ,# 2026-10-12 103"agentionai/Qwen3.8-Flash-Next-Gyro-GGUF" :"1ada08422e404aca51ab9df665f089f34c419c6b" ,# 2026-10-13 104} 105 106 107HF_DEFAULT = "https://huggingface.co" 108 109 110def hf_endpoint ()-> str : 111"""#495: the Hugging Face host - HF_ENDPOINT as huggingface_hub reads it (a mirror, e.g. https://hf-mirror.com), 112else huggingface.co. The pinned revisions and the SHA-256 checks are the same whichever host serves the files.""" 113return (os .environ .get ("HF_ENDPOINT" )or "" ).strip ().rstrip ("/" )or HF_DEFAULT 114 115 116def hf (repo :str )-> str : 117"""The download folder of a Hugging Face repository at its pinned revision.""" 118return f" { hf_endpoint () } / { repo } /resolve/ { HF_REVISIONS [ repo ] } /" 119 120 121def hf_unpinned (url :str )-> str : 122"""The same file at the repository's current revision (main).""" 123return re .sub (r"^(https?://[^/]+/.+?/resolve/)[0-9a-f]{40}/" ,r"\1main/" ,url ,count = 1 ) 124 125 126_unpinned_said = [] 127 128 129def allow_unpinned ()-> bool : 130"""STRATA_ALLOW_UNPINNED=1: a tester's opt-out. A file whose pinned version is gone from Hugging Face is then taken 131from the repository's current files, without the SHA-256 check (nothing pins them). Off by default, announced when set.""" 132on = (os .environ .get ("STRATA_ALLOW_UNPINNED" )or "" ).strip ()== "1" 133if on and not _unpinned_said : 134_unpinned_said .append (1 ) 135warn ("STRATA_ALLOW_UNPINNED=1: a model file whose pinned version is gone from Hugging Face is taken from its " 136"current files instead, and is NOT checked against a SHA-256. Unset it to get the checked files only" ) 137return on 138 139 140def file_pin (url :str ): 141"""(bytes, sha256) pinned for the Hugging Face file `url` names (REPO_PINS), else None.""" 142m = HF_FILE .match (url ) 143if m is None : 144return None 145name = m .group ("path" ).rsplit ("/" ,1 )[- 1 ] 146by_commit = REV_PINS .get ((m .group ("repo" ),m .group ("rev" )), {})# a repository with files at more than one commit (UNSLOTH_V31_REVISION) 147return by_commit [name ]if name in by_commit else REPO_PINS .get (m .group ("repo" ), {}).get (name ) 148 149 150# ModelScope (www.modelscope.cn) hosts every repository above under the same name, with the same file paths and 151# sizes, and is reachable from mainland China where huggingface.co often is not. It serves a repository's current 152# files (no pinned revision), so a file from it is checked against the SHA-256 ModelScope publishes for it, and the 153# MTP tensors against the pinned checkpoint's own hashes (tools/mtp_fetch.py). 154# --source / STRATA_SOURCE: huggingface (what auto means), or modelscope: only when asked for (a different host 155# serving current files, not our pinned revision: setup never switches to it by itself, it recommends it, #908). 156MS_DEFAULT = "https://www.modelscope.cn" 157SOURCES = ("auto" ,"modelscope" ,"huggingface" ) 158HF_FILE = re .compile (r"^https?://[^/]+/(?P<repo>[^/]+/[^/]+)/resolve/(?P<rev>[^/]+)/(?P<path>.+)$" ) 159_sources = {}# model_source()'s answer per (STRATA_SOURCE, HF_ENDPOINT, host) 160_ms_files = {} 161 162 163def ms_endpoint ()-> str : 164return (os .environ .get ("MODELSCOPE_ENDPOINT" )or "" ).strip ().rstrip ("/" )or MS_DEFAULT 165 166 167def reachable (url :str ,timeout :float = 5.0 )-> bool : 168"""Whether `url` answers a HEAD request with success (2xx, after redirects) within `timeout` seconds.""" 169try : 170_urlopen (urllib .request .Request (url ,method = "HEAD" ,headers = {"User-Agent" :"strata-setup" }), 171timeout = timeout ).close () 172return True 173except OSError :# HTTPError too: an error page is not the file 174return False 175 176 177def model_source ()-> str : 178""""modelscope" or "huggingface". ModelScope only when --source modelscope / STRATA_SOURCE=modelscope asks for it; 179everything else (auto, a HF_ENDPOINT mirror chosen on purpose, #495) is Hugging Face. Setup does not switch hosts 180by itself (#908): ModelScope serves a repository's current files, not our pinned revision.""" 181want = (os .environ .get ("STRATA_SOURCE" )or "auto" ).strip ().lower () 182key = (want ,os .environ .get ("HF_ENDPOINT" )or "" ,ms_endpoint ()) 183if key not in _sources : 184_sources [key ]= "modelscope" if want in ("ms" ,"modelscope" )else "huggingface" 185return _sources [key ] 186 187 188def source_hint (url :str )-> str : 189"""The recommendation that goes with a failed download from Hugging Face: ModelScope, by an explicit choice.""" 190if "huggingface" in url or "hf-mirror" in url : 191return ("; if huggingface.co does not reach you (mainland China), the same files are on ModelScope: run setup " 192"with --source modelscope (docs/INSTALL.md)" ) 193return "" 194 195 196def model_alias (name :str )-> str : 197"""A --model name as setup keeps it (the DeepSeek sets' second spellings were the only aliases; DeepSeek is no longer offered).""" 198return name 199 200 201def proxy_hint ()-> str : 202"""The next step when a download cannot reach its server: behind a proxy, the variables below are what Strata (and pip, git) read.""" 203names = ("HTTPS_PROXY" ,"https_proxy" ,"ALL_PROXY" ,"all_proxy" ) 204if any (os .environ .get (n )for n in names ): 205return "; a proxy is set in this terminal (HTTPS_PROXY): check that it is the right one and that it is running" 206return "; behind a company or school proxy, set HTTPS_PROXY (for example HTTPS_PROXY=http://host:port) in this terminal first" 207 208 209def ms_file (url :str ): 210"""(repo, path) when `url` is a Hugging Face file of a repository setup knows (HF_REVISIONS), else None.""" 211m = HF_FILE .match (url ) 212if m is None or m .group ("repo" )not in HF_REVISIONS : 213return None 214return m .group ("repo" ),m .group ("path" ) 215 216 217def ms_url (repo :str ,path :str )-> str : 218return f" { ms_endpoint () } /models/ { repo } /resolve/master/ { path } " 219 220 221def ms_meta (repo :str ,path :str ): 222"""(size, sha256) ModelScope publishes for a file, or None when it cannot be asked.""" 223if repo not in _ms_files : 224try : 225api = f" { ms_endpoint () } /api/v1/models/ { repo } /repo/files?Recursive=true" 226with _urlopen (urllib .request .Request (api ,headers = {"User-Agent" :"strata-setup" }), 227timeout = 60 )as r : 228files = json .loads (r .read ())["Data" ]["Files" ] 229_ms_files [repo ]= {f ["Path" ]: (int (f .get ("Size" )or 0 ), (f .get ("Sha256" )or "" ).lower ())for f in files } 230except (OSError ,ValueError ,KeyError ,TypeError ): 231return None 232return _ms_files [repo ].get (path ) 233 234 235HF = hf ("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ) 236LLAMA_CPP_COMMIT = "3cf03257f219afbe7334045ff7c6a06ac68c627d" 237 238# The ready-made engine: <PREBUILT_URL><asset>, a zip with strata(.exe), strata-vision(.exe) and BUILD.json, built 239# by tools/make_release.py. Set this to the GitHub release download folder when publishing, e.g. 240# "https://github.com/<you>/Strata/releases/latest/download/" (or pass --prebuilt / set STRATA_PREBUILT_URL). 241# With the default, the release of this checkout's own version (PREBUILT_TAG_URL, CMakeLists.txt's version) is 242# tried first and the latest release is the fallback (#214): an older checkout keeps the engine it shipped with. 243PREBUILT_URL = "https://github.com/Niko1221/Strata/releases/latest/download/" 244# The repository the release assets and their SHA-256 come from; `engine_digest` reads the API here even 245# when --prebuilt points the download somewhere else, because the hash is only worth having if it comes 246# from somewhere the download does not. 247REPO = "Niko1221/Strata" 248PREBUILT_TAG_URL = "https://github.com/Niko1221/Strata/releases/download/v{version}/" 249PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" 250# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages 251CUDA_WHEELS = ["nvidia-cublas==13.0.2.14" ,"nvidia-cuda-runtime==13.0.96" ] 252MIN_DRIVER = 580 # CUDA 13.0 253# Older NVIDIA GPUs (experimental): CUDA 13 dropped Pascal (sm_60/61) and Volta (sm_70), so a model whose GPUs include 254# one runs a second engine, built with CUDA 12.9 (-DSTRATA_EXPERIMENTAL_SM60=ON) and kept in its own folder: the 255# ready-made one is CUDA12_ASSET (Windows; on Linux it is compiled here with a CUDA 12.x toolkit). One engine runs per 256# model, so the choice is per model config, by its oldest GPU; --cuda 12|13 overrides it (docs/OLDER_GPUS.md). 257CUDA13_MIN_ARCH = 75 # the oldest compute capability CUDA 13 compiles for (sm_75, RTX 20) 258CUDA12_ASSET = "strata-windows-x64-cuda12.zip" if WIN else "strata-linux-x64-cuda12.zip" 259CUDA12_WHEELS = ["nvidia-cublas-cu12==12.9.1.4" ,"nvidia-cuda-runtime-cu12==12.9.79" ] 260# The wheels match the 12.9.1 toolkit the CUDA 12 engine is built with (cuBLAS 12.9.1.4, runtime 12.9.79). 261# CUDA12_COMPAT_DRIVER is NVIDIA's minor-version-compatibility line (Linux 525.60.13, Windows 527.41): under it no CUDA 12 program starts, so 262# setup stops there. It is NOT what setup promises: the ready-made packages are built with CUDA 12.9 and carry their own `min_driver` 263# (575.51 / 576.02), which `strata update` enforces. cuda12_min_driver() reads that from the package or the feed (#4247 #4188). 264CUDA12_COMPAT_DRIVER = 528 if WIN else 525 265ENGINE12_DIR = "engine-cuda12" 266MIN_ENGINE = (0 ,1 ,46 )# versions compare all numbers; v0.1.60: engine changes since v0.2.13.1 (git log 628f74955..HEAD); v0.1.59: engine changes since v0.2.12 (git log 146df3c46..HEAD); v0.1.58: engine rounds 0215-0217 (tuned drafters, the file-tier re-check, prefill and Q5_0 fixes; git log c3b3f5035..HEAD); v0.1.46: the 0.2 release engine (UPDATE.bat and setup fetch it from the signed feed, #3469 #3437); v0.1.45: Qwen3.6 parallel requests and pictures, fixes #2346 #2372 #2396; v0.1.44.1: CPUs without AVX2 start again (#2324: an illegal instruction before main in the NVFP4 CPU rows), the CUDA 12.0/12.1 toolkits build (#2322), a crashed engine start is named instead of retried as a GPU runtime start, Mac M2 (#2323); v0.1.44: UD-Q4/Q5/Q6_K_XL and Q8_0 Unsloth files in setup (K-quant experts, MMQ prompt library strata_kq), NVFP4 packs, Qwen3.6-35B-A3B, Intel Arc A-series kernels, the pipelined-decode and latency work; v0.1.43.1: the adaptive overlap no longer collapses decode on pinned-host desktops (#1964 #1975), Windows PLE mmap stall (#1984), pinned prompt uploads (#1996), the I/O watchdog allowance; v0.1.43: adaptive-tier copies overlap on CUDA, P100 (sm_60) kernel tables, RDNA4 (gfx1200/gfx1201) defaults (route tail skip, measured PCIe share, 16K prompt chunks, fused IQ3 prompt experts); v0.1.42.1: the GGUF-in-place file tier on Windows unmaps every shard, dual-socket starts judge each NUMA node and STRATA_DROP_CACHE_ON_EXIT, tools/strata_bench.py; v0.1.42: STRATA_ROUTE_TAIL_SKIP=7 default on CUDA (+13-16% decode), the AMD 2-GPU checkpoint fix (H13), Phase 2 fixes and opt-ins; v0.1.41.1 (folded into 0.1.42): the #1576 card order, #1616 stage size, #1595 CPU share, #1630/#1607 Windows HIP chunk cap and commit-limit warning, #1603 parallel-request bookkeeping; v0.1.41: CPU prefill share on by default (NVIDIA, chunks < 1024), --batch-groups auto, the file tier read in batches on Windows, Pascal decode fix, per-arch tables; v0.1.40.3: the #1357 MTP router guard, the #1376 Windows HIP cache floor, #461 runtime DLLs, Intel A750 first-request fix; v0.1.40.2: F4 verify windows, the Linux file tier (#1194), the stager wait (#1057), #1264/#1201/#1139 fixes, opt-in CPU share (#1282), Intel Arc; v0.1.40: --resident-experts on a layer split with the split+resident variant (#848), --kv k8v4 with KV streaming (#711); v0.1.39: the #577 file-tier regression fixed, the OpenAI Responses API (#451, Codex), a reply stuck on one token ended (#606), the head before the arena (#620), effort_position (#458), --vram-reserve hot resize opt-in (#533), PR batch; v0.1.38: prompts faster (one gather per expert group #372, the first chunk's PLE rows beside layer 0 #374, DeltaNet three heads per thread #413), --kv q4_0 prompts on tensor cores (#452), Q5_0 experts on the GPU (#473), IQ4_XS on AVX-2 (#415), unbuffered expert loading on Windows (#357 #362), --peer-device (#531), a 6 GB card starts (#496), PR batch; v0.1.37: a silent engine is restarted (#481), Windows AMD counts the desktop's VRAM (#380 #377 #497), a steadier PCIe probe (#485), fixes #496 #495 #498 #505 #493; v0.1.36: a cancelled prompt logged as read so far (#471), the draft-head hint (#474), UPDATE.bat (#475), --expert-profile-save (#477); v0.1.35: Windows AMD uses its bundled HIP runtime (#468 #461), the low-RAM resident mode on Windows 32 GB (#467), fixes #460 #459 #446 #447 #457 #448 #444; v0.1.34: AMD on Windows (a ready-made HIP engine), an MCP server for AI assistants (tools/strata_mcp.py), a shorter README; v0.1.33: a portable image encoder again (#411 #412), setup recommends instead of forcing (#406 #403 #364 #384), fixes #352 #365 #369 #371 #375 #393 #408 #414; v0.1.32: split prompts faster (#340), AMD router +12%, Unsloth Q4 in setup, faster Q4 prompts, #326/#327/#342/#344 fixes, PR batch; v0.1.31: Unsloth UD-Q4_K_XL (experimental), GGUF-in-place low-RAM mode, Windows GGUF load 2x, server race + tokenizer fixes, AMD intrinsics; v0.1.30: short prompts faster (streaming from 1024 tokens), resident low-RAM variant, multi-GPU session carve, RDNA4; v0.1.29: sampled answers faster (split top-k), #154 correctness fixes; v0.1.28: the expert cache reserves the draft head, a cancelled request no longer fails the next; v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties 267# KV bytes per context token and attention layer: 8-bit 1056, rotated 4-bit 576, hybrid K8V4 (8-bit K, 4-bit V) 816 268KV_CELL_BYTES = {"q4_0" :576 ,"k8v4" :816 } 269PY_PACKAGES = ["numpy" ,"jinja2" ,"regex" ,"pyyaml" ,"tqdm" ,"requests" ,"pillow" ,"psutil" ] 270REQUIREMENTS = ROOT / "requirements.txt" # the same packages and their dependencies, pinned (#214) 271BUILD_PACKAGES = ["cmake" ,"ninja" ] 272BUILD_REQUIREMENTS = ROOT / "requirements-build.txt" 273 274# NVFP4 experts (MODEL-UPDATE Phase 4; the engine path is ported from sergqwer/strata-nvfp4, MIT). Ready-made Strata 275# packs on Hugging Face by the fork's author: nothing is converted here. Every file is pinned by its upload's commit, 276# size and SHA-256 (the fork's setup.py NVFP4_REPOS, checked against the Hub's LFS pointers 2026-10-12). The FP8 n-gram 277# table and the BF16 token embedding are the same files in both repositories (a second install links them). The 278# MTP draft layer is setup's own, as for every other model, so the repositories' mtp/ folder is not downloaded. 279# role: pack = the experts pack folder (index.txt, experts.bin, ...), dense = the dense GGUF (--native and 280# --native-dense-gguf), ple = the FP8 n-gram table (--ple-gguf), embd = the BF16 token embedding (--embd-gguf) 281NVFP4_GPTQ_REPO = "Maximilian228/Qwen3.8-Flash-Next-NVFP4-GPTQ-Strata" # Qwen's BF16 experts by GPTQ (the fork) 282NVFP4_NVIDIA_REPO = "Maximilian228/Qwen3.8-Flash-Next-NVIDIA-NVFP4-Strata" # nvidia/Qwen3.8-Flash-Next-NVFP4, converted 283_NVFP4_TOKENIZER = { 284"pack/tokenizer/chat_template.jinja" : ("pack" ,8952 ,"c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041" ), 285"pack/tokenizer/merges.txt" : ("pack" ,3600844 ,"080cf95432173729d160346b7882bd2a644b07f7a3813a3eb73f4e66787bfde9" ), 286"pack/tokenizer/token_type.json" : ("pack" ,744960 ,"5088c8c298fc06af8382ddb3b76c888703ac2634e82263b97eedcc2ad202738b" ), 287"pack/tokenizer/tokenizer.json" : ("pack" ,554 ,"87be2ac47d8bc7393b7435df6ccd276740019a393941a2585d5edce59f450c54" ), 288"pack/tokenizer/vocab.json" : ("pack" ,5737005 ,"4ba64f0332abcfb0b600b7df1537d1e836e68009d5fb7cdb77339738dc6365c4" ), 289} 290_NVFP4_SHARED = { 291"ple-fp8.gguf" : ("ple" ,51200246176 ,"37f89b8ce5a3425932763257c40229ec02723ad2ab14b4bbfc26a486f4725c9c" ), 292"token-embd-bf16.gguf" : ("embd" ,1271398656 ,"386203af9070c7b43acb24ded8922876721d97bbad1a709b25cb49d694a7f51d" ), 293} 294NVFP4_REPOS = { 295NVFP4_GPTQ_REPO : {"revision" :"640a1db97446ddd5e89d2b70ecd0297987192c93" ,"files" : { 296"pack/dense.bin" : ("pack" ,1538035200 ,"974df6dcefcae85e3fd2c19fcc12eeaacaadde8261ab732d5af5af6ce2e25a7a" ), 297"pack/experts.bin" : ("pack" ,67948118016 ,"325e5e0d85c262a8d8278daf73b20696ec877d9a3ff584e57391fa69ad10bc64" ), 298"pack/index.txt" : ("pack" ,93663 ,"f62dc71e1c74a72794db54d3917bc71131cc6eae6f3dcdc3fdada48ff70f93ab" ), 299"pack/native_experts.txt" : ("pack" ,1599 ,"615f655fb28bf60b243664860b135710bf4177b111c6be89073e780a35de1018" ), 300** _NVFP4_TOKENIZER , 301"qwen-nvfp4-gptq-dense.gguf" : ("dense" ,5991569472 ,"abdf74336b53d8f7ca3d99947f1eac8f19b8a544966750127cb61e561b127e3b" ), 302** _NVFP4_SHARED }}, 303NVFP4_NVIDIA_REPO : {"revision" :"cca8f7fee5ce0af932097340a75e06df25c4e57d" ,"files" : { 304"pack/dense.bin" : ("pack" ,1538625024 ,"1f1c2422069de292673ae6cee7d69f7090732dec69f3f125612a0de456279714" ), 305"pack/experts.bin" : ("pack" ,67948118016 ,"bb42080bb7585505b64d091d5a734c05376bbd6171406fa9688a46fbc261b957" ), 306"pack/index.txt" : ("pack" ,117490 ,"17793d1c5b187a73d3c1dc1677af4d4c9b23845394dd7e88bfa53396b41b77e3" ), 307"pack/native_experts.txt" : ("pack" ,1590 ,"d7f8b4372bb122f3d711030e5d522bff1c8746ac7d133a59a2cc7277283e59b6" ), 308** _NVFP4_TOKENIZER , 309"qwen-nvidia-nvfp4-dense.gguf" : ("dense" ,5992176896 ,"0f795ca0cbb908e0cf2b894b30103e21455b5a05346a7ef79da208540cfd2be3" ), 310** _NVFP4_SHARED }}, 311} 312NVFP4_FP4LOCAL_REPO = "nvidia/Qwen3.8-Flash-Next-FP4-Local" # NVIDIA's QAD checkpoint (ModelOpt safetensors), prepared here 313# Not a ready-made pack: the safetensors (95 GiB) are downloaded as NVIDIA ships them and tools/nvfp4_local_pack.py prepare 314# turns them into the pack, the dense GGUF, the n-gram table and the draft layer on this PC (nothing of NVIDIA's weights is 315# redistributed). Role "src" = a file of the checkpoint; the prepared files are in FP4LOCAL_PREPARED. 316NVFP4_REPOS [NVFP4_FP4LOCAL_REPO ]= {"revision" :"b9ce18a6887e18c089fdea8509a33e63429a3300" ,"files" : { 317"config.json" : ("src" ,75217 ,"b50dbc52a0c83b0cd2a44a372c1fb6b5e0e6827d22f2611c97d4d030f92f6b28" ), 318"generation_config.json" : ("src" ,202 ,"e70c136c1b78ddc1fb0905bac8e733a4dc448d4f852a5dd75143fffc70be550e" ), 319"chat_template.jinja" : ("src" ,8952 ,"c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041" ), 320"merges.txt" : ("src" ,3353259 ,"a9d356d7bdf1ef4949e3e748e95b8e10ad9d4e2e838eddc38a0a7b6b94d1db8d" ), 321"tokenizer.json" : ("src" ,12809320 ,"0997f410c57a1f4e53b09e4be8f4a172d90edd9564368fb0847030937229b9f3" ), 322"tokenizer_config.json" : ("src" ,17928 ,"b11349aafa7cdc6a320767cf7ceb29ed82f7eda5d65e8e0819e76f0ce947bf27" ), 323"vocab.json" : ("src" ,6722759 ,"ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003" ), 324"model.safetensors.index.json" : ("src" ,47280974 ,"5fa166bbb1cf25adda455117563efa72a2072272001f459eedece131ffc913e1" ), 325"tensors/model-00001-of-00021.safetensors" : ("src" ,5000643504 ,"ebf3648c5f4cd1f24e79789e7803498dc4e74cb52515cc515b2d22cf8161953b" ), 326"tensors/model-00002-of-00021.safetensors" : ("src" ,5002792096 ,"79a643fc5c024089cecd32ca27dc43e671cbec70ff3628b728909b7656ac43ec" ), 327"tensors/model-00003-of-00021.safetensors" : ("src" ,5002927400 ,"c45f942203db4c7f5a1071700b93b908495cc790271acddfff39091c2b953923" ), 328"tensors/model-00004-of-00021.safetensors" : ("src" ,5003194672 ,"071ab9cf963ca0f1a6a194b4cec485f5de18ef9804da915b2e6abd0eb0c707af" ), 329"tensors/model-00005-of-00021.safetensors" : ("src" ,5003151448 ,"f80d17870eb1d36917257494770984953476583c57737f61fdbd341c957b9715" ), 330"tensors/model-00006-of-00021.safetensors" : ("src" ,5002892148 ,"3e9183d4ebb267fa92429184d5132d302cb1a98fd049149e5d01dccd4ca65795" ), 331"tensors/model-00007-of-00021.safetensors" : ("src" ,5002907708 ,"aa1ad959c4d62e0bc4600fd0b57cc2939b463e9fb53dc01020e188552b52ce5a" ), 332"tensors/model-00008-of-00021.safetensors" : ("src" ,5003103756 ,"0b18844027be74b84b240f23bf3a744bc29b35de0bd384f41c40cd85e6339326" ), 333"tensors/model-00009-of-00021.safetensors" : ("src" ,5002976316 ,"2d0b6c66790c17f8b1fdcf442f541778c8f0a381aca26c11b9d7cfcf7c96f2f0" ), 334"tensors/model-00010-of-00021.safetensors" : ("src" ,5002834136 ,"3ed9bd73745aebf6dc136f437b67d6b9fc3d38d25ad84300b399164bc87a72b7" ), 335"tensors/model-00011-of-00021.safetensors" : ("src" ,5002685828 ,"4936ff28c6cc8b66653ddb9cae28bc284569a1a2f7116819a017dc1a0e517ed8" ), 336"tensors/model-00012-of-00021.safetensors" : ("src" ,5002912920 ,"dd7df5a6ff73e9960412243f744eab9ec35f4be40da5bb158dc4ba8796b33742" ), 337"tensors/model-00013-of-00021.safetensors" : ("src" ,5003237060 ,"28a455c8ea4ebaa847fb4cbed2bc1de9eff0b501dd3f848a3a3cfc38778e8500" ), 338"tensors/model-00014-of-00021.safetensors" : ("src" ,4845006312 ,"6941676e685abf9817d9c48a17fdeda20b2b72d16217555252aa4c602b7f98b8" ), 339"tensors/model-00015-of-00021.safetensors" : ("src" ,4860574920 ,"2a1129b5acfc24a45bf402aa63dcef08b531aedfdaf5233c65fd3d12dc303fdd" ), 340"tensors/model-00016-of-00021.safetensors" : ("src" ,4950031028 ,"635e97fbad78fa988647d407e2b58e55d551ef94d798c9b6fb5550de25e86429" ), 341"tensors/model-00017-of-00021.safetensors" : ("src" ,4950030896 ,"bf60d564d89a805b67f8be5f2847a1b1567a70dbc23d19754395c127568474ad" ), 342"tensors/model-00018-of-00021.safetensors" : ("src" ,4950030896 ,"c5bde22f9364e82eb25973456795592fdcb4b158bc2095898979a2566bf4c562" ), 343"tensors/model-00019-of-00021.safetensors" : ("src" ,4950030904 ,"da3dc3b4f428f5b9dd53362691043d0242f48d03adca9b7b553bd9f3a1e96350" ), 344"tensors/model-00020-of-00021.safetensors" : ("src" ,4950030904 ,"4978bb6b8480cfc02d3c8bc84ba86202889f5f10d090bb17c21fee663cea7683" ), 345"tensors/model-00021-of-00021.safetensors" : ("src" ,2700016864 ,"48203838f2c76921bddbf1cc51d20a23858c128821a21add55fa1778e5e25283" ), 346}} 347FP4LOCAL_PREPARED = "prepared" # <models>/nvidia--Qwen3.8-Flash-Next-FP4-Local/prepared/ 348 349# the first release engine with NVFP4 experts (a source build of this checkout has them whatever its number says) 350NVFP4_ENGINE = (0 ,1 ,44 ) 351# the first engine that reads NVIDIA's NVFP4 n-gram table (strata.ple.format = nvfp4x16); a source build of this checkout has it 352FP4LOCAL_ENGINE = (0 ,1 ,45 ) 353 354# agentionai's Gyro files (Qwen3.8-Flash-Next with trellis-coded, Hadamard-rotated experts, TQ2_T / TQK6 / TQK7): one 355# GGUF per size, the n-gram table inside it (hence the 58 / 92 GB downloads for 27.6 / 35 GB of memory). The engine 356# reads them from 0.1.45.1 on: the experts are native_experts.txt v5 (Hadamard-folded, hadamard.txt), which the engine reads since the 357# APR port (commit f47b0385f, 2026-10-02, first in the 0.2.0 line). The released 0.1.45 engine reads only up to v4 and refuses a 358# Gyro pack, so 0.1.45 is NOT enough: 0.1.45.1 is the first engine package built after the reader was merged (checked: the 359# "native_experts.txt v5 declares Hadamard-folded experts" message is in every 0.1.45.1+ strata binary and in no 0.1.45 release one). 360# (ported from agentionai/Strata rc2, MIT); the sizes and SHA-256 are the Hub's LFS pointers 361# of the revision pinned in HF_REVISIONS. The model's license is Qwen's. 362GYRO_ENGINE = (0 ,1 ,45 ,1 ) 363GYRO_FILES = { 364"Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf" : 365 (58487015808 ,"c6ea1b08ca312f99095b27588ba35976b53f948268e7f91e7761926aa01d9c87" ), 366"Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf" : 367 (91965774272 ,"7aa36d15131d255179ab6c87fa9c9f81a0b541fc9e81e959d4c3e29eb20feb5f" ), 368} 369 370# ISTA-DASLab's Qwen3.8-Flash-Next shards (Q2_0, IQ2_XS, IQ3_XXS, IQ3_S) and the picture reader at the revision pinned in HF_REVISIONS: name -> (bytes, sha256), 371# the Hub's LFS pointers (tools/hf_pin_fetch.py). The n-gram table (shard 2) is the same file for all four sizes. 372ISTA_FILES = { 373"Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf" : 374 (39225954592 ,"92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7" ), 375"Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf" : 376 (28800138432 ,"316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" ), 377"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" : 378 (54817524224 ,"4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3" ), 379"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf" : 380 (28800138432 ,"316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" ), 381"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf" : 382 (47039860096 ,"219ea929900dfa9ef091f3aa473fdba6874b65fcb36526d7d851ac9e95856d15" ), 383"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf" : 384 (28800138432 ,"316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" ), 385"Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" : 386 (37623740192 ,"69820c02ec7d0b45ef2ebb19d6620299db749fe2aded7f39f93c6b88b199b720" ), 387"Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" : 388 (28800138432 ,"316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" ), 389"mmproj-Qwen3.8-Flash-Next-BF16.gguf" : 390 (907543008 ,"b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0" ), 391} 392# Swift 1.5's shards (Q2_0, IQ2_XS, IQ3_XXS, IQ3_S) and its picture reader, same source and form. 393SWIFT_FILES = { 394"Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf" : 395 (39788473344 ,"ca3b302d3d1eb6eddce3ea4acc79854e6cc5fdc0583e374a6a8b6bb67327743b" ), 396"Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf" : 397 (28363693824 ,"e4996a6de18fd49c58d9a0040fcfd73787db6407c51973f29884bee7b14c9dbb" ), 398"Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" : 399 (44900816736 ,"46cb3996cd1a17fe8bc5ae1f9bb16869480de5a03f17f868d6047a20a46edd3b" ), 400"Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf" : 401 (38842920384 ,"70ce6fb48a94fe34bd7e9a53a526be68066c64b5a5077cdc82fb31350b66b608" ), 402"Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf" : 403 (39785790560 ,"3bddaa667c750f63baca766df9433e1afd35a139f401c5ca5e7ff560ceff3d23" ), 404"Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf" : 405 (36180282560 ,"b0b15f782af71eb471909d2f3313b2927c324962f86c084325c247cd411a0160" ), 406"Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" : 407 (39799117984 ,"79e2a3873f1b05df835a1a191b20f2e74b9e12df949cd89861d17d98b6ef9678" ), 408"Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" : 409 (26750834816 ,"ef3bb04fb4e14f04624abd8acf25faf1603594a034050b048df85ec152ad5ae0" ), 410"mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf" : 411 (907543520 ,"cd1140f4abba943ce8d9fa92fed8407e389954d26907efde7b72153c75bd8a60" ), 412} 413# The Coder's IQ1_M shards and its picture reader (the original's file), same source and form. 414CODER_FILES = { 415"Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf" : 416 (29608446496 ,"e11083ba855e7666b48ea3f2db6a9c3a20c18751a012cc24f948de91b7087fad" ), 417"Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf" : 418 (28800138432 ,"316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" ), 419"mmproj-Qwen3.8-Flash-Next-BF16.gguf" : 420 (907543008 ,"b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0" ), 421} 422 423# Round 0214: Unsloth re-published the repository on 2026-11-04 (commit d9620119, "Dynamic v3.1"). The files of UD-Q4_K_XL, UD-IQ4_XS (three shards), 424# UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 stay at the commit in HF_REVISIONS (38bb39ee, pinned since 0.1.31); the sets that are new there (UNSLOTH_V31_SHARDS) name this 425# commit in their MODELS entry ("revision"), so a repository has more than one revision and the pin of a file is found by the commit its URL names (file_pin). 426UNSLOTH_REPO = "unsloth/Qwen3.8-Flash-Next-GGUF" 427UNSLOTH_V31_REVISION = "d96201194f103c906994f283f504209dc8d2a10c" # 2026-11-04 428UNSLOTH_V31_IQ4_XS = "UD-IQ4_XS-v31" # the catalog name of the new UD-IQ4_XS (its files on the Hub have the pinned one's names, with four shards instead of three) 429UNSLOTH_V31_ENGINE = (0 ,1 ,57 )# the engine that ships with these sets (i-quant experts with Q2_0 / IQ4_NL / Q5_0 downs, a Q6_K dense side) 430 431MODELS = { 432# the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which 433# the pack tool (tools/iq_pack.py) cannot prepare yet (#171) 434"Q2_0" : {"about" :"2-bit, the fastest" ,"download_gb" :66.4 ,"ram_gb" :48 ,"arena_gb" :34.0 ,"families" : ("qwen" ,)}, 435"IQ2_XS" : {"about" :"2-bit i-quant, a little better quality, close in speed" ,"download_gb" :68.0 ,"ram_gb" :48 , 436"arena_gb" :35.5 }, 437"IQ3_XXS" : {"about" :"3-bit i-quant, better quality, slower (more CPU work per token)" ,"download_gb" :75.8 , 438"ram_gb" :60 ,"arena_gb" :42.9 }, 439# matches the full BF16 model on the published benchmarks; Swift 1.5 got an IQ3_S tier of its own (#1651) 440"IQ3_S" : {"about" :"3.5-bit i-quant, the best quality (matches the full model), the slowest; needs a 64 GB PC " 441"with little else running" ,"download_gb" :83.6 ,"ram_gb" :62 ,"arena_gb" :50.3 }, 442# the Coder release: 256 of the 512 experts kept (the ones code, tools and vision use), IQ2_S-IQ4_XS like IQ3_S 443"IQ1_M" : {"about" :"the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)" ,"download_gb" :58.4 , 444"ram_gb" :32 ,"arena_gb" :23.4 ,"families" : ("coder" ,)}, 445# #621: Unsloth's UD-IQ4_XS - IQ3_S gate/up experts with IQ4_NL (43 layers) or Q8_0 (5) downs, the dense side as 446# UD-Q4_K_XL's; three shards. A regular choice from 0.1.39 (no longer experimental). Its 59.5 GB of experts: a 447# RAM budget of them, like UD-Q4_K_XL, but far fewer read from the SSD on a 64 GB PC and none from ~80 GB of RAM. 448# Images: the vision path has no restriction for this pack (the same base model and image encoder), so setup asks 449"UD-IQ4_XS" : {"about" :"~4-bit i-quant (Unsloth Dynamic), between IQ3_S and UD-Q4_K_XL in quality; on a PC with " 450"less than ~80 GB of RAM part of its experts are read from the SSD" , 451"download_gb" :93.7 ,"ram_gb" :48 ,"arena_gb" :59.5 ,"families" : ("unsloth" ,),"budget" :True , 452"shards" :3 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00003.gguf" ,"engine" : (0 ,1 ,38 ), 453"vision" :True }, 454# Unsloth's 4-bit file (docs/UNSLOTH_Q4.md); experimental until MODEL-UPDATE Phase 2. Its 77 GB of experts stay in 455# RAM from ~94 GB of RAM (unsloth_budget); on a 64 GB PC the engine keeps a RAM budget of them 456# (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD. It runs on AMD too (R9700: 457# the quality yardstick and the decode/prompt numbers in docs/QUANTS.md), so it is no longer NVIDIA-only (#429). 458"UD-Q4_K_XL" : {"about" :"4-bit (Unsloth Dynamic): K-quant experts, between UD-IQ4_XS and UD-Q5_K_XL in quality" , 459"download_gb" :111.3 ,"ram_gb" :48 ,"arena_gb" :77.0 ,"families" : ("unsloth" ,),"budget" :True , 460# #967 / MODEL-UPDATE: images run end to end with this file (CUDA: RTX A4000, GPU encoder; HIP: 461# R9700, CPU encoder; the test picture's text and shapes as the IQ3_XXS pack answers them) 462"vision" :True }, 463# MODEL-UPDATE: Unsloth's larger files (docs/QUANTS.md). The same GGUF-in-place mode: every expert in RAM where it 464# fits with UNSLOTH_RESIDENT_BESIDE_GB more (unsloth_budget), else a RAM budget of them and the rest read from the 465# SSD while it answers - so "ram_gb" is the all-in-RAM need, and below it setup asks first (default no). Their 466# shards 2 (the head) and 3 (the 54 GB Q8_0 PLE table) are the same bytes in all three files. UD-Q5_K_XL and 467# UD-Q6_K_XL need the Q6_K expert kernels every engine has from MODEL-UPDATE Phase 1 on (Q5: layer 2's gate/up). 468"UD-Q5_K_XL" : {"about" :"5-bit (Unsloth Dynamic): Q5_K experts with Q8_0 downs, close to Q8_0 in quality" , 469"download_gb" :158.3 ,"ram_gb" :108 ,"arena_gb" :98.4 ,"families" : ("unsloth" ,),"budget" :True , 470"shards" :6 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf" ,"engine" : (0 ,1 ,44 ), 471"vision" :True }, 472"UD-Q6_K_XL" : {"about" :"6-bit (Unsloth Dynamic): Q6_K experts with Q8_0 downs" , 473"download_gb" :169.2 ,"ram_gb" :118 ,"arena_gb" :109.2 ,"families" : ("unsloth" ,),"budget" :True , 474"shards" :6 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf" ,"engine" : (0 ,1 ,44 ), 475"vision" :True }, 476"Q8_0" : {"about" :"8-bit, the reference quality (every expert Q8_0); for a 192 GB PC" , 477"download_gb" :188.2 ,"ram_gb" :136 ,"arena_gb" :128.3 ,"families" : ("unsloth" ,),"budget" :True , 478"shards" :6 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf" ,"engine" : (0 ,1 ,38 ), 479"vision" :True }, 480# Round 0214: Unsloth's v3.1 sets (revision UNSLOTH_V31_REVISION, pins UNSLOTH_V31_SHARDS): i-quant / Q2_0 experts, the last shard is the n-gram table 481# (IQ4_NL, 28.8 GB, in a shard of its own); "quant" is the name on the Hub (folder and file names). The about lines come with the wording commit. 482# download_gb / arena_gb: the pinned shard sizes and the routed experts' bytes (tests/fixtures/unsloth_v31); ram_gb: the RAM-budget floor of UD-Q4_K_XL. 483"UD-IQ1_M" : {"about" :"~1-bit (Unsloth Dynamic v3.1), the smallest download" ,"download_gb" :68.0 ,"ram_gb" :48 ,"arena_gb" :34.8 ,"families" : ("unsloth" ,),"budget" :True , 484"shards" :3 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00003.gguf" ,"quant" :"UD-IQ1_M" , 485"revision" :UNSLOTH_V31_REVISION ,"engine" :UNSLOTH_V31_ENGINE ,"vision" :True ,"uma_pool_auto" :True }, 486"UD-Q2_0" : {"about" :"2-bit (Unsloth Dynamic v3.1)" ,"download_gb" :70.5 ,"ram_gb" :48 ,"arena_gb" :37.4 ,"families" : ("unsloth" ,),"budget" :True , 487"shards" :3 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00003.gguf" ,"quant" :"UD-Q2_0" , 488"revision" :UNSLOTH_V31_REVISION ,"engine" :UNSLOTH_V31_ENGINE ,"vision" :True ,"uma_pool_auto" :True }, 489"UD-IQ2_XS" : {"about" :"2-bit i-quant (Unsloth Dynamic v3.1)" ,"download_gb" :75.8 ,"ram_gb" :48 ,"arena_gb" :42.3 ,"families" : ("unsloth" ,),"budget" :True , 490"shards" :3 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00003.gguf" ,"quant" :"UD-IQ2_XS" , 491"revision" :UNSLOTH_V31_REVISION ,"engine" :UNSLOTH_V31_ENGINE ,"vision" :True ,"uma_pool_auto" :True }, 492"UD-Q2_K_XL" : {"about" :"2-bit (Unsloth Dynamic v3.1) with some 3-bit experts" ,"download_gb" :79.6 ,"ram_gb" :48 ,"arena_gb" :46.0 ,"families" : ("unsloth" ,),"budget" :True , 493"shards" :4 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf" ,"quant" :"UD-Q2_K_XL" , 494"revision" :UNSLOTH_V31_REVISION ,"engine" :UNSLOTH_V31_ENGINE ,"vision" :True ,"uma_pool_auto" :True }, 495"UD-IQ3_XXS" : {"about" :"3-bit i-quant (Unsloth Dynamic v3.1)" ,"download_gb" :83.6 ,"ram_gb" :48 ,"arena_gb" :50.3 ,"families" : ("unsloth" ,),"budget" :True , 496"shards" :4 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf" ,"quant" :"UD-IQ3_XXS" , 497"revision" :UNSLOTH_V31_REVISION ,"engine" :UNSLOTH_V31_ENGINE ,"vision" :True ,"uma_pool_auto" :True }, 498"UD-Q3_K_XL" : {"about" :"3-bit (Unsloth Dynamic v3.1) with some 4-bit experts" ,"download_gb" :89.5 ,"ram_gb" :48 ,"arena_gb" :56.2 ,"families" : ("unsloth" ,),"budget" :True , 499"shards" :4 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf" ,"quant" :"UD-Q3_K_XL" , 500"revision" :UNSLOTH_V31_REVISION ,"engine" :UNSLOTH_V31_ENGINE ,"vision" :True ,"uma_pool_auto" :True }, 501# the v3.1 UD-IQ4_XS is another file from the pinned UD-IQ4_XS (345 of 1224 tensors changed type; four shards): its own name 502UNSLOTH_V31_IQ4_XS : {"about" :"~4-bit i-quant (Unsloth Dynamic v3.1), a newer file than UD-IQ4_XS with other tensor types" ,"download_gb" :93.7 ,"ram_gb" :48 ,"arena_gb" :60.4 ,"families" : ("unsloth" ,),"budget" :True , 503"shards" :4 ,"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf" ,"quant" :"UD-IQ4_XS" , 504"revision" :UNSLOTH_V31_REVISION ,"engine" :UNSLOTH_V31_ENGINE ,"vision" :True ,"uma_pool_auto" :True }, 505# MODEL-UPDATE Phase 4: NVFP4 experts, ready-made packs (NVFP4_REPOS). 63.3 GiB (68.0 GB) of experts in the 506# pack's experts.bin; the low-RAM mode reads them from there on a PC whose RAM does not hold them. NVIDIA only 507# (the HIP and SYCL engines have no NVFP4 kernels). Images: both packs keep Qwen's vision tower unquantized, so the 508# original's image encoder (ISTA's mmproj, the same file as for every Flash-Next model) reads pictures for them; 509# checked end to end on an RTX 5070 and an RTX 3060 against IQ3_XXS's answers on the same picture. 510# Gyro (agentionai): "ram_gb" is the memory the weights need in total, VRAM and RAM together ("mem_total"): Gyro-S 511# 27.6 GB, Gyro-M 35 GB (the rest of the download is the n-gram table, read from the SSD). Neither is anyone's 512# default: setup and the MCP server mention them where the other sizes do not fit. Images: the same mmproj as every 513# Flash-Next model; strata-vision reads only the vocabulary and header of the Gyro GGUF (tools/vision/gguf_meta.h), 514# whose TQK6 / TQK7 tensors llama.cpp does not know. 515"Gyro-S" : {"about" :"the smallest option, for PCs with little memory (27.6 GB of VRAM + RAM together); lower quality " 516"than the 2-3-bit sizes, and the 2-bit Q2_0 decodes faster" , 517"download_gb" :58.5 ,"ram_gb" :27.6 ,"arena_gb" :25.8 ,"families" : ("gyro" ,),"mem_total" :True , 518"file" :"Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf" ,"shards" :1 ,"engine" :GYRO_ENGINE ,"vision" :True }, 519"Gyro-M" : {"about" :"about IQ3_XXS quality with about 20% less GPU memory (35 GB of VRAM + RAM together); decodes " 520"about 16-21% slower than Q2_0 on 12 GB cards" , 521"download_gb" :92.0 ,"ram_gb" :35.0 ,"arena_gb" :32.1 ,"families" : ("gyro" ,),"mem_total" :True , 522"file" :"Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf" ,"shards" :1 ,"engine" :GYRO_ENGINE ,"vision" :True }, 523"NVFP4" : {"about" :"best quality of the NVFP4 versions (GPTQ, sergqwer's strata-nvfp4 pack); RTX 50 has FP4 tensor cores, " 524"other NVIDIA cards run it at 8-bit precision" ,"download_gb" :128.0 ,"ram_gb" :80 ,"arena_gb" :68.0 , 525"families" : ("nvfp4" ,),"nvidia_only" :True ,"vision" :True ,"repo" :NVFP4_GPTQ_REPO , 526"engine" :NVFP4_ENGINE , 527"license" :"Qwen Community License 1.0 (Qwen3.8-Flash-Next's): https://huggingface.co/Qwen/Qwen3.8-Flash-Next" }, 528"NVFP4-NVIDIA" : {"about" :"NVIDIA's own NVFP4 checkpoint (plain rounding), converted by sergqwer; the same size " 529"and speed as NVFP4" ,"download_gb" :128.0 ,"ram_gb" :80 ,"arena_gb" :68.0 , 530"families" : ("nvfp4" ,),"nvidia_only" :True ,"vision" :True ,"repo" :NVFP4_NVIDIA_REPO , 531"engine" :NVFP4_ENGINE , 532"license" :"NVIDIA Open Model License (Licensed by NVIDIA Corporation under the NVIDIA Open Model " 533"License) with Qwen3.8-Flash-Next's Qwen Community License 1.0: " 534"https://huggingface.co/nvidia/Qwen3.8-Flash-Next-NVFP4" }, 535"NVFP4-QAD" : {"about" :"NVIDIA's FP4, trained for FP4 (NVIDIA's Qwen3.8-Flash-Next-FP4-Local) - slightly faster on short prompts; " 536"a 102 GB download that this PC turns into a Strata pack once (about 20-40 minutes, 110 GB more disk); " 537"RTX 50 cards have FP4 tensor cores, other NVIDIA cards run it at 8-bit precision. It reads pictures (the shared Qwen3.8-Flash-Next encoder)" , 538"download_gb" :102.2 ,"prepare_gb" :110.0 ,"ram_gb" :80 ,"arena_gb" :68.0 , 539"families" : ("nvfp4" ,),"nvidia_only" :True ,"vision" :True ,"repo" :NVFP4_FP4LOCAL_REPO , 540"prepare" :"fp4-local" ,"engine" :FP4LOCAL_ENGINE , 541"license" :"NVIDIA Open Model Agreement (Licensed by NVIDIA Corporation under the NVIDIA Open Model " 542"Agreement) with Qwen3.8-Flash-Next's Qwen Community License 1.0: " 543"https://huggingface.co/nvidia/Qwen3.8-Flash-Next-FP4-Local" }, 544} 545# The experimental Unsloth file's four shards at the pinned revision: name -> (bytes, sha256), checked after the 546# download (setup trusts no other model file by name and size alone either: check_shards reads their directories). 547UNSLOTH_SHARDS = { 548"Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" : 549 (10946624 ,"4448186216b3af4cc558bbce2c3213f01608f8f8b2e5267a9767971dd3ec8082" ), 550"Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf" : 551 (49859583136 ,"3f342f1c1580473f1ee94ddd5b28206e8c07a70fa1a366f59d1d6c922919a6c9" ), 552"Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf" : 553 (49376141504 ,"56758f40269cad5cd9b0d3d6fbae0f40f6d5be6de49e4ab392dbe83157d9cbd3" ), 554"Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf" : 555 (12087983520 ,"753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a" ), 556} 557# #621: UD-IQ4_XS's three shards at the same revision (sizes and SHA-256: the Hub's LFS pointers) 558UNSLOTH_IQ4_XS_SHARDS = { 559"Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf" : 560 (10946624 ,"5ce89370720f8bf90890f439361282104c1aa1482d4013bb9a50923e758e71a4" ), 561"Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00003.gguf" : 562 (49835229856 ,"577a38a2392b40ca2193cea502e1d92f60b8cd370675d308e0ec21885d9daaa7" ), 563"Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf" : 564 (43836407744 ,"d4634e6d84f0ebb0940be15c90d3790bf6464e3dea3a1cddc567dc0e83ad8833" ), 565} 566# MODEL-UPDATE: UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 at the same revision (sizes and SHA-256: the Hub's LFS pointers; shards 567# 2 and 3 are byte-identical across the three) 568UNSLOTH_BIG_SHARDS = { 569"Qwen3.8-Flash-Next-UD-Q5_K_XL-00001-of-00006.gguf" : 570 (10946618 ,"610922cdb1afe1094e95d7a3e86b12ee33317ebbf7320ac9344e21b6ae4bb69f" ), 571"Qwen3.8-Flash-Next-UD-Q5_K_XL-00002-of-00006.gguf" : 572 (682434912 ,"494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e" ), 573"Qwen3.8-Flash-Next-UD-Q5_K_XL-00003-of-00006.gguf" : 574 (54400261312 ,"34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20" ), 575"Qwen3.8-Flash-Next-UD-Q5_K_XL-00004-of-00006.gguf" : 576 (49990245824 ,"9ee6bbe462e6830864382d629101490625b1c95afa15492b7ad550c7bed2dd13" ), 577"Qwen3.8-Flash-Next-UD-Q5_K_XL-00005-of-00006.gguf" : 578 (49882416192 ,"0b2437f661f584030cb5aeb8fb1bb70f6422518a6746bfcc0304167c7b6b8beb" ), 579"Qwen3.8-Flash-Next-UD-Q5_K_XL-00006-of-00006.gguf" : 580 (3320101792 ,"55dd96c5ad0863b06b6393151b9ad0ac727b8d58a62e02a296ca5d5ddbfee4a3" ), 581"Qwen3.8-Flash-Next-UD-Q6_K_XL-00001-of-00006.gguf" : 582 (10946624 ,"8bdc6bad55b6699f46f60708829932ff4018d7ac9bd309c388534fa31753bdb7" ), 583"Qwen3.8-Flash-Next-UD-Q6_K_XL-00002-of-00006.gguf" : 584 (682434912 ,"494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e" ), 585"Qwen3.8-Flash-Next-UD-Q6_K_XL-00003-of-00006.gguf" : 586 (54400261312 ,"34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20" ), 587"Qwen3.8-Flash-Next-UD-Q6_K_XL-00004-of-00006.gguf" : 588 (49814108512 ,"0ea4b599880a5a52fcd9c188ba1443f646c69c96571904ddbd6a79246a01a997" ), 589"Qwen3.8-Flash-Next-UD-Q6_K_XL-00005-of-00006.gguf" : 590 (49419317344 ,"9948e81ae8368144b135a7403d8c0f2cf9a6c2f9f692313865855b2832e696c9" ), 591"Qwen3.8-Flash-Next-UD-Q6_K_XL-00006-of-00006.gguf" : 592 (14838313984 ,"e4ae255234f42b18012f6d6eec5bf615b57479b7e0a0233c47436a321ffeec3f" ), 593"Qwen3.8-Flash-Next-Q8_0-00001-of-00006.gguf" : 594 (10946624 ,"2dabcbb53ca537a7947bc7d20414fd464eeaf4d66d43021b5b2556cc87544ad2" ), 595"Qwen3.8-Flash-Next-Q8_0-00002-of-00006.gguf" : 596 (682434912 ,"494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e" ), 597"Qwen3.8-Flash-Next-Q8_0-00003-of-00006.gguf" : 598 (54400261312 ,"34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20" ), 599"Qwen3.8-Flash-Next-Q8_0-00004-of-00006.gguf" : 600 (49446841216 ,"bfa634025fabbd2658bf7694bc80b90e571699c768723f844c934c7ef06c691a" ), 601"Qwen3.8-Flash-Next-Q8_0-00005-of-00006.gguf" : 602 (49668930400 ,"232a8f14cc0fa4262e7efe8593774b136fe40909e39c7a020342ddaa27259a97" ), 603"Qwen3.8-Flash-Next-Q8_0-00006-of-00006.gguf" : 604 (34015618784 ,"538a93bca918064983409a41187ad4c68640f9aced6f29564da8f551bf86d7a5" ), 605} 606# Round 0214: the sets that are new at UNSLOTH_V31_REVISION (UD-IQ1_M, UD-Q2_0, UD-IQ2_XS, UD-Q2_K_XL, UD-IQ3_XXS, UD-Q3_K_XL and the v3.1 UD-IQ4_XS), name -> (bytes, 607# sha256): the Hub's LFS pointers (phaseA-tests/quants0211/unsloth-head-pins.json). The last shard of each is the n-gram table. No name is in UNSLOTH_SHARDS, 608# UNSLOTH_IQ4_XS_SHARDS or UNSLOTH_BIG_SHARDS (the v3.1 UD-IQ4_XS has four shards, the pinned one three). 609UNSLOTH_V31_SHARDS = { 610"Qwen3.8-Flash-Next-UD-IQ1_M-00001-of-00003.gguf" : 611 (10946618 ,"b0d883bb9464021f31074145af74bfc2aa2d4bf0cf506f26f6f5107f4ca6ce17" ), 612"Qwen3.8-Flash-Next-UD-IQ1_M-00002-of-00003.gguf" : 613 (39196009888 ,"bddcd79634ccddbb2e0951345c73c6ae8bd7b12594f55a2a529474701757391e" ), 614"Qwen3.8-Flash-Next-UD-IQ1_M-00003-of-00003.gguf" : 615 (28800138432 ,"05716382c280d999b81afff92b2d527fadbfd926ac225ffdc273f2d1d13331c6" ), 616"Qwen3.8-Flash-Next-UD-Q2_0-00001-of-00003.gguf" : 617 (10946618 ,"38803c4e8d13077165aa9854502b3d4e7fef750e72a21d27a38ee42089f96ad6" ), 618"Qwen3.8-Flash-Next-UD-Q2_0-00002-of-00003.gguf" : 619 (41738806688 ,"57af20207d5f18fa72fba503806d98d65f58ba3982fe55c89c6ed6e691471acc" ), 620"Qwen3.8-Flash-Next-UD-Q2_0-00003-of-00003.gguf" : 621 (28800138432 ,"05716382c280d999b81afff92b2d527fadbfd926ac225ffdc273f2d1d13331c6" ), 622"Qwen3.8-Flash-Next-UD-IQ2_XS-00001-of-00003.gguf" : 623 (10946618 ,"91e8dc8f1428ce25d48fd1f711e4bf1f42215c5bac0f32eeb5608e6ec7ae91e9" ), 624"Qwen3.8-Flash-Next-UD-IQ2_XS-00002-of-00003.gguf" : 625 (47021008288 ,"11a67c82f54a9edf683d6b708062de78d803921a18a6cb2bf1dd55949b4ef9bd" ), 626"Qwen3.8-Flash-Next-UD-IQ2_XS-00003-of-00003.gguf" : 627 (28800138432 ,"05716382c280d999b81afff92b2d527fadbfd926ac225ffdc273f2d1d13331c6" ), 628"Qwen3.8-Flash-Next-UD-Q2_K_XL-00001-of-00004.gguf" : 629 (10946618 ,"297e174dc185f2bf3ab1856461059cb8a05aa741bc27edf42461cde87e5420af" ), 630"Qwen3.8-Flash-Next-UD-Q2_K_XL-00002-of-00004.gguf" : 631 (49732486272 ,"a4782511810bb61bd6b3236607a0aad05b1bfa04b90356defd202bb17e7db16d" ), 632"Qwen3.8-Flash-Next-UD-Q2_K_XL-00003-of-00004.gguf" : 633 (1037181344 ,"4dffc4a1cea7ad484f2d5c711b747840e459b040b636cc8ddaa524d01e60662e" ), 634"Qwen3.8-Flash-Next-UD-Q2_K_XL-00004-of-00004.gguf" : 635 (28800138432 ,"5de8b5dbf89409acc39468decafd4a4a95b13c29d88a14b0356107897829ec36" ), 636"Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00004.gguf" : 637 (10946618 ,"9d5644b371ffac921427c8021cc7242dab8e3ba37d7b48d1e79fe3770fbf9915" ), 638"Qwen3.8-Flash-Next-UD-IQ3_XXS-00002-of-00004.gguf" : 639 (49946027488 ,"aacaff3bdb9032c2c3be428167930809735f65d3cfb204eba07d85e421e7ddf4" ), 640"Qwen3.8-Flash-Next-UD-IQ3_XXS-00003-of-00004.gguf" : 641 (4869325888 ,"ef8f14e790ab471b363f146d5e8664eefbaf03e5776f317a1fb96a2bc7707b07" ), 642"Qwen3.8-Flash-Next-UD-IQ3_XXS-00004-of-00004.gguf" : 643 (28800138432 ,"5de8b5dbf89409acc39468decafd4a4a95b13c29d88a14b0356107897829ec36" ), 644"Qwen3.8-Flash-Next-UD-Q3_K_XL-00001-of-00004.gguf" : 645 (10946618 ,"7666000ba91eb5527f8e12e0414de36766dc82a082876337f7827c2caa859143" ), 646"Qwen3.8-Flash-Next-UD-Q3_K_XL-00002-of-00004.gguf" : 647 (49742117248 ,"e954cb3044ae087a003ce8cc1631c9d40fe15ae64a8befcf4aa06457848c647c" ), 648"Qwen3.8-Flash-Next-UD-Q3_K_XL-00003-of-00004.gguf" : 649 (10911746208 ,"fcce26b1e5e6e54559a7e7c2f8d6e37067ec695ff1f14bce662810bde78abe1f" ), 650"Qwen3.8-Flash-Next-UD-Q3_K_XL-00004-of-00004.gguf" : 651 (28800138432 ,"5de8b5dbf89409acc39468decafd4a4a95b13c29d88a14b0356107897829ec36" ), 652"Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00004.gguf" : 653 (10946618 ,"93ff23a08e5cd7501f24fa16f5b415d5807d0175e04edd3ed6a7a41b601a4eef" ), 654"Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00004.gguf" : 655 (49604491008 ,"13d5dc8b93d039e4cfade5a9af7037f10c97f7ec4e53f75bd2e9ae34aae54aeb" ), 656"Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00004.gguf" : 657 (15256783680 ,"f6b9b5934908a2043732269dd740155d0f921d0763a1dcdd3452246311651f87" ), 658"Qwen3.8-Flash-Next-UD-IQ4_XS-00004-of-00004.gguf" : 659 (28800138432 ,"5de8b5dbf89409acc39468decafd4a4a95b13c29d88a14b0356107897829ec36" ), 660} 661# UD-Q4_K_XL as re-sharded at UNSLOTH_V31_REVISION: the same 1224 tensors, the n-gram table in a shard of its own. The file names are the pinned UD-Q4_K_XL's, so these are 662# NOT downloaded: setup keeps fetching the pinned files, and takes this layout from files already here (--gguf-dir, --model-path, the app's "Use a local GGUF") by size and 663# SHA-256 (fam_pin). One set or the other: the shard boundaries differ, so the shards of the two cannot be mixed. 664UNSLOTH_Q4_V31_SHARDS = { 665"Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" : 666 (10946618 ,"acc44040f74d0e55fb89c3967056cce5dbda1bcc52e909c3ba6fc72b5e9c0858" ), 667"Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf" : 668 (49720539552 ,"45792ae869072d8229384c51c7c73dd959e191505252b41dd71852d9746f5ce4" ), 669"Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf" : 670 (32803030176 ,"8c76e79d444b16a663d9c8db54e585ed3b1da13eebd2619c37b0c355da803c82" ), 671"Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf" : 672 (28800138432 ,"5de8b5dbf89409acc39468decafd4a4a95b13c29d88a14b0356107897829ec36" ), 673} 674UNSLOTH_ENGINE = (0 ,1 ,32 )# the first engine setup configures for UD-Q4_K_XL (0.1.31 ran it by hand) 675UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and the file cache the rest is read through 676UNSLOTH_MIN_RAM_GB = 48 # the RAM-budget mode below which setup says an Unsloth file does not fit (UD-Q4_K_XL's floor) 677# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will 678# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor 679# from the final context (final / 262144, at least 1) itself (below), keeps an explicit 680# --rope-scaling/--rope-scale, and refuses an explicit --rope-scaling none there - the stock angles past 681# the trained range are out of spec. 682# 204800 (200K) sits between 128K and 256K: it is inside the trained 262144, so it needs no rope scaling and 683# costs ~2.8 GB of 8-bit KV with IQ3_S (vs ~3.6 GB at 256K) - a middle step for PCs that cannot hold 256K. 684CONTEXTS = [8192 ,32768 ,65536 ,131072 ,204800 ,262144 ,393216 ,524288 ] 685# The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. 686FAMILIES = { 687"qwen" : {"title" :"Qwen3.8-Flash-Next" ,"by" :"Qwen; GSQ-RCO quants by ISTA-DASLab" , 688"about" :"the original model" , 689"hf" :hf ("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" )+ "{q}/" , 690"file" :"Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf" ,"tag" :"" , 691"mmproj_hf" :hf ("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ), 692"mmproj" :"mmproj-Qwen3.8-Flash-Next-BF16.gguf" ,"name" :"qwen3.8-flash-next" }, 693"swift" : {"title" :"Swift 1.5" ,"by" :"UkisAI's fine-tune of Qwen3.8-Flash-Next" , 694"about" :"thinks much shorter (-63% thinking tokens, 1.8x sooner answers by its authors' numbers)" , 695"hf" :hf ("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ), 696"file" :"Swift-Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf" ,"tag" :"swift-" , 697"mmproj_hf" :hf ("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ), 698"mmproj" :"mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf" ,"name" :"swift-1.5" , 699"license" :"Swift Open License 1.0: https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" }, 700# ISTA-DASLab's expert-pruned release: half of each layer's experts removed, chosen for code, agentic tool use and 701# vision; its shard 2 (the n-gram table) and vision encoder are the original's files, shared with it 702"coder" : {"title" :"Qwen3.8-Flash-Next Coder" ,"by" :"ISTA-DASLab's coding version" , 703"about" :"half the experts (code, tools, images kept): needs ~32 GB of RAM, faster; weaker outside coding" , 704"hf" :hf ("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF" )+ "{q}/" , 705"file" :"Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf" ,"tag" :"coder-" , 706"mmproj_hf" :hf ("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF" ), 707"mmproj" :"mmproj-Qwen3.8-Flash-Next-BF16.gguf" ,"name" :"qwen3.8-flash-next-coder" , 708"profile" :"expert-profile-coder.bin" }, 709# Unsloth's UD-IQ4_XS (three shards, #621), UD-Q4_K_XL (four), UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 (six) of the original 710# model (docs/QUANTS.md): regular choices since f-quants; the shard count and "vision" are per model (MODELS) 711"unsloth" : {"title" :"Qwen3.8-Flash-Next (Unsloth)" ,"by" :"Unsloth's 1- to 8-bit quantizations" , 712"about" :"UD-IQ1_M, UD-Q2_0, UD-IQ2_XS, UD-Q2_K_XL, UD-IQ3_XXS, UD-Q3_K_XL, UD-IQ4_XS, UD-IQ4_XS-v31, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL or Q8_0 (68 to 188 GB downloads): every expert in " 713"RAM from ~50 GB (UD-IQ1_M) to ~136 GB (Q8_0) of RAM, else part of them read from the SSD" , 714"hf" :hf ("unsloth/Qwen3.8-Flash-Next-GGUF" )+ "{q}/" , 715"file" :"Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf" ,"shards" :4 ,"tag" :"unsloth-" , 716"mmproj_hf" :hf ("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ), 717"mmproj" :"mmproj-Qwen3.8-Flash-Next-BF16.gguf" ,"name" :"qwen3.8-flash-next-unsloth" , 718"vision" :True ,"pack_args" : ["--compat-bf16" ], 719"sha256" : {** UNSLOTH_V31_SHARDS ,** UNSLOTH_SHARDS ,** UNSLOTH_IQ4_XS_SHARDS ,** UNSLOTH_BIG_SHARDS }, 720"sha256_alt" : {n : (pin ,)for n ,pin in UNSLOTH_Q4_V31_SHARDS .items ()}}, 721# MODEL-UPDATE Phase 4: the original model with NVFP4 experts, as ready-made packs (NVFP4_REPOS): the files come 722# as the engine reads them (no GGUF to pack), each size has its own repository ("repo" in MODELS) 723# agentionai's Gyro quantizations (see GYRO_FILES): after the regular families, never the default 724"gyro" : {"title" :"Qwen3.8-Flash-Next (Gyro)" ,"by" :"Gyro quantizations by agentionai" , 725"about" :"Gyro-S (27.6 GB of memory) and Gyro-M (35 GB): the smallest sizes, for PCs with little memory; " 726"58 and 92 GB downloads (the files include the n-gram table)" , 727"hf" :hf ("agentionai/Qwen3.8-Flash-Next-Gyro-GGUF" ),"file" :"Qwen3.8-Flash-Next-{q}.gguf" ,"shards" :1 , 728"tag" :"gyro-" ,"name" :"qwen3.8-flash-next-gyro" ,"vision" :True ,"pack_args" : ["--compat-bf16" ], 729"mmproj_hf" :hf ("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ),"mmproj" :"mmproj-Qwen3.8-Flash-Next-BF16.gguf" , 730"sha256" :GYRO_FILES , 731"license" :"Qwen Community License 1.0 (Qwen3.8-Flash-Next's; the Gyro files are agentionai's quantization): " 732"https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF" }, 733"nvfp4" : {"title" :"Qwen3.8-Flash-Next (NVFP4)" ,"by" :"NVFP4 packs by sergqwer (strata-nvfp4)" , 734"about" :"4-bit NVFP4 experts, NVIDIA cards; a 128 GB download, ~80 GB of RAM to keep every expert in RAM" , 735"tag" :"nvfp4-" ,"name" :"qwen3.8-flash-next-nvfp4" ,"ready" :True , 736"mmproj_hf" :hf ("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ),"mmproj" :"mmproj-Qwen3.8-Flash-Next-BF16.gguf" , 737"mmproj_sha256" : (907543008 ,"b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0" )}, 738} 739MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" 740# Qwen3.6-35B-A3B (GGUF architecture qwen35moe), Unsloth's GGUFs with the MTP block: a family with an engine path of its 741# own (src/qwen35; `strata` switches to it from the file's architecture). No pack, no expert profile, no separate MTP 742# draft layer: the engine reads the GGUF as it is, keeps every expert it can in VRAM and computes the rest on the CPU 743# (the hybrid mode), and drafts with the file's own MTP block. Not in FAMILIES (whose entries are Flash-Next files with 744# packs): OWN_PATH_FAMILIES, offered in the same menu and installed by install_own_path. NVIDIA (CUDA) and AMD (HIP) 745# only: the Intel Arc (SYCL) engine refuses it. 746QWEN36_FILES = { 747"Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf" : (22853663008 ,"55983c5a75a1ab969824077b3bb3de4146e82a9234072b48ad4e8f92ad3fe9f1" ), 748"Qwen3.6-35B-A3B-UD-Q6_K_XL.gguf" : (32611711264 ,"35fce994cd36104a7dc1bd8a4bdf13778145664c00fdef6773aebc9246e5019c" ), 749"Qwen3.6-35B-A3B-Q8_0.gguf" : (37801097504 ,"c1283d8b80c3e38b2735ddbc9766d3b3126f44d6c484be419d4e101d09a76131" ), 750"mmproj-F16.gguf" : (899283584 ,"71f3cbc1f7cc0f30d09d41cfa924c0060827ebc33bf15ace7e86661e856f0160" ), 751} 752OWN_PATH_FAMILIES = { 753"qwen36" : {"title" :"Qwen3.6-35B-A3B" ,"by" :"Qwen; GGUFs with the MTP layer by Unsloth" ,"arch" :"qwen35moe" , 754"about" :"35B mixture of experts with 3B active (256 experts, top-8): a smaller cousin of " 755"Qwen3.8-Flash-Next with the same tokenizer" , 756"hf" :hf ("unsloth/Qwen3.6-35B-A3B-MTP-GGUF" ),"file" :"Qwen3.6-35B-A3B-{q}.gguf" ,"tag" :"qwen36-" , 757"mmproj_hf" :hf ("unsloth/Qwen3.6-35B-A3B-MTP-GGUF" ),"mmproj" :"mmproj-F16.gguf" , 758"name" :"qwen3.6-35b-a3b" ,"license" :"Apache 2.0: https://huggingface.co/Qwen/Qwen3.6-35B-A3B" , 759# RAM: the engine keeps a copy of every expert in RAM when they do not all fit in VRAM (the hybrid mode), 760# so the file's size plus room for the OS and the rest (measured: UD-Q4_K_XL on a 46 GB PC with a 12 GB 761# card, 18.75 GiB of experts pinned) 762"models" : {"UD-Q4_K_XL" : {"about" :"4-bit (Unsloth Dynamic), the smallest" ,"ram_gb" :32 }, 763"UD-Q6_K_XL" : {"about" :"6-bit (Unsloth Dynamic), closer to the full model" ,"ram_gb" :44 }, 764"Q8_0" : {"about" :"8-bit, the closest to the full model" ,"ram_gb" :52 }}, 765"sha256" :QWEN36_FILES , 766# the engine's KV cache per context token: 10 attention layers + the MTP block, 2 KV heads x 256, K and 767# V in fp32 (strata-q36) 768"kv_bytes_per_token" :11 * 2 * 256 * 2 * 4 , 769"mtp" :2 ,# drafts per step (greedy requests): measured best on the R9700 770# pictures: Unsloth's mmproj (the same projector family as Flash-Next's: qwen3vl_merger) through 771# strata-vision; a parallel slot's session: its KV cache (kv_bytes_per_token) and the recurrent state of 772# the 30 GDN layers (state_gb) 773"vision" :True ,"state_gb" :0.07 } 774} 775PREVIEW_FAMILIES = OWN_PATH_FAMILIES # the earlier name (tools and tests that import it) 776 777# Every model file Strata downloads has a fixed size and SHA-256: (repository, file name) -> (bytes, sha256). download() 778# checks the file against it as soon as it is whole (a wrong file is deleted and setup stops), and stops before the 779# download when the server's size is not the pinned one. The files are fetched from the commits in HF_REVISIONS. 780REPO_PINS = { 781"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" :ISTA_FILES , 782"ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" :SWIFT_FILES , 783"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF" :CODER_FILES , 784UNSLOTH_REPO : {** UNSLOTH_V31_SHARDS ,** UNSLOTH_SHARDS ,** UNSLOTH_IQ4_XS_SHARDS ,** UNSLOTH_BIG_SHARDS }, 785"unsloth/Qwen3.6-35B-A3B-MTP-GGUF" :QWEN36_FILES , 786"agentionai/Qwen3.8-Flash-Next-Gyro-GGUF" :GYRO_FILES , 787} 788# the files of a repository at a commit other than HF_REVISIONS' (UNSLOTH_V31_REVISION): (repository, commit) -> name -> (bytes, sha256); file_pin looks here first 789REV_PINS = {(UNSLOTH_REPO ,UNSLOTH_V31_REVISION ): {** UNSLOTH_V31_SHARDS ,** UNSLOTH_Q4_V31_SHARDS }} 790# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README 791ESP_VECTOR = ROOT / "data" / "experimental-speed-projection" / "Qwen3.8-Flash-Next-experimental-speed-projection.gguf" 792# the image encoder on the GPU (~1.2 GB at 1024 image tokens) warms up before the engine starts, so the engine 793# sizes its expert slots around it and the default reserve (700 MiB) is enough; engines before 0.1.2 need more 794VISION_GPU_SMALL_RESERVE_MIB = 1000 # the tip for images on a <= 12 GB card (the engine's LOW line asked ~1003) 795VISION = {"gpu" : {"max_tokens" :1024 ,"reserve_mib" :700 }, 796"cpu" : {"max_tokens" :300 ,"reserve_mib" :0 }}# the CPU reader takes no VRAM: no reserve (serve/server.py adds 700 only for a GPU reader) 797EXE = "strata.exe" if WIN else "strata" 798VEXE = "strata-vision.exe" if WIN else "strata-vision" 799HVEXE = "strata-vision-hip.exe" if WIN else "strata-vision-hip" # AMD: the picture reader on the GPU (tools/vision, STRATA_VISION_HIP) 800# MODEL-UPDATE Phase 1: the K-quant prompt kernels (Unsloth's UD-Q4/Q5/Q6_K_XL experts) are a library next to the CUDA 801# engine, opened only for those models; an engine without it runs them on the FP16 prompt path 802KQ_LIB = "strata_kq.dll" if WIN else "libstrata_kq.so" 803 804 805# ------------------------------------------------------------------------------------------------ output 806def say (msg = "" ): 807msg ,flush = True ) 808 809 810def step (n ,title ): 811say () 812say (f"=== Step { n } : { title } ===" ) 813 814 815def ok (msg ): 816say (f" [ok] { msg } " ) 817 818 819def warn (msg ): 820say (f" [!] { msg } " ) 821 822 823def fail (msg ,hint = None ): 824say (f"\n [X] { msg } " ) 825if hint : 826say (f" { hint } " ) 827say ("\nSetup stopped. Fix the item above and run it again - everything already done is kept and skipped." ) 828sys .exit (1 ) 829 830 831def flush_typed_ahead ()-> None : 832"""#841: keys pressed while setup was busy (a download, a build) are not answers to the next question: Enter pressed 833to "wake" a slow step answered "Go on anyway?" with its default. Dropped before a question is asked, on a terminal 834only (a pipe or a test keeps its input).""" 835try : 836if not sys .stdin .isatty (): 837return 838if WIN : 839import msvcrt 840while msvcrt .kbhit (): 841msvcrt .getwch () 842else : 843import termios 844termios .tcflush (sys .stdin .fileno (),termios .TCIFLUSH ) 845except (ImportError ,OSError ,ValueError ,AttributeError ): 846pass 847 848 849def ask (question ,choices ,default ,yes ): 850if yes : 851return default 852flush_typed_ahead () 853while True : 854try : 855a = input (f" { question } [ { default } ]: " ).strip () 856except EOFError : 857fail ("input ended before a setup answer was received" , 858"run setup in a terminal, or pass --yes to accept the recommended answers" ) 859if not a : 860return default 861if a .lower ()in [c .lower ()for c in choices ]: 862return next (c for c in choices if c .lower ()== a .lower ()) 863say (f" please answer one of: { ', ' . join ( choices ) } " ) 864 865 866def _urlopen (req ,timeout = None ): 867"""Every network request of this file goes through here: starting and serving never reach the network 868(strata_control/acquisition.py), only an explicit setup, update or install does.""" 869acquisition .require ("a download" ) 870try : 871# strata_control/netpolicy.py: `timeout` bounds the connection phase (lookup, connect, TLS, the answer's headers); a read after 872# the answer that gets no byte for netpolicy.STALL_S ends the connection 873return netpolicy .urlopen (req ,timeout = timeout ) 874except urllib .error .URLError as e : 875if tls .is_certificate_error (e ):# not the raw urlopen text, and never a way to skip the check 876raise tls .CertificateProblem (tls .host_of (req .full_url if hasattr (req ,"full_url" )else str (req )))from None 877raise 878 879 880def _open_net (req ,check_memory :bool = True ): 881"""One request under the network rule (strata_control/netpolicy.py): 12 s, then one retry with 30 s, a line naming the host after 8825 s, and a host that did not answer is not asked again in this run. Raises netpolicy.NetFailure, HTTPError or CertificateProblem.""" 883return netpolicy .open_url (_urlopen ,req ,say = lambda line :say (f" { line } ..." ),check_memory = check_memory ) 884 885 886def net_fail (e :"netpolicy.NetFailure" ,url :str ,what = None ): 887"""setup's stop for a host that cannot be reached: the plain sentence, the one next step, then the proxy and ModelScope hints.""" 888extra = "" .join (" " + h [2 :3 ].upper ()+ h [3 :]+ "." for h in (proxy_hint (),source_hint (url ))if h ) 889if e .detail (): 890say (f" ( { e . host } : { e . detail () } )" )# the raw reason, for the log 891fail (e .headline (netpolicy .what_words (what )),e .next_step ()+ extra ) 892 893 894def run (cmd ,cwd = None ,env = None ,check = True ,quiet = False ): 895"""An install, build or preparation step (pip, cmake, a package manager, tools/*.py): never part of a start.""" 896acquisition .require ("an install or build step (" + Path (str (cmd [0 ])).name + ")" ) 897if CONTROL :# the app: only this Python running a bundled tool 898argv = [str (c )for c in cmd ] 899if len (argv )< 2 or os .path .normcase (argv [0 ])!= os .path .normcase (sys .executable )or argv [1 ]== "-m" or \ 900Path (argv [1 ]).resolve ().parent not in ((ROOT / "tools" ).resolve (), (ROOT / "metal" / "tools" ).resolve ()): 901raise acquisition .AcquisitionRefused ("the desktop app's installer only runs its bundled preparation tools; " 902+ " " .join (argv [:2 ])) 903say (" > " + " " .join (str (c )for c in cmd )) 904env = dict (os .environ if env is None else env ) 905env .setdefault ("STRATA_EXIT_WITH_PARENT" ,"1" )# tools/mtp_fetch.py ends when setup ends (#3257: a cancel left it writing) 906r = subprocess .run ([str (c )for c in cmd ],cwd = cwd ,env = env , 907stdout = subprocess .PIPE if quiet else None ,stderr = subprocess .STDOUT if quiet else None , 908text = True ,errors = "replace" ) 909if check and r .returncode != 0 : 910if quiet and r .stdout : 911say (r .stdout [- 4000 :]) 912fail (f"command failed (exit { r . returncode } ): { Path ( str ( cmd [ 0 ])). name } " ) 913return r 914 915 916def fetch_mtp (mtp :Path ,env :dict ,tries :int = 3 ): 917"""The ~5 GB of MTP tensors (tools/mtp_fetch.py). A timeout or a dropped connection stops one run, not the install (#3214 #3193): 918it is run again, and each run continues where the last one stopped. The progress lines it prints are what the app shows.""" 919cmd = [sys .executable ,str (ROOT / "tools" / "mtp_fetch.py" ),"fetch" ,"--out" ,str (mtp )] 920env = {** env ,"STRATA_SOURCE" :model_source ()} 921def on_disk ()-> int : 922try : 923return sum (f .stat ().st_size for f in Path (mtp ).rglob ("*" )if f .is_file ()) 924except OSError : 925return 0 926for n in range (1 ,tries + 1 ): 927before = on_disk () 928r = run (cmd ,env = env ,check = False ) 929rc = 0 if r is None else r .returncode # (a test double answers None) 930if rc == 0 : 931return True 932if rc == 5 :# tools/mtp_fetch.py OFFLINE: its [X] lines above say so; the model is set up and starts without the layer, 933return False # and the next launch with a connection fetches it (offline users: never a stop) 934if rc == 4 :# tools/mtp_fetch.py NO_ANSWER: its [X] lines above name the host and the next step 935say ("\nSetup stopped. Fix the item above and run it again - everything already done is kept and skipped." ) 936sys .exit (1 ) 937if r is not None and on_disk ()<= before :# the network rule: run again only when the last run moved bytes 938break 939if n < tries : 940warn (f"the draft layer's download stopped (exit { rc } ); trying again, it continues where it stopped " 941f"( { n + 1 } of { tries } )" ) 942time .sleep (5 ) 943fail (f"the draft layer's download keeps stopping (exit { rc } ): the connection to Hugging Face is slow or drops" , 944"run setup again - what is downloaded is kept. If it still stops, set STRATA_SOURCE=modelscope (setup --source modelscope) " 945"to read the same files from ModelScope" ) 946 947 948def out (cmd ): 949try : 950return subprocess .run (cmd ,capture_output = True ,text = True ,errors = "replace" ,timeout = 60 ).stdout or "" 951except (OSError ,subprocess .TimeoutExpired ): 952return "" 953 954 955def _kept_mark (path :Path )-> Path | None : 956"""Where the finish mark of a file in a folder Strata cannot write to is kept instead: marks/<hash>.done under Strata's own folder. The hash is of 957the file's full path, size and modification time, so a file that changed (or a different file at the same place) has no mark.""" 958try : 959st = path .stat () 960key = f" { path . resolve () } | { st . st_size } | { st . st_mtime_ns } " 961except OSError : 962return None 963return ROOT / "marks" / (hashlib .sha1 (key .encode ("utf-8" ,"replace" )).hexdigest ()[:24 ]+ ".done" ) 964 965 966def _change_time_ns (path :Path ,st :os .stat_result )-> int : 967"""The time of the file's last change of content or metadata, in ns. It moves on every write and on every setting of the modification time, 968so a file rewritten in place that keeps its size and modification time still shows a new value. Linux and Mac: st_ctime_ns. Windows: os.stat's 969ctime is the creation time there (an in-place rewrite keeps it), so the file system's own ChangeTime is read (GetFileInformationByHandleEx, 970FileBasicInfo); if that cannot be read, st_ctime_ns is used.""" 971if os .name != "nt" : 972return st .st_ctime_ns 973try : 974from ctypes import wintypes 975 976class _BasicInfo (ctypes .Structure ): 977_fields_ = [("CreationTime" ,ctypes .c_longlong ), ("LastAccessTime" ,ctypes .c_longlong ), ("LastWriteTime" ,ctypes .c_longlong ), 978 ("ChangeTime" ,ctypes .c_longlong ), ("FileAttributes" ,wintypes .DWORD )] 979k32 = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 980k32 .CreateFileW .restype = wintypes .HANDLE 981k32 .CreateFileW .argtypes = [wintypes .LPCWSTR ,wintypes .DWORD ,wintypes .DWORD ,ctypes .c_void_p ,wintypes .DWORD ,wintypes .DWORD , 982wintypes .HANDLE ] 983k32 .GetFileInformationByHandleEx .argtypes = [wintypes .HANDLE ,ctypes .c_int ,ctypes .c_void_p ,wintypes .DWORD ] 984k32 .GetFileInformationByHandleEx .restype = wintypes .BOOL 985k32 .CloseHandle .argtypes = [wintypes .HANDLE ] 986# FILE_READ_ATTRIBUTES, share read / write / delete, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS (a folder opens too) 987h = k32 .CreateFileW (str (path ),0x80 ,0x7 ,None ,3 ,0x02000000 ,None ) 988if h is None or h == ctypes .c_void_p (- 1 ).value : 989return st .st_ctime_ns 990try : 991info = _BasicInfo () 992if not k32 .GetFileInformationByHandleEx (h ,0 ,ctypes .byref (info ),ctypes .sizeof (info )):# 0 = FileBasicInfo 993return st .st_ctime_ns 994return int (info .ChangeTime )* 100 # 100 ns steps since 1601; only compared, never shown 995finally : 996k32 .CloseHandle (h ) 997except (OSError ,AttributeError ,ValueError ): 998return st .st_ctime_ns 999 1000 1001def _alt_reader_mark (path :Path )-> Path | None : 1002"""The mark that remembers the SHA-256 of an alternative picture reader (accepted_alt_reader). Its own key: the real path, size, modification 1003time AND change time (_change_time_ns), so a file rewritten in place with its size and modification time kept is hashed again. Only this 1004mark has the change time in its key: every other kept mark (_kept_mark, a 110 GB Engram's too) keeps its key and stays valid.""" 1005try : 1006real = path .resolve () 1007st = real .stat () 1008key = f"alt-reader| { real } | { st . st_size } | { st . st_mtime_ns } | { _change_time_ns ( real , st ) } " 1009except OSError : 1010return None 1011return ROOT / "marks" / (hashlib .sha1 (key .encode ("utf-8" ,"replace" )).hexdigest ()[:24 ]+ ".done" ) 1012 1013 1014_OWN_DIRS :list = []# --gguf-dir: folders of the person's own model files (a Hugging Face cache, a share) 1015 1016 1017def own_files_in (folder )-> None : 1018"""Strata writes nothing beside the person's own model files (lane NET item 5): their finish marks are kept in marks/ (_kept_mark).""" 1019try : 1020_OWN_DIRS .append (Path (folder ).expanduser ().resolve ()) 1021except OSError : 1022_OWN_DIRS .append (Path (folder ).expanduser ()) 1023 1024 1025def _is_own_file (path :Path )-> bool : 1026if not _OWN_DIRS : 1027return False 1028try : 1029parent = Path (path ).expanduser ().absolute ().parent .resolve () 1030except OSError : 1031return False 1032return any (parent == d for d in _OWN_DIRS ) 1033 1034 1035def mark_text (path :Path )-> str | None : 1036"""The text of the finish mark of `path` (beside it, else the kept one), or None when it has none.""" 1037for m in (path .with_name (path .name + ".done" ),_kept_mark (path )): 1038try : 1039if m is not None and m .exists (): 1040return m .read_text (encoding = "utf-8" ,errors = "replace" ) 1041except OSError : 1042pass 1043return None 1044 1045 1046def done (path :Path )-> bool : 1047"""A step's finish mark: <path>.done exists (written only after the step completed).""" 1048return mark_text (path )is not None 1049 1050 1051def mark (path :Path ,text = "" ): 1052"""Write the finish mark. A folder that cannot be written (--gguf-dir on a read-only share, #570, a read-only model disk) keeps the mark 1053in Strata's own folder instead (marks/), so a 110 GB Engram is hashed once, not on every launch; only when that cannot be written either 1054does setup say so and go on (the step is repeated on the next run), it does not stop.""" 1055text = text or time .strftime ("%Y-%m-%d %H:%M" ) 1056beside :BaseException | str = "a folder of the person's own model files" 1057if not _is_own_file (path ): 1058try : 1059path .with_name (path .name + ".done" ).write_text (text ,encoding = "utf-8" ) 1060return 1061except OSError as e : 1062beside = e 1063kept = _kept_mark (path ) 1064try : 1065if kept is not None : 1066kept .parent .mkdir (parents = True ,exist_ok = True ) 1067kept .write_text (text ,encoding = "utf-8" ) 1068return 1069except OSError : 1070pass 1071warn (f"the finish mark of { path . name } cannot be written ( { beside } ): the next run does this step again" ) 1072 1073 1074# ------------------------------------------------------------------------------------------------ the PC 1075def _memory_status (): 1076"""Windows' GlobalMemoryStatusEx: RAM, and the commit limit (ullTotalPageFile = RAM + page file).""" 1077class MS (ctypes .Structure ): 1078_fields_ = [("dwLength" ,ctypes .c_ulong ), ("dwMemoryLoad" ,ctypes .c_ulong ), 1079 ("ullTotalPhys" ,ctypes .c_ulonglong ), ("ullAvailPhys" ,ctypes .c_ulonglong ), 1080 ("ullTotalPageFile" ,ctypes .c_ulonglong ), ("ullAvailPageFile" ,ctypes .c_ulonglong ), 1081 ("ullTotalVirtual" ,ctypes .c_ulonglong ), ("ullAvailVirtual" ,ctypes .c_ulonglong ), 1082 ("ullAvailExtendedVirtual" ,ctypes .c_ulonglong )] 1083m = MS () 1084m .dwLength = ctypes .sizeof (MS ) 1085ctypes .windll .kernel32 .GlobalMemoryStatusEx (ctypes .byref (m )) 1086return m 1087 1088 1089def ram_gb (): 1090if WIN : 1091return _memory_status ().ullTotalPhys / 2 ** 30 1092if sys .platform == "darwin" : 1093try : 1094value = subprocess .run (["sysctl" ,"-n" ,"hw.memsize" ],capture_output = True , 1095text = True ,errors = "replace" ,timeout = 3 ,check = True ).stdout .strip () 1096return int (value )/ 2 ** 30 1097except (OSError ,ValueError ,subprocess .CalledProcessError ,subprocess .TimeoutExpired ): 1098return 0.0 1099total = 0.0 1100try : 1101with open ("/proc/meminfo" )as stream : 1102for line in stream : 1103if line .startswith ("MemTotal" ): 1104total = int (line .split ()[1 ])* 1024 / 2 ** 30 1105break 1106except (OSError ,ValueError ): 1107pass 1108if total <= 0.0 : 1109return 0.0 1110# In a container /proc/meminfo is the host's: the container's own limit is the RAM the engine gets. 1111limit = _cgroup_memory_limit () 1112if limit is not None and limit / 2 ** 30 < total : 1113return limit / 2 ** 30 1114return total 1115 1116 1117def _cgroup_memory_limit (self_cgroup = "/proc/self/cgroup" ,root = "/sys/fs/cgroup" ): 1118"""The smallest memory limit (bytes) on this process's cgroup and its ancestors, as the engine's memory guard reads 1119it (strata_control/cgroup_memory.py). None when no level sets a limit or the files cannot be read.""" 1120from strata_control import cgroup_memory 1121return cgroup_memory .memory_limit (self_cgroup ,root ) 1122 1123 1124_MM_KEY = r"SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" 1125 1126 1127def _mm_multi_sz (name ): 1128"""A REG_MULTI_SZ value of Memory Management, None when it cannot be read. PagingFiles is what the Virtual memory 1129dialog set; ExistingPageFiles is where the page files are now.""" 1130try : 1131import winreg 1132with winreg .OpenKey (winreg .HKEY_LOCAL_MACHINE ,_MM_KEY )as k : 1133v ,_t = winreg .QueryValueEx (k ,name ) 1134except (ImportError ,OSError ): 1135return None 1136return [x for x in v if x ]if isinstance (v ,list )else None 1137 1138 1139def parse_paging_file (line :str ): 1140"""One PagingFiles entry ("C:\\pagefile.sys 16000 64000", "C:\\pagefile.sys 0 0", "?:\\pagefile.sys"): (drive, 1141initial MB, maximum MB), both -1 when Windows manages the size and the drive '?' when it manages every drive; 1142None for anything else.""" 1143s = line .strip () 1144if len (s )< 2 or s [1 ]!= ":" : 1145return None 1146parts = s .split () 1147try : 1148initial ,maximum = (int (parts [1 ]),int (parts [2 ]))if len (parts )>= 3 else (- 1 ,- 1 ) 1149except ValueError : 1150initial ,maximum = - 1 ,- 1 1151if maximum <= 0 : 1152initial ,maximum = - 1 ,- 1 1153return s [0 ].upper (),initial ,maximum 1154 1155 1156PAGE_FILE_FIXED_MB = 65536 # the advice: a fixed size (initial = maximum) of 64 GB, the size #60's PC started with 1157 1158 1159def _drive_mb (drive :str ): 1160"""(free MB, the page file's size now in MB) of a drive, None when it cannot be read. The page file is locked: 1161its size comes from the directory entry.""" 1162root = f" { drive } :\\" 1163try : 1164du = shutil .disk_usage (root ) 1165except OSError : 1166return None 1167current = 0 1168try : 1169with os .scandir (root )as it : 1170for e in it : 1171if e .name .lower ()== "pagefile.sys" : 1172current = e .stat (follow_symlinks = False ).st_size 1173break 1174except OSError : 1175pass 1176return du .free / 2 ** 20 ,current / 2 ** 20 1177 1178 1179def page_file_setting (): 1180"""The page files Windows is set to use (PagingFiles, what the Virtual memory dialog writes): [(drive, initial MB, 1181maximum MB, MB now, the drive's free MB)], the sizes -1 for a system-managed file; "?:" (every drive automatic) is 1182the drive ExistingPageFiles names. None off Windows or when the setting cannot be read.""" 1183if not WIN : 1184return None 1185lines = _mm_multi_sz ("PagingFiles" ) 1186if lines is None : 1187return None 1188auto = []# "?:\pagefile.sys": where Windows keeps it now, else C: 1189for s in _mm_multi_sz ("ExistingPageFiles" )or []: 1190i = s .find (":" ) 1191if i > 0 : 1192auto .append (s [i - 1 ].upper ()) 1193auto = auto or [(os .environ .get ("SystemDrive" )or "C:" )[0 ].upper ()] 1194files = [] 1195for line in lines : 1196e = parse_paging_file (line ) 1197if e is None : 1198continue 1199drive ,initial ,maximum = e 1200for d in (auto if drive == "?" else [drive ]): 1201free ,now = _drive_mb (d )or (0.0 ,0.0 ) 1202files .append ((d ,initial ,maximum ,now ,free )) 1203return files 1204 1205 1206def page_file_grows (files )-> bool : 1207"""Whether Windows grows one of these page files on demand: system-managed, or an initial size below the maximum.""" 1208return any (maximum <= 0 or initial < maximum for _d ,initial ,maximum ,_now ,_free in files or []) 1209 1210 1211def page_file_gb (): 1212"""The page files' size (GB) that is there for sure on Windows, None elsewhere. The graphics card's memory needs 1213room there too: under Windows' driver model every allocation on the card is also charged to the commit (RAM + page 1214file), so with the page file off or tiny the engine cannot use the free VRAM (issue #60). What counts is the size 1215the files have now (the commit limit minus RAM), or a file's configured initial size when that is larger (within 1216its drive's free space) - never what a file may grow to: a page file Windows grows on demand may not grow in time 1217while the card's memory is charged (#60: "System managed" and 4096-32768 MB still failed, a fixed 64 GB worked).""" 1218if not WIN : 1219return None 1220m = _memory_status () 1221mb = max (0.0 , (m .ullTotalPageFile - m .ullTotalPhys )/ 2 ** 20 ) 1222files = page_file_setting () 1223if files : 1224mb = max (mb ,sum (max (now ,min (max (initial ,0 ),now + free ))for _d ,initial ,_m ,now ,free in files )) 1225return mb / 1024 1226 1227 1228def page_file_advice (pf :float ,files )-> str : 1229"""Step 1's warning for a page file below 4 GB (issue #60): a fixed size, and why when the setting (`files`, 1230page_file_setting) has Windows grow it on demand.""" 1231grows = ("It is set to grow on demand (\"System managed\" or an initial size below the maximum), and a growing " 1232"page file may not grow in time for the card's memory (#60: \"System managed\" and 4096-32768 MB still " 1233"failed, a fixed 64 GB worked). " )if page_file_grows (files )else "" 1234return (f"Windows' page file is { pf :.1f } GB: the graphics card's memory needs room there too (issue #60), so the " 1235f"model may not start or may use less VRAM. { grows } Set a fixed size: System > About > Advanced system " 1236"settings > Performance > Advanced > Virtual memory > Change, untick \"Automatically manage\", Custom size " 1237f"with initial and maximum size { PAGE_FILE_FIXED_MB } MB, Set, then restart Windows" ) 1238 1239 1240def cpu_cores (): 1241"""#642: (performance cores, efficiency cores) of a hybrid CPU (Intel 12th gen+, AMD Zen 5 + Zen 5c), counted 1242as the engine's pool counts them (detect_cpu_topology: physical cores, by Windows' EfficiencyClass or Linux's 1243cpu_capacity); None on a CPU whose cores are all alike, or when the OS does not say.""" 1244classes = []# one entry per physical core: its efficiency/capacity class 1245try : 1246if WIN : 1247k32 = ctypes .windll .kernel32 1248n = ctypes .c_ulong (0 ) 1249k32 .GetLogicalProcessorInformationEx (0 ,None ,ctypes .byref (n ))# RelationProcessorCore: the size 1250if not n .value : 1251return None 1252buf = ctypes .create_string_buffer (n .value ) 1253if not k32 .GetLogicalProcessorInformationEx (0 ,buf ,ctypes .byref (n )): 1254return None 1255raw ,at = buf .raw [:n .value ],0 1256while at + 10 <= len (raw ):# SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX: Relationship, Size, then 1257rel ,size = struct .unpack_from ("<II" ,raw ,at )# PROCESSOR_RELATIONSHIP (Flags, 1258if size <= 0 :# EfficiencyClass, ...) 1259break 1260if rel == 0 : 1261classes .append (raw [at + 9 ]) 1262at += size 1263else : 1264classes = linux_core_classes () 1265if classes is None : 1266return None 1267except (OSError ,ValueError ,AttributeError ): 1268return None 1269if not classes or max (classes )== min (classes ): 1270return None 1271p = sum (1 for c in classes if c == max (classes )) 1272return p ,len (classes )- p 1273 1274 1275def linux_core_classes (sys_root :str = "/sys" ): 1276"""One class per physical core on Linux: 1 for a P-core, 0 for an E-core; None when the kernel does not say. 1277#798: Intel's hybrid PMU lists (cpu_core/cpus, cpu_atom/cpus) when they exist; else cpu_capacity, where an E-core is 1278one under 90% of the largest - Turbo Boost Max 3.0 gives the "favored" P-cores a slightly higher capacity (1024 1279against 1012), so "below the maximum" counted 2 of a Core Ultra 7 270K Plus's 8 P-cores.""" 1280pmu = linux_hybrid_pmu (sys_root + "/devices" ) 1281seen ,top = {},0 1282for cpu in sorted ((Path (sys_root )/ "devices" / "system" / "cpu" ).glob ("cpu[0-9]*" ),key = lambda p :int (p .name [3 :])): 1283cap = cpu / "cpu_capacity" 1284pkg ,core = cpu / "topology" / "physical_package_id" ,cpu / "topology" / "core_id" 1285if not cap .exists ()and pmu is None : 1286return None 1287key = (pkg .read_text (encoding = "utf-8" ).strip (),core .read_text (encoding = "utf-8" ).strip ()) \ 1288if pkg .exists ()and core .exists ()else cpu .name 1289num = int (cpu .name [3 :]) 1290capacity = int (cap .read_text (encoding = "utf-8" ).strip ())if cap .exists ()else 0 1291top = max (top ,capacity ) 1292if pmu is not None and num in pmu [1 ]: 1293seen .setdefault (key ,None )# a listed E-core (the atom list and, #3262, the LP-E list) 1294elif pmu is not None and num in pmu [0 ]: 1295seen .setdefault (key ,False )# a listed P-core 1296else :# in no list (or no lists at all): its capacity decides 1297seen .setdefault (key ,capacity ) 1298# an E-core is under 90% of the largest capacity; the PMU lists (None: E, False: P) decide where they say 1299return [0 if c is None else 1 if c is False else (1 if c * 10 >= top * 9 else 0 )for c in seen .values ()] 1300 1301 1302def cpulist (text :str )-> set : 1303"""A kernel cpulist ("0-7,16") as a set of CPU numbers.""" 1304out = set () 1305for part in text .strip ().split ("," ): 1306lo ,_ ,hi = part .strip ().partition ("-" ) 1307if lo .isdigit (): 1308out .update (range (int (lo ),int (hi or lo )+ 1 )) 1309return out 1310 1311 1312def linux_hybrid_pmu (root :str = "/sys/devices" ): 1313"""#798: (P-core CPUs, E-core CPUs) from Intel's hybrid PMU lists (cpu_core/cpus, cpu_atom/cpus), or None on a CPU 1314that has no such lists.""" 1315try : 1316p = cpulist ((Path (root )/ "cpu_core" / "cpus" ).read_text (encoding = "utf-8" )) 1317e = cpulist ((Path (root )/ "cpu_atom" / "cpus" ).read_text (encoding = "utf-8" )) 1318except OSError : 1319return None 1320try :# #3262: Meteor Lake / Arrow Lake-H list their LP-E cores in a third set, in neither of the two above 1321e |= cpulist ((Path (root )/ "cpu_lowpower" / "cpus" ).read_text (encoding = "utf-8" )) 1322except OSError : 1323pass 1324return (p ,e )if p and e else None 1325 1326 1327def hybrid_pool_workers (cores )-> int | None : 1328"""#642 (Hardin22's measurement): on a hybrid CPU the expert pool runs best on the P-cores but the host loop's one 1329plus HALF of the E-cores - an E-core runs the expert kernels ~2.2x slower and each layer waits for its slowest 1330part (i9-14900KF, 8P + 16E: 15 workers decoded 165 / 116 tok/s against 106 / 84 with all 23). Only on a CPU with 1331more E-cores than P-cores: on an i7-13700KF (8P + 8E, docs/AMD_HIP.md's gfx1030 report) all 15 workers decoded 133238-42 tok/s against 36 with 8, so there the engine's own count stays. None: the engine's own default (one worker 1333per physical core but the host's) stays.""" 1334if not cores : 1335return None 1336p ,e = cores 1337if e <= p : 1338return None 1339return max (1 ,p - 1 + e // 2 ) 1340 1341 1342def recommend_pool_workers (args :list )-> list : 1343"""`args` with setup's recommended `--pool-workers` for a hybrid CPU, unless they set one already (a calibration's 1344measured count, or the user's own). A recommendation: the config line can be edited or removed.""" 1345n = hybrid_pool_workers (cpu_cores ()) 1346if n is None or "--pool-workers" in args : 1347return args 1348n = min (n ,POOL_WORKERS_CAP )# setup never writes a big worker count (see plan_pool_workers) 1349p ,e = cpu_cores () 1350ok (f"hybrid CPU ( { p } performance + { e } efficiency cores): { n } CPU expert workers - the performance cores and half " 1351"of the efficiency cores (--pool-workers in the config; START-HERE --calibrate measures it on this PC)" ) 1352return [* args ,"--pool-workers" ,str (n )] 1353 1354 1355def linux_sockets (sys_root :str = "/sys" ): 1356"""(sockets, physical cores per socket) from the kernel's topology files, or None when they do not say.""" 1357cores = {} 1358for cpu in (Path (sys_root )/ "devices" / "system" / "cpu" ).glob ("cpu[0-9]*" ): 1359pkg ,core = cpu / "topology" / "physical_package_id" ,cpu / "topology" / "core_id" 1360try : 1361cores .setdefault (pkg .read_text (encoding = "utf-8" ).strip (),set ()).add (core .read_text (encoding = "utf-8" ).strip ()) 1362except OSError : 1363return None 1364return (len (cores ),min (len (c )for c in cores .values ()))if cores else None 1365 1366 1367def cpu_sockets (): 1368"""(sockets, physical cores per socket); None when unknown. Windows: the packages and cores that 1369GetLogicalProcessorInformationEx lists (RelationProcessorPackage 3, RelationProcessorCore 0).""" 1370try : 1371if not WIN : 1372return linux_sockets () 1373k32 = ctypes .windll .kernel32 1374counts = {} 1375for rel in (0 ,3 ): 1376n = ctypes .c_ulong (0 ) 1377k32 .GetLogicalProcessorInformationEx (rel ,None ,ctypes .byref (n )) 1378if not n .value : 1379return None 1380buf = ctypes .create_string_buffer (n .value ) 1381if not k32 .GetLogicalProcessorInformationEx (rel ,buf ,ctypes .byref (n )): 1382return None 1383raw ,at ,c = buf .raw [:n .value ],0 ,0 1384while at + 8 <= len (raw ): 1385size = struct .unpack_from ("<II" ,raw ,at )[1 ] 1386if size <= 0 : 1387break 1388c += 1 1389at += size 1390counts [rel ]= c 1391return (counts [3 ],counts [0 ]// counts [3 ])if counts [3 ]else None 1392except Exception : 1393return None 1394 1395 1396def two_socket_note (sockets )-> list [str ]: 1397"""Bench #674 #707 (2-socket Xeons: 17-18 workers beat 35 by ~20%): a tip to keep the expert pool on one socket's 1398cores, one fewer for the host loop. Nothing is written to the config.""" 1399if not sockets or sockets [0 ]< 2 or sockets [1 ]< 3 : 1400return [] 1401n = sockets [1 ]- 1 1402return [f"tip: this PC has { sockets [ 0 ] } CPU sockets of { sockets [ 1 ] } cores. Expert workers on the other socket have " 1403f"been measured slower than fewer, local ones (35 vs 17-18 on 2-socket Xeons): try --pool-workers { n } in " 1404"the config's args (START-HERE --calibrate measures it on this PC)" ] 1405 1406 1407# The engine's default count of CPU expert workers (include/strata/kernels/cpu/pool_plan.hpp, which tools/test_pool_plan.py 1408# keeps in step with these numbers). Setup writes no worker count on an ordinary CPU: the engine picks it, from the 1409# physical cores (not the SMT siblings), minus the host thread's core and a reserve on a big CPU, on the host thread's 1410# socket, under a cap. What setup does write (a hybrid CPU's count, the vision encoder's threads) is capped the same way. 1411POOL_WORKERS_CAP = 32 1412POOL_RESERVE_FROM = 16 1413POOL_RESERVE = 1 1414VISION_THREADS_CAP = 16 1415 1416 1417def plan_pool_workers (logical :int ,cores_per_package = None ,quota :float = 0.0 ,hybrid = None )-> int : 1418"""The engine's default pool worker count for a CPU of `logical` threads whose physical cores per socket are 1419`cores_per_package` (the host thread's socket first; None/empty: the layout is not known) and a container CPU 1420quota (0: none).""" 1421cores = list (cores_per_package or []) 1422if cores and sum (cores )> 0 : 1423local = cores [0 ] 1424else :# no layout: half the logical processors on a many-thread CPU 1425local = logical // 2 if logical >= 16 else logical 1426n = max (1 ,local - 1 )# the host thread has the first core 1427if n >= POOL_RESERVE_FROM : 1428n -= POOL_RESERVE 1429if hybrid and hybrid [0 ]> 0 and hybrid [1 ]> hybrid [0 ]:# (P-cores, E-cores): the P-cores but the host's + half the E-cores 1430n = min (n ,max (1 ,hybrid [0 ]- 1 + hybrid [1 ]// 2 )) 1431if quota > 0 : 1432n = min (n ,max (1 ,int (quota )- 1 )) 1433return max (1 ,min (n ,POOL_WORKERS_CAP )) 1434 1435 1436def cpu_core_layout (): 1437"""(logical threads, [physical cores per socket]); the cores list is empty when the OS does not say.""" 1438logical = os .cpu_count ()or 1 1439sockets = cpu_sockets () 1440return logical , ([sockets [1 ]]* sockets [0 ]if sockets else []) 1441 1442 1443def pool_workers_note (args ,layout = None )-> list [str ]: 1444"""A plain warning when the config's `--pool-workers` is above what this CPU uses well. Recommend, never force: the 1445count stays as it is and the engine runs with it.""" 1446if "--pool-workers" not in args : 1447return [] 1448try : 1449asked = int (args [args .index ("--pool-workers" )+ 1 ]) 1450except (IndexError ,ValueError ): 1451return [] 1452hybrid = cpu_cores ()if layout is None else None 1453logical ,cores = layout or cpu_core_layout () 1454rec = plan_pool_workers (logical ,cores ,hybrid = hybrid ) 1455if asked <= rec : 1456return [] 1457why = ("more than this PC has CPU threads" if asked + 1 > logical else 1458"more than its physical cores" if cores and asked + 1 > sum (cores )else 1459"more than the cores of one CPU socket" if len (cores )> 1 and asked + 1 > cores [0 ]else 1460"more than the memory bandwidth can feed" ) 1461return [f"the config asks for { asked } CPU expert workers, { why } : extra workers can make Strata slower. Recommended: " 1462f"--pool-workers { rec } (or remove the setting: the engine picks that by itself). It stays as you set it." ] 1463 1464 1465def vision_threads (logical :int | None = None )-> int : 1466"""The CPU vision encoder's threads: one per physical core as before (half the logical threads), at most 1467VISION_THREADS_CAP - a 256-thread server does not need 128 of them.""" 1468return max (1 ,min ((logical if logical is not None else (os .cpu_count ()or 8 ))// 2 ,VISION_THREADS_CAP )) 1469 1470 1471def cpu_info (): 1472"""(name, avx2, avx512): avx512 means everything Strata's fast AVX-512 kernels use (F, BW, VL, VNNI, VBMI), 1473the same test the engine makes (cpu_avx512_ok), not just AVX-512F.""" 1474name ,avx2 ,avx512 = sysinfo .processor ()or "unknown CPU" ,False ,False 1475if WIN : 1476pf = ctypes .windll .kernel32 .IsProcessorFeaturePresent 1477avx2 = bool (pf (40 ))or _cpuid_avx2 ()# PF_AVX2_INSTRUCTIONS_AVAILABLE, else the CPU itself (#159) 1478n = out (["powershell" ,"-NoProfile" ,"-Command" ,"(Get-CimInstance Win32_Processor).Name" ]).strip () 1479name = n or name 1480avx512 = bool (pf (41 ))and _cpuid_avx512_full () 1481else : 1482try : 1483txt = open ("/proc/cpuinfo" ).read () 1484mflags = re .search (r"^flags\s*:\s*(.*)$" ,txt ,re .M ) 1485if mflags is None : 1486# aarch64 lists Features, not the x86 flags line, and no "model name": lscpu names the cores (a DGX Spark: 1487# Cortex-X925 + Cortex-A725). No AVX of any kind; the arm64 engine needs none. 1488cores = re .findall (r"^\s*Model name:\s*(.+)$" ,out (["lscpu" ]),re .M ) 1489name = " + " .join (dict .fromkeys (c .strip ()for c in cores ))or (sysinfo .processor ()or "arm64 CPU" ) 1490return name ,False ,False 1491flags = set (mflags .group (1 ).split ()) 1492avx2 = "avx2" in flags 1493avx512 = {"avx512f" ,"avx512bw" ,"avx512vl" ,"avx512_vnni" ,"avx512vbmi" }<= flags 1494m = re .search (r"^model name\s*:\s*(.*)$" ,txt ,re .M ) 1495name = m .group (1 )if m else name 1496except OSError : 1497pass 1498return name ,avx2 ,avx512 1499 1500 1501def _cpuid_floor ()-> str : 1502"""Below AVX2 (Windows): "avx" when the CPU has AVX and the OS saves the YMM registers, "sse4.2" with SSE4.2 and 1503POPCNT, else "".""" 1504try : 1505regs = (ctypes .c_uint32 * 4 )() 1506_run_stub (bytes ([0x53 ,0x49 ,0x89 ,0xC8 ,0x89 ,0xD0 ,0x31 ,0xC9 ,0x0F ,0xA2 ,# push rbx; r8=rcx; eax=edx; ecx=0; cpuid 15070x41 ,0x89 ,0x00 ,0x41 ,0x89 ,0x58 ,0x04 ,0x41 ,0x89 ,0x48 ,0x08 ,# [r8]=eax, [r8+4]=ebx, [r8+8]=ecx 15080x41 ,0x89 ,0x50 ,0x0C ,0x5B ,0xC3 ]),# [r8+12]=edx; pop rbx 1509ctypes .addressof (regs ),1 ) 1510ecx1 = regs [2 ] 1511if (ecx1 >> 27 )& 1 and (ecx1 >> 28 )& 1 :# OSXSAVE, AVX 1512xcr0 = (ctypes .c_uint32 * 2 )() 1513_run_stub (bytes ([0x49 ,0x89 ,0xC8 ,0x31 ,0xC9 ,0x0F ,0x01 ,0xD0 ,# r8=rcx; ecx=0; xgetbv 15140x41 ,0x89 ,0x00 ,0x41 ,0x89 ,0x50 ,0x04 ,0xC3 ]),ctypes .addressof (xcr0 )) 1515if xcr0 [0 ]& 6 == 6 : 1516return "avx" 1517return "sse4.2" if (ecx1 >> 20 )& 1 and (ecx1 >> 23 )& 1 else "" 1518except Exception : 1519return "" 1520 1521 1522def is_arm64 ()-> bool : 1523"""An ARM64 CPU (DGX Spark / GB10, Grace): there is no AVX here, and no ready-made engine for it.""" 1524return sysinfo .machine ().lower ()in ("aarch64" ,"arm64" ) 1525 1526 1527def is_gb10 (g )-> bool : 1528"""A DGX Spark's GPU: the GB10 (compute capability 12.1), on arm64 Linux, with the CPU's memory as its own. The part the Spark settings 1529below were measured on (docs/DGX_SPARK_LINUX.md); any other unified-memory NVIDIA GPU gets the ordinary settings.""" 1530return isinstance (g ,dict )and bool (g .get ("uma" ))and str (g .get ("arch" ))== "121" and is_arm64 ()and sys .platform .startswith ("linux" ) 1531 1532 1533def cpu_floor (avx2 :bool )-> str : 1534"""The experimental older-CPU build this PC needs (#394 #595 #623): "" with AVX2 (the normal engine), "avx" (Sandy / 1535Ivy Bridge, AMD Bulldozer), "none" (SSE4.2 + POPCNT: Nehalem, Westmere), or "unsupported". STRATA_ISA_FLOOR=avx| 1536none asks for that build on any PC (testing it on a newer one).""" 1537forced = os .environ .get ("STRATA_ISA_FLOOR" ,"" ).strip ().lower () 1538if forced in ("avx" ,"none" ): 1539return forced 1540if is_arm64 (): 1541return "" 1542if avx2 : 1543return "" 1544if WIN : 1545f = _cpuid_floor () 1546else : 1547try : 1548txt = open ("/proc/cpuinfo" ).read () 1549flags = set (re .search (r"^flags\s*:\s*(.*)$" ,txt ,re .M ).group (1 ).split ()) 1550except (OSError ,AttributeError ): 1551flags = set () 1552f = "avx" if "avx" in flags else "sse4.2" if {"sse4_2" ,"popcnt" }<= flags else "" 1553return {"avx" :"avx" ,"sse4.2" :"none" }.get (f ,"unsupported" ) 1554 1555 1556def _cpuid_avx512_full ()-> bool : 1557"""Windows has no feature bit for VNNI / VBMI: ask the CPU (CPUID leaf 7) through a tiny machine-code stub.""" 1558try : 1559code = bytes ([0x53 ,0x49 ,0x89 ,0xC8 ,0xB8 ,0x07 ,0x00 ,0x00 ,0x00 ,0x31 ,0xC9 ,0x0F ,0xA2 ,# push rbx; r8=rcx; cpuid(7,0) 15600x41 ,0x89 ,0x18 ,0x41 ,0x89 ,0x48 ,0x04 ,0x5B ,0xC3 ])# [r8]=ebx,[r8+4]=ecx; pop rbx 1561k32 = ctypes .windll .kernel32 1562k32 .VirtualAlloc .restype = ctypes .c_void_p 1563buf = k32 .VirtualAlloc (None ,len (code ),0x3000 ,0x40 ) 1564if not buf : 1565return False 1566ctypes .memmove (buf ,code ,len (code )) 1567regs = (ctypes .c_uint32 * 2 )() 1568ctypes .CFUNCTYPE (None ,ctypes .c_void_p )(buf )(ctypes .addressof (regs )) 1569ebx ,ecx = regs [0 ],regs [1 ] 1570need_ebx = (1 << 16 )| (1 << 30 )| (1 << 31 )# F, BW, VL 1571need_ecx = (1 << 1 )| (1 << 11 )# VBMI, VNNI 1572return (ebx & need_ebx )== need_ebx and (ecx & need_ecx )== need_ecx 1573except Exception : 1574return False 1575 1576 1577def _run_stub (code :bytes ,* args )-> None : 1578"""Runs a few bytes of x64 machine code (Windows calling convention: the arguments in rcx, rdx).""" 1579k32 = ctypes .windll .kernel32 1580k32 .VirtualAlloc .restype = ctypes .c_void_p 1581k32 .VirtualFree .argtypes = (ctypes .c_void_p ,ctypes .c_size_t ,ctypes .c_uint32 ) 1582buf = k32 .VirtualAlloc (None ,len (code ),0x3000 ,0x40 ) 1583if not buf : 1584raise OSError ("VirtualAlloc failed" ) 1585try : 1586ctypes .memmove (buf ,code ,len (code )) 1587ctypes .CFUNCTYPE (None ,* [ctypes .c_void_p ]* len (args ))(buf )(* args ) 1588finally : 1589k32 .VirtualFree (buf ,0 ,0x8000 ) 1590 1591 1592def _cpuid_avx2 ()-> bool : 1593"""AVX2 asked from the CPU (CPUID leaf 7 EBX bit 5), with the OS saving the YMM registers (OSXSAVE + XCR0): 1594Windows' IsProcessorFeaturePresent(PF_AVX2) says no on some PCs whose CPU has it (a Ryzen 9 3950X, #159).""" 1595try : 1596def cpuid (leaf ): 1597regs = (ctypes .c_uint32 * 4 )() 1598_run_stub (bytes ([0x53 ,0x49 ,0x89 ,0xC8 ,0x89 ,0xD0 ,0x31 ,0xC9 ,0x0F ,0xA2 ,# push rbx; r8=rcx; eax=edx; ecx=0; cpuid 15990x41 ,0x89 ,0x00 ,0x41 ,0x89 ,0x58 ,0x04 ,0x41 ,0x89 ,0x48 ,0x08 ,# [r8]=eax, [r8+4]=ebx, [r8+8]=ecx 16000x41 ,0x89 ,0x50 ,0x0C ,0x5B ,0xC3 ]),# [r8+12]=edx; pop rbx 1601ctypes .addressof (regs ),leaf ) 1602return list (regs ) 1603if cpuid (0 )[0 ]< 7 : 1604return False 1605ecx1 = cpuid (1 )[2 ] 1606if not (ecx1 >> 27 )& 1 or not (ecx1 >> 28 )& 1 :# OSXSAVE, AVX 1607return False 1608xcr0 = (ctypes .c_uint32 * 2 )() 1609_run_stub (bytes ([0x49 ,0x89 ,0xC8 ,0x31 ,0xC9 ,0x0F ,0x01 ,0xD0 ,# r8=rcx; ecx=0; xgetbv 16100x41 ,0x89 ,0x00 ,0x41 ,0x89 ,0x50 ,0x04 ,0xC3 ]),ctypes .addressof (xcr0 )) 1611if xcr0 [0 ]& 6 != 6 :# the OS saves XMM and YMM 1612return False 1613return bool ((cpuid (7 )[1 ]>> 5 )& 1 ) 1614except Exception : 1615return False 1616 1617 1618def gpus (): 1619"""Every NVIDIA GPU, numbered as nvidia-smi numbers them (by PCI bus, the order the engine is told to use).""" 1620s = out (["nvidia-smi" ,"--query-gpu=index,name,memory.total,compute_cap,driver_version" , 1621"--format=csv,noheader,nounits" ]) 1622found = [] 1623for line in s .strip ().splitlines (): 1624try : 1625idx ,name ,mem ,cc ,drv = [x .strip ()for x in line .split ("," )] 1626try : 1627mem_gb = float (mem )/ 1024.0 # nvidia-smi nounits: MiB 1628except ValueError : 1629if not is_arm64 (): 1630raise # as before on x86: a card whose memory nvidia-smi does not report is not listed 1631# a DGX Spark (GB10): one memory for the CPU and the GPU, and nvidia-smi gives memory.total as [N/A]. Counted as 1632# Strix Halo's is (amd_apply_uma): the GPU may use all of the RAM but the OS's share, and none of it is extra room 1633# beside the RAM (dedicated_gb 0), so the low-RAM rules do not count it twice 1634shared = max (0.0 ,ram_gb ()- UMA_OS_LEFT_GB ) 1635found .append ({"index" :int (idx ),"name" :name ,"vram_gb" :shared ,"arch" :cc .replace ("." ,"" ), 1636"driver" :drv ,"uma" :True ,"dedicated_gb" :0.0 ,"shared_gb" :shared }) 1637continue 1638found .append ({"index" :int (idx ),"name" :name ,"vram_gb" :mem_gb ,"arch" :cc .replace ("." ,"" ), 1639"driver" :drv }) 1640except ValueError : 1641continue 1642return found 1643 1644 1645def gpu_drives_display (g )-> bool : 1646"""#779: True when nvidia-smi says this card has a display attached (display_active Enabled): its desktop needs 1647VRAM too, and a full expert cache beside it has crashed laptops.""" 1648text = out (["nvidia-smi" ,"-i" ,str (g .get ("index" ,0 )),"--query-gpu=display_active" ,"--format=csv,noheader" ]) 1649return text .strip ().lower ()== "enabled" 1650 1651 1652def gpu_compute_mode (index :int )-> str : 1653"""#1445: nvidia-smi's compute mode for this card ("Default", "Exclusive_Process", "Prohibited", ...); "" when it 1654does not say.""" 1655return out (["nvidia-smi" ,"-i" ,str (index ),"--query-gpu=compute_mode" ,"--format=csv,noheader" ]).strip () 1656 1657 1658def compute_mode_warning (index :int ,mode :str )-> str | None : 1659"""#1445: the warning for a card that is not in the Default compute mode, or None. In Exclusive_Process only one 1660process may hold a CUDA context, so the engine, the vision encoder and the tuning run cannot share the card 1661("CUDA-capable device(s) is/are busy or unavailable"); Prohibited allows none. A warning only: it is the 1662administrator's setting, Strata never changes it.""" 1663if not mode or mode .lower ()== "default" or mode .lower ().startswith ("n/a" )or mode .lower ().startswith ("[n/a" ): 1664return None 1665return (f"GPU { index } is in the compute mode { mode } , not Default: a second process cannot use the card while " 1666"the first holds it, so the vision encoder or the tuning run can fail with \"CUDA-capable device(s) is/are " 1667f"busy or unavailable\". If it does, set it back with: sudo nvidia-smi -i { index } -c DEFAULT" ) 1668 1669 1670def pcie_link (index :int )-> dict | None : 1671"""The NVIDIA card's PCIe link: {"gen": the generation card and board both run (an idle card drops to a lower 1672one, so the current generation is not asked), "gpu_gen", "host_gen", "width", "max_width"}; None when nvidia-smi 1673does not say.""" 1674s = out (["nvidia-smi" ,"-i" ,str (index ),"--query-gpu=pcie.link.gen.max,pcie.link.gen.gpumax,pcie.link.gen.hostmax," 1675"pcie.link.width.current,pcie.link.width.max" ,"--format=csv,noheader,nounits" ]) 1676try : 1677gen ,gpu_gen ,host_gen ,width ,max_width = (int (x .strip ())for x in s .strip ().splitlines ()[0 ].split ("," )) 1678except (ValueError ,IndexError ): 1679return None 1680return {"gen" :gen ,"gpu_gen" :gpu_gen ,"host_gen" :host_gen ,"width" :width ,"max_width" :max_width } 1681 1682 1683PCIE_GBPS = {1 :0.25 ,2 :0.5 ,3 :0.985 ,4 :1.97 ,5 :3.94 }# GB/s per lane, each direction 1684 1685 1686def pcie_lines (link :dict )-> tuple [str ,str | None ]: 1687"""(the ok line, a warning or None) for step 1. The copy rate the engine measures is about 75% of the link's.""" 1688lim = [] 1689if link ["gpu_gen" ]> link ["gen" ]: 1690lim .append (f"the card supports { link [ 'gpu_gen' ] } .0, the board { link [ 'host_gen' ] } .0" ) 1691line = f"PCIe: { link [ 'gen' ] } .0 x { link [ 'width' ] } " + (f" ( { '; ' . join ( lim ) } )" if lim else "" ) 1692rate = PCIE_GBPS .get (link ["gen" ],0 )* link ["width" ] 1693if 0 < rate < 12 : 1694line += (f" - up to ~ { rate :.0f } GB/s to the GPU: long prompts are read slower than on a PCIe 4.0 x16 PC (their " 1695"experts are copied over it); the engine measures the link at start for the output speed" ) 1696warn_line = None 1697if link ["width" ]< link ["max_width" ]: 1698# (#912) the width is read now, and some cards and laptops narrow the link while idle: a hint, not a verdict 1699warn_line = (f"the GPU's PCIe link reads { link [ 'width' ] } of its { link [ 'max_width' ] } lanes right now (some cards " 1700"narrow it when idle); if it stays narrow under load: is it in the right slot (the one wired " 1701"x16), fully seated, and not sharing lanes with an M.2 drive? (the BIOS can say)" ) 1702return line ,warn_line 1703 1704 1705GPU_PICK = None # --gpu N (issue #51); None: the card with the most VRAM 1706SPLIT_MIN_VRAM_GB = 8 # a card sharing a model holds the dense weights and its own 1707# prompt buffers too (docs/MULTI_GPU.md) 1708SPLIT_PROMPT_VRAM_GB = 12 # #448: a split stage lends a prompt chunk's buffers from its 1709# own cache; below this one cannot fund a 4096-token chunk 1710# (a 10 GB RTX 3080 beside a 32 GB card: 512 tokens, prompts 1711# 6.2x slower), while the big card alone could 1712 1713 1714def cc (g )-> str : 1715return f" { g [ 'arch' ][: - 1 ] } . { g [ 'arch' ][ - 1 ] } " 1716 1717 1718OLD_GPUS = None # why Pascal / Volta cards are admitted in this run (old_gpus_opt_in), None: they are not 1719 1720 1721def experimental_sm60 ()-> bool : 1722"""#295: STRATA_EXPERIMENTAL_SM60=1 admits Pascal (6.x) and Volta (7.0) cards, run by the experimental CUDA 12 1723engine (-DSTRATA_EXPERIMENTAL_SM60=ON). So does naming such a card (--gpu N / --gpus), --cuda 12, or a PC that 1724has no newer card (old_gpus_opt_in).""" 1725return os .environ .get ("STRATA_EXPERIMENTAL_SM60" ,"" ).strip ()== "1" or OLD_GPUS is not None 1726 1727 1728def sm60_card (arch )-> bool : 1729return 60 <= int (arch )<= 70 1730 1731 1732def maxwell_card (arch )-> bool : 1733"""#3218: Maxwell (5.x). No ready-made engine holds code for it; it is a source build (docs/OLDER_GPUS.md).""" 1734return 50 <= int (arch )< 60 1735 1736 1737def maxwell_note (found )-> str : 1738"""#3218: what to tell a PC whose only NVIDIA cards are Maxwell: setup cannot install an engine for it, and a 1739source build exists. Empty when there is no Maxwell card. A warning with the way forward, never a switch: setup 1740does not route a Maxwell card to an engine that holds no code for it.""" 1741cards = [g for g in found if maxwell_card (g ["arch" ])] 1742if not cards : 1743return "" 1744names = ", " .join (f"GPU { g [ 'index' ] } ( { g [ 'name' ] } )" for g in cards ) 1745return (f" { names } : Maxwell (compute capability { cc ( cards [ 0 ]) } ). No ready-made Strata engine holds code for it, so " 1746"setup cannot install one. One reporter built the engine from source for two Quadro M6000 with a CUDA 12.x " 1747"toolkit (cmake -B build -G Ninja -DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52) and saw about " 1748"22 tokens a second with a 1-bit Qwen3.8-Flash-Next; nobody has checked the answer text yet. Steps and " 1749"caveats: docs/OLDER_GPUS.md. A card of the RTX 20 series or newer runs the ready-made engine" ) 1750 1751 1752def old_gpus_opt_in (found ,named = (),cuda = None ,other = False ): 1753"""Why this run may use Pascal / Volta cards (the experimental CUDA 12 engine), or None. The cards are an opt-in: 1754the user named one (`named`: --gpu / --gpus), asked for --cuda 12, set STRATA_EXPERIMENTAL_SM60=1, or the PC has 1755no card the ready-made engine runs on and no supported AMD card (`other`; it used to stop there). A PC with a 1756newer card keeps recommending it.""" 1757old = [g for g in found if sm60_card (g ["arch" ])] 1758if not old : 1759return None 1760if os .environ .get ("STRATA_EXPERIMENTAL_SM60" ,"" ).strip ()== "1" : 1761return "STRATA_EXPERIMENTAL_SM60=1" 1762if str (cuda )== "12" : 1763return "--cuda 12" 1764picked = [g for g in old if g ["index" ]in set (named )] 1765if picked : 1766return "you chose " + ", " .join (f"GPU { g [ 'index' ] } ( { g [ 'name' ] } )" for g in picked ) 1767if not other and not any (int (g ["arch" ])>= CUDA13_MIN_ARCH for g in found ): 1768return "it is the only kind of NVIDIA GPU in this PC" 1769return None 1770 1771 1772def named_gpus (gpu ,gpus )-> list : 1773"""The card numbers --gpu / --gpus name (an unreadable value: none; parse_gpus says what is wrong later).""" 1774try : 1775if gpus and str (gpus ).strip ().lower ()!= "all" : 1776return [int (x )for x in str (gpus ).split ("," )if x .strip ()] 1777return [int (gpu )]if gpu is not None else [] 1778except ValueError : 1779return [] 1780 1781 1782_CUDA12_FLOORS :dict = {} 1783 1784 1785def cuda12_min_driver (feed :bool = False )-> tuple [int ,str ,str ]: 1786"""(driver major, the package's figure such as "576.02", where it came from): the oldest NVIDIA driver the CUDA 12 engine runs on, read 1787from the engine package (installed, else - with `feed` - the signed feed, else the figure the packages carry) and not from a constant 1788of setup's own. Remembered for the run. Only a setup run asks the feed (a few seconds at most, once); a plain call reads the disk.""" 1789got = _CUDA12_FLOORS .get (True )or _CUDA12_FLOORS .get (feed ) 1790if got : 1791return got 1792from strata_control import driver_floor 1793roots = [engine_component .components_dir (),home ()/ "engine-feed" ] 1794source = None 1795if feed and not acquisition .is_forbidden (): 1796try : 1797from strata_cli import update_cmd 1798source = update_cmd ._feed_source (argparse .Namespace (feed = None ),home ()) 1799except Exception :# noqa: BLE001 - no feed address: the built-in figure 1800source = None 1801try : 1802from strata_control import targets 1803platform_name = targets .host_platform () 1804except Exception :# noqa: BLE001 1805platform_name = "" 1806figure ,where = driver_floor .cuda12_floor (platform_name ,roots = roots ,feed_source = source ) 1807_CUDA12_FLOORS [feed ]= got = (driver_floor .major (figure ),figure ,where ) 1808return got 1809 1810 1811def cuda_choice (archs ,cuda = None ,driver = None ): 1812"""The CUDA toolkit of one model's engine: (12 or 13, why). 13 (the ready-made engine) unless a card is older 1813than CUDA 13 supports (Pascal / Volta: CUDA 13 cannot compile for them) - one engine runs per model, so its oldest 1814card decides. `cuda` (--cuda 12|13) overrides it; setup recommends, it does not refuse (the caller warns).""" 1815archs = sorted ({int (x )for x in archs }) 1816old = [a for a in archs if a < CUDA13_MIN_ARCH ] 1817if str (cuda )== "13" : 1818return 13 , ("--cuda 13 (as you chose)" + (f"; CUDA 13 has no code for sm_ { old [ 0 ] } : the engine will not run " 1819"on that card" if old else "" )) 1820if str (cuda )== "12" : 1821return 12 ,"--cuda 12 (as you chose" + ("; RTX 50 (sm_120) engines built with CUDA 12.8 crashed on long " 1822"prompts, #220" if archs and archs [- 1 ]>= 120 else "" )+ ")" 1823if old : 1824return 12 , (f"sm_ { old [ 0 ] } is older than CUDA 13 supports (it dropped Pascal and Volta): this model runs the " 1825"experimental CUDA 12 engine" ) 1826if driver and CUDA12_COMPAT_DRIVER <= int (driver )< MIN_DRIVER :# #3843: a driver too old for CUDA 13 still runs the CUDA 12 engine 1827return 12 , (f"the NVIDIA driver { driver } is older than CUDA 13 needs ( { MIN_DRIVER } ): this model runs the CUDA 12 engine " 1828f"(a newer driver from https://www.nvidia.com/drivers gives the CUDA 13 engine)" ) 1829return 13 ,None 1830 1831 1832def cuda12_driver_warning (driver )-> str | None : 1833"""A plain warning when the NVIDIA driver is older than the ready-made CUDA 12 engine package needs, or None. The number is the package's 1834own (cuda12_min_driver), the same one `strata update` enforces, so setup no longer says "works" where the update says "no engine" (#4247 #4188). 1835Recommend, never force: setup goes on (an engine compiled here, or one the person brings, may still run).""" 1836floor ,figure ,where = cuda12_min_driver () 1837if not driver or int (driver )>= floor : 1838return None 1839return (f"the NVIDIA driver { driver } is older than the ready-made CUDA 12 engine package needs ( { figure } , { where } ): `strata update` will not " 1840"install that package on this PC. Update the driver from https://www.nvidia.com/drivers" 1841+ ("; setup compiles the engine here instead, which can run on an older driver" if not WIN else "" )) 1842 1843 1844def engine_dir (toolkit = 13 )-> Path : 1845"""The folder of the engine a model runs: engine/ (CUDA 13, or HIP), engine-cuda12/ (the experimental one).""" 1846return ROOT / (ENGINE12_DIR if int (toolkit )== 12 else "engine" ) 1847 1848 1849def config_toolkit (cfg :dict )-> int : 1850"""12 when a model config runs the experimental CUDA 12 engine (its exe is in engine-cuda12/), else 13.""" 1851return 12 if cfg .get ("cuda" )== 12 or Path (str (cfg .get ("exe" ,"" ))).parent .name == ENGINE12_DIR else 13 1852 1853 1854def gpu_problem (g ,together = False ): 1855"""Why Strata cannot use this card, in plain words (None: it can).""" 1856if int (g ["arch" ])< 75 and not (sm60_card (g ["arch" ])and experimental_sm60 ()): 1857return (f"not supported - older than the RTX 20 series (compute capability { cc ( g ) } ; Strata needs 7.5 or " 1858"newer" + ("; experimental: choose it with --gpu " + str (g ["index" ])+ " (the CUDA 12 engine, " 1859"docs/OLDER_GPUS.md)" if sm60_card (g ["arch" ])else 1860"; Maxwell only runs from a source build, docs/OLDER_GPUS.md" if maxwell_card (g ["arch" ])else "" )+ ")" ) 1861if together and g ["vram_gb" ]< SPLIT_MIN_VRAM_GB - 0.5 : 1862return (f"not supported together with other GPUs - { g [ 'vram_gb' ]:.0f } GB of VRAM (a card sharing the model " 1863f"needs { SPLIT_MIN_VRAM_GB } GB or more)" ) 1864return None 1865 1866 1867def gpu_rank (g ): 1868"""The order cards share a model in: the newest generation first (it gets the first layers and most of the 1869work), then the most VRAM.""" 1870return (- int (g ["arch" ]),- round (g ["vram_gb" ]),g ["index" ]) 1871 1872 1873def gpu_name (g )-> str : 1874return f"GPU { g [ 'index' ] } ( { g [ 'name' ] } , { g [ 'vram_gb' ]:.0f } GB)" 1875 1876 1877def gpu_table (found )-> None : 1878say (" Your NVIDIA GPUs:" ) 1879for g in found : 1880p = gpu_problem (g ) 1881say (f" GPU { g [ 'index' ] } : { g [ 'name' ] } , { g [ 'vram_gb' ]:.0f } GB VRAM - " + ("can be used" if p is None else p )) 1882 1883 1884def together_ok (found )-> list : 1885"""The cards that can share one model, in the order they would (empty if fewer than two).""" 1886ok_ = sorted ([g for g in found if gpu_problem (g ,together = True )is None ],key = gpu_rank ) 1887return ok_ if len (ok_ )>= 2 else [] 1888 1889 1890def split_short (cards )-> list : 1891"""#448: the later cards of a split that would cap its prompt chunk below what the first card alone reads (a card 1892under SPLIT_PROMPT_VRAM_GB beside one that has it). Empty: the split is recommended as before.""" 1893if len (cards )< 2 or cards [0 ]["vram_gb" ]< SPLIT_PROMPT_VRAM_GB - 0.5 : 1894return [] 1895return [g for g in cards [1 :]if g ["vram_gb" ]< SPLIT_PROMPT_VRAM_GB - 0.5 ] 1896 1897 1898def split_short_note (g )-> str : 1899return (f"GPU { g [ 'index' ] } ( { g [ 'name' ] } , { g [ 'vram_gb' ]:.0f } GB) is too small to lend a split its prompt buffers: " 1900"it would cap prompt reading at 512-2048-token chunks, several times slower than the first card alone " 1901"(#448). It can serve as a helper expert cache instead (docs/SECOND_GPU.md)" ) 1902 1903 1904def parse_gpus (text ,found )-> list : 1905"""--gpus / --gpu with several: "0,2" or "all" (every card that can share the model).""" 1906if str (text ).strip ().lower ()== "all" : 1907sel = [g ["index" ]for g in together_ok (found )] 1908if not sel : 1909gpu_table (found ) 1910fail ("--gpus all: this PC does not have two GPUs Strata can use together" ) 1911return sel 1912try : 1913sel = [int (x )for x in str (text ).split ("," )if x .strip ()] 1914except ValueError : 1915fail (f"--gpus takes GPU numbers as nvidia-smi numbers them, e.g. --gpus 0,2 (or --gpus all), not { text !r } " ) 1916if len (sel )< 2 or len (set (sel ))!= len (sel ): 1917fail ("--gpus takes two or more different GPUs, e.g. --gpus 0,2 (one GPU: --gpu 0)" ) 1918return sel 1919 1920 1921def check_gpus (sel ,found ,what = "" ,yes = False ,named = False )-> None : 1922"""Stops with a plain message when a chosen card is missing or cannot be used, and says what can. named: the user 1923named these cards (--gpus 0,1, or a config that has them): a card that is only short of VRAM for sharing the model 1924is then a risk to confirm, not a stop (the owner's rule; --yes with the named cards is the consent).""" 1925together = len (sel )> 1 1926for i in sel : 1927g = next ((x for x in found if x ["index" ]== i ),None ) 1928p = "not found on this PC" if g is None else gpu_problem (g ,together ) 1929if p is None : 1930continue 1931if named and g is not None and gpu_problem (g )is None :# it runs Strata; only its VRAM is small 1932confirm_risk (f"GPU { i } ( { g [ 'name' ] } ) has { g [ 'vram_gb' ]:.0f } GB of VRAM: a card sharing the model needs " 1933f" { SPLIT_MIN_VRAM_GB } GB or more (it holds the dense weights of its layers and its own prompt " 1934"buffers), so the model may not start, or run slower than without it" ,True ,yes , 1935f"GPU { i } ( { g [ 'name' ] } ) { what } is not used together with other GPUs: { p } " , 1936"leave it out of --gpus, or answer y to use it anyway" ," Use it anyway?" ) 1937warn (f"GPU { i } ( { g [ 'name' ] } ) is used together with the others, as you chose" ) 1938continue 1939say () 1940gpu_table (found ) 1941can = together_ok (found ) 1942single = [x for x in found if gpu_problem (x )is None ] 1943ones = " or " .join (f"--gpu { x [ 'index' ] } " for x in single ) 1944both = "--gpus " + "," .join (str (x ["index" ])for x in can )if can else "" 1945hint = ((f"use these together: { both } " + (f" (or one card: { ones } )" if not together else "" ))if can else 1946f"use one card: { ones } " if single else "Strata needs an NVIDIA RTX 20 series or newer card" ) 1947fail (f"GPU { i } { '' if g is None else ' (' + g [ 'name' ] + ')' } { what } cannot be used: { p } " ,hint ) 1948 1949 1950def arch_numbers (value )-> list : 1951"""The CUDA architectures of a BUILD.json `archs` / `vision_archs` value, as numbers. The packaging recipes write the picture 1952reader's as ONE string ("75;86;89;120", packaging/package_engine.py stamp_vision_archs, build_cuda_linux.sh), the engine's own as a 1953list of numbers ([75, 86, 89, 120]); [60, "sm_61", "70-real", "compute_89"] and "60,61 70" are read too (#3810: a string was 1954iterated character by character and setup stopped with int(';')).""" 1955if value is None or value == "" : 1956return [] 1957parts = list (value )if isinstance (value , (list ,tuple ,set ))else re .split (r"[;,\s]+" ,str (value )) 1958out :list = [] 1959for part in parts : 1960m = re .search (r"\d+" ,str (part )) 1961if m and int (m .group ())not in out : 1962out .append (int (m .group ())) 1963return out 1964 1965 1966def arch_names (value )-> list : 1967"""The AMD architectures ("gfx1100") of a BUILD.json `archs` / `vision_archs` value, as strings: a list or one ";" / "," separated string.""" 1968if value is None or value == "" : 1969return [] 1970parts = list (value )if isinstance (value , (list ,tuple ,set ))else re .split (r"[;,\s]+" ,str (value )) 1971return [str (p )for p in parts if str (p )] 1972 1973 1974def engine_archs (toolkit = 13 ): 1975"""The GPU generations the installed engine has code for: (archs, ptx), or None when there is none.""" 1976info = engine_dir (toolkit )/ "BUILD.json" 1977try : 1978meta = json .loads (info .read_text (encoding = "utf-8" )) 1979except (OSError ,ValueError ): 1980return None 1981return arch_numbers (meta .get ("archs" )),bool (meta .get ("ptx" )) 1982 1983 1984def engine_archs_hip (): 1985"""The AMD architectures the installed HIP engine was compiled for ("gfx1201", ...), or None.""" 1986try : 1987meta = json .loads ((ROOT / "engine" / "BUILD.json" ).read_text (encoding = "utf-8" )) 1988except (OSError ,ValueError ): 1989return None 1990return arch_names (meta .get ("archs" ))if meta .get ("backend" )== "hip" else None 1991 1992 1993def engine_runs_on (g ,toolkit = 13 )-> bool : 1994ea = engine_archs (toolkit ) 1995if ea is None or not ea [0 ]: 1996return True 1997archs ,ptx = ea 1998return int (g ["arch" ])in archs or (ptx and int (g ["arch" ])> max (archs )) 1999 2000 2001def start_gpus (text ): 2002"""--gpus when starting an installed model: NVIDIA cards as nvidia-smi numbers them, or on a PC whose AMD cards 2003are the ones Strata can use, AMD cards as setup lists them ("all": every supported AMD card).""" 2004if not text : 2005return None 2006found = gpus () 2007if str (text ).strip ().lower ()== "all" and not WIN and not together_ok (found ): 2008amd = amd_gpus () 2009if len ([g for g in amd if amd_problem (g )is None ])>= 2 : 2010return [g ["index" ]for g in amd_parse_gpus ("all" ,amd )] 2011if not found and not WIN :# #1594: no NVIDIA card, AMD ones: "1,0" names those, as setup lists them 2012amd = amd_gpus () 2013if amd : 2014return [g ["index" ]for g in amd_parse_gpus (text ,amd )] 2015return parse_gpus (text ,found ) 2016 2017 2018def choose_gpus (a ,found )-> list : 2019"""Which cards this install uses: --gpus / --gpu, or asked when two or more can share the model (the two best 2020together recommended), else the supported card with the most VRAM. Returns their numbers, in the engine order, the Main card last when roles are chosen.""" 2021if a .gpus : 2022sel = parse_gpus (a .gpus ,found ) 2023check_gpus (sel ,found ,yes = a .yes ,named = str (a .gpus ).strip ().lower ()!= "all" ) 2024return sel 2025if a .gpu is not None : 2026check_gpus ([a .gpu ],found ) 2027return [a .gpu ] 2028single = sorted ([g for g in found if gpu_problem (g )is None ],key = lambda x : (- round (x ["vram_gb" ]),x ["index" ])) 2029if not single : 2030gpu_table (found ) 2031fail ("none of your GPUs can run Strata" ,"it needs an NVIDIA RTX 20 series or newer (compute capability 7.5+)" ) 2032can = together_ok (found ) 2033if not can : 2034for g in found :# said, not asked: a card that works alone but cannot share a model beside a bigger one 2035if g ["index" ]!= single [0 ]["index" ]and gpu_problem (g )is None : 2036say (f" GPU { g [ 'index' ] } ( { g [ 'name' ] } , { g [ 'vram_gb' ]:.0f } GB) is not used: a card that shares a model needs { SPLIT_MIN_VRAM_GB } GB or more, " 2037f"so the model runs on GPU { single [ 0 ][ 'index' ] } alone." ) 2038return [single [0 ]["index" ]] 2039return choose_roles (a ,found ) 2040 2041 2042def fallback_card (a ,gpu ,chosen ): 2043"""A model that cannot share its memory across cards keeps ONE card: the one setup always chose (the most VRAM, then the lower number), 2044not the Main card of the roles - unless the person named the roles (--gpu-roles), then their Main card.""" 2045if getattr (a ,"_roles_explicit" ,False )or not getattr (a ,"_roles" ,None ): 2046return gpu 2047return min (chosen ,key = lambda g : (- round (g ["vram_gb" ]),g ["index" ])) 2048 2049 2050def card_speeds ()-> dict : 2051"""{card number: SMs x max clock} of the NVIDIA cards (strata_control/gpu_roles.py); {} when it cannot say.""" 2052from strata_control import gpu_roles 2053return gpu_roles .nvidia_speeds () 2054 2055 2056def roles_cards (found )-> list : 2057sp = card_speeds () 2058return [{"index" :g ["index" ],"name" :g ["name" ],"vram_gb" :g ["vram_gb" ],"usable" :gpu_problem (g )is None ,"vendor" :"nvidia" , 2059** ({"speed" :sp [g ["index" ]]}if g ["index" ]in sp else {})}for g in found ] 2060 2061 2062def choose_roles (a ,found )-> list : 2063"""Two or more cards can share the model: the recommended role of each (the best card Main, the others Helper, a card with 8 GB or less 2064Off) and ONE question, "Use these roles?". n takes the person's own: 1=main,0=helper (cards left out are Off). Returns the card 2065numbers in the engine's order (Main last) and keeps the roles in a._roles for the config (docs/MULTI_GPU.md).""" 2066from strata_control import gpu_roles 2067cards = roles_cards (found ) 2068roles = dict (gpu_roles .recommend (cards )["roles" ]) 2069say () 2070say (" Strata recommends a role for each graphics card. Main does the last steps of every answer; a Helper holds part of the model;" ) 2071say (" Off leaves the card alone (a card with 8 GB or less starts Off beside a bigger card). Details: docs/MULTI_GPU.md." ) 2072by = {c ["index" ]:c for c in cards } 2073for i in sorted (roles ): 2074say (f" GPU { i + 1 } { gpu_roles . short_name ( by [ i ]):<22 } { by [ i ][ 'vram_gb' ]:>4.0f } GB { roles [ i ]. capitalize () } " ) 2075for g in found : 2076if gpu_problem (g ,together = True )is not None and roles .get (g ["index" ])== "off" : 2077say (f" (GPU { g [ 'index' ] + 1 } , { g [ 'name' ] } : { gpu_problem ( g , together = True ) } )" ) 2078if ask ("Use these roles?" , ["y" ,"n" ],"y" ,a .yes or a .check )== "n" : 2079while True : 2080try : 2081text = input ("Roles, e.g. " + "," .join (f" { i } = { r } " for i ,r in sorted (roles .items ()))+ " (cards you leave out are Off): " ).strip () 2082except EOFError : 2083fail ("input ended before a setup answer was received" ,"run setup in a terminal, or pass --yes to accept the recommended roles" ) 2084if not text : 2085break 2086try : 2087roles = gpu_roles .roles_from_text (text ,cards ) 2088break 2089except ValueError as e : 2090say (f" { e } " ) 2091roles = gpu_roles .normalize (roles ,cards ) 2092lst = gpu_roles .order (roles ,cards ) 2093if not lst : 2094fail ("every graphics card is Off" ,"setup needs one card for Main (the app and `strata launch` can start with all cards Off)" ) 2095a ._roles = roles 2096a ._roles_cards = cards 2097ok (gpu_roles .describe (roles ,cards )) 2098return lst 2099 2100 2101def split_mmap (cfg :dict )-> bool : 2102"""#364 #384: the low-RAM mode's resident variant (--resident-experts) has no layer split yet. A config with it 2103that runs on several GPUs reads the experts the GPUs do not hold through the OS file cache instead 2104(--mmap-experts: the placement those reports measured 1.3-1.6x faster than one GPU), said plainly - the engine 2105used to refuse the pair. #642: the engines from RESIDENT_SPLIT_ENGINE run it on a split, so it is kept. True 2106when the config changed.""" 2107a = cfg .get ("args" , []) 2108if "--resident-experts" not in a or resident_split (): 2109return False 2110a [a .index ("--resident-experts" )]= "--mmap-experts" 2111warn ("the low-RAM mode's resident variant (--resident-experts) has no layer split yet: on several GPUs the experts " 2112"the GPUs do not hold are read through the OS file cache (--mmap-experts) instead, and RAM can fill up to 0 " 2113"free during long prompts. One GPU keeps them in RAM (steady RAM use): START-HERE --setup, or --gpu N for a " 2114"start" ) 2115return True 2116 2117 2118def model_file (fam :dict ,model :str ,i :int )-> str : 2119"""Shard i's file name: the family's pattern, or the model's own (#621: UD-IQ4_XS has three shards, not four). {q} is the 2120name on the Hub ("quant"; the catalog name of the v3.1 UD-IQ4_XS is another).""" 2121return MODELS .get (model , {}).get ("file" ,fam ["file" ]).format (q = model_quant (model ),i = i ) 2122 2123 2124def model_quant (model :str )-> str : 2125"""The name of the model's files and folder on the Hub: the catalog name, except where a catalog name had to differ (UNSLOTH_V31_IQ4_XS).""" 2126return MODELS .get (model , {}).get ("quant" ,model ) 2127 2128 2129def model_hf (fam :dict ,model :str )-> str : 2130"""The Hugging Face folder the model's shards are fetched from: the family's, at the commit the model names ("revision") when it is not 2131the repository's pinned one (HF_REVISIONS).""" 2132base = fam ["hf" ].format (q = model_quant (model )) 2133rev = MODELS .get (model , {}).get ("revision" ) 2134return re .sub (r"(/resolve/)[0-9a-f]{40}(?=/)" ,r"\g<1>" + rev ,base ,count = 1 )if rev else base 2135 2136 2137def fam_pin (fam :dict ,s :Path )-> tuple : 2138"""(bytes, sha256) the family pins for the shard `s`: its entry in fam["sha256"], or, where the family also knows the same file name 2139in another layout ("sha256_alt": UD-Q4_K_XL's four shards at UNSLOTH_V31_REVISION), the one of those with the size the file on the disk has.""" 2140pin = fam ["sha256" ][s .name ] 2141if s .exists ()and s .name in fam .get ("sha256_alt" , {}): 2142have = s .stat ().st_size 2143if have != pin [0 ]: 2144for alt in fam ["sha256_alt" ][s .name ]: 2145if alt [0 ]== have : 2146return alt 2147return pin 2148 2149 2150def model_shards (fam :dict ,model :str )-> int : 2151return MODELS .get (model , {}).get ("shards" ,fam .get ("shards" ,2 )) 2152 2153 2154def budget_model (cfg :dict )-> str : 2155"""The Unsloth model a config with a RAM budget runs, from its --native shard's name (UD-Q4_K_XL by default).""" 2156a = cfg .get ("args" , []) 2157native = Path (a [a .index ("--native" )+ 1 ]).name .upper ()if "--native" in a and a .index ("--native" )+ 1 < len (a ) \ 2158else "" 2159mine = [m for m ,d in MODELS .items ()if d .get ("budget" )and f"- { model_quant ( m ). upper () } -" in native ] 2160if len (mine )> 1 :# the pinned UD-IQ4_XS (three shards) and the v3.1 one (four): the shard count in the name tells them apart 2161count = re .search (r"-OF-(\d{5})\.GGUF$" ,native ) 2162mine = [m for m in mine if count and MODELS [m ].get ("shards" )== int (count .group (1 ))]or mine 2163return mine [0 ]if mine else "UD-Q4_K_XL" 2164 2165 2166def unsloth_split_need_gb (model = "UD-Q4_K_XL" )-> float : 2167"""#498: the RAM UD-Q4_K_XL needs on several GPUs, where it has no RAM budget (the engine refuses 2168--resident-budget-gib with a layer split): its GGUF files and UNSLOTH_RAM_LEFT_GB more (~135 GB). Measured safe 2169at 165 GiB (2x RTX 3090: MemAvailable never under 68 GiB); the 0-free case of #384 was 47 GB with a 70 GB model.""" 2170return MODELS [model ]["download_gb" ]+ UNSLOTH_RAM_LEFT_GB 2171 2172 2173def split_budget (cfg :dict ,yes :bool = False ,explicit :bool = False )-> bool : 2174"""#498: a UD-Q4_K_XL config (its RAM budget, --resident-budget-gib) started on several GPUs. The engine refused 2175the budget with a layer split (it exited with code 2), so the split runs without it - all the experts loaded into 2176RAM at start - where the RAM holds the GGUFs and 24 GB more; else setup says so and asks (#737: a recommendation, 2177not a wall - 128 GB ran it fine): a "no" stops, before the config is saved; `explicit` (--gpus) with --yes goes on. 2178#642: the engines from RESIDENT_SPLIT_ENGINE keep the resident RAM copy on a split - every card's cache left out 2179of it, the rest ranked by the whole expert profile - and the budget is that copy's size, so it is kept, as 2180split_mmap keeps --resident-experts. True when the config changed.""" 2181a = cfg .get ("args" , []) 2182if "--resident-budget-gib" not in a or resident_split (): 2183return False 2184model = budget_model (cfg ) 2185need ,ram = unsloth_split_need_gb (model ),ram_gb () 2186if ram < need : 2187confirm_risk (f" { model } cannot share its RAM budget across GPUs (the engine has no layer split with it), and " 2188f"without the budget it needs ~ { need :.0f } GB of RAM (its GGUF files and { UNSLOTH_RAM_LEFT_GB } GB " 2189f"more); this PC has { ram :.0f } GB. The estimate is a worst case: a 128 GB PC ran it (#737), but " 2190"it may page or stall here." ,explicit ,yes , 2191f" { model } on several GPUs needs ~ { need :.0f } GB of RAM; this PC has { ram :.0f } GB" , 2192"start it on one GPU: START-HERE.bat --gpu N (Linux: ./setup.sh --gpu N)" ) 2193i = a .index ("--resident-budget-gib" ) 2194del a [i :i + 2 ] 2195ok (f" { model } on several GPUs: no RAM budget (the engine has none with a layer split) - all its experts are " 2196"loaded into RAM from the model files at start, and the files pass through the OS file cache (#498)" ) 2197return True 2198 2199 2200REMOTE_EXPERT_OPT = "--remote-expert-opt" 2201HELPER_CACHE_FLAGS = ("--expert-cache-device1" ,"--expert-cache-device2" ,"--expert-cache-device3" ) 2202 2203 2204def recommend_remote_expert_opt (cfg :dict ,off :bool = False )-> None : 2205"""0.1.39b (#578): a config on two or more GPUs with a helper cache gets --remote-expert-opt - the helper expert caches 2206(--expert-cache-device1..3) then stay complementary to the main GPU's, return their rows already weighted and skip 2207the CPU's activation quantization where no expert is left to it (dual RTX 4090: +63% mixed, +132% code over the 2208plain helper path). The engine uses it only with a helper cache; a layer split runs as before. A recommendation: 2209`off` (setup's --no-remote-expert-opt) or "remote_expert_opt": false in the config keeps it out, and a single-GPU 2210config is not touched.""" 2211if len (gpu_sel (cfg .get ("gpu" )))< 2 : 2212return 2213args = cfg .setdefault ("args" , []) 2214if off or cfg .get ("remote_expert_opt" )is False : 2215if REMOTE_EXPERT_OPT in args : 2216args .remove (REMOTE_EXPERT_OPT ) 2217return 2218# #1352: --pipeline-windows (the first card starts the next window) is switched off by --remote-expert-opt (the 2219# helper caches), so a config that asks for it keeps its pipeline: one of the two, not both (docs/MULTI_GPU.md) 2220pw = args .index ("--pipeline-windows" )if "--pipeline-windows" in args else - 1 2221if pw >= 0 and pw + 1 < len (args )and args [pw + 1 ]!= "0" : 2222if REMOTE_EXPERT_OPT in args : 2223warn ("--pipeline-windows and --remote-expert-opt are both in this config: the engine turns the pipeline off " 2224"beside the helper caches. Keep one - remove --remote-expert-opt for the pipeline " 2225"(docs/MULTI_GPU.md, #1352)" ) 2226else : 2227ok ("multi-GPU: --pipeline-windows is set, so --remote-expert-opt is not added (the helper caches turn the " 2228"pipeline off; docs/MULTI_GPU.md)" ) 2229return 2230# #1447: the flag acts only on the helper caches (--expert-cache-device1..3); without one the engine builds nothing 2231# from it, and a plain layer split gained a flag that says "helpers" for no reason. Setup adds it only beside a 2232# helper cache; a flag already in the config stays (the user's, or an earlier setup's - harmless). 2233if not any (a .split ("=" ,1 )[0 ]in HELPER_CACHE_FLAGS for a in args ): 2234return 2235if REMOTE_EXPERT_OPT not in args : 2236args .append (REMOTE_EXPERT_OPT ) 2237ok ("multi-GPU: --remote-expert-opt (helper expert caches complementary to the main GPU's, #578; " 2238"--no-remote-expert-opt leaves it out)" ) 2239 2240 2241def offer_together (cfg_path :Path ,cfg :dict ,yes :bool )-> dict : 2242"""Starting a model set up for one card on a PC with two or more that can share it: asked once (the answer is 2243saved in its config).""" 2244if isinstance (cfg .get ("gpu" ),list )or cfg .get ("gpus_asked" ): 2245return cfg 2246found = gpus () 2247can = together_ok (found ) 2248if not can : 2249return cfg 2250# #498: UD-Q4_K_XL's RAM budget had no layer split; without it the RAM must hold the GGUFs and 24 GB more. #642: 2251# the engines from RESIDENT_SPLIT_ENGINE keep the budget on both cards, so any RAM is offered them (one GPU stays 2252# the recommendation, the tested setup) 2253budget = "--resident-budget-gib" in cfg .get ("args" , []) 2254if budget and not resident_split ()and ram_gb ()< unsloth_split_need_gb (budget_model (cfg )): 2255return cfg 2256pair = can [:2 ] 2257cfg ["gpus_asked" ]= True 2258# #364 #384: the resident low-RAM variant stays on one card unless the user says otherwise (its RAM use is steady); 2259# #642: the engines from RESIDENT_SPLIT_ENGINE keep it on both cards, so they are offered as for any config 2260resident = "--resident-experts" in cfg .get ("args" , [])and not resident_split () 2261say () 2262say (" This PC has " + " and " .join (gpu_name (g )for g in pair )+ ": Strata can share the model across both." ) 2263say (" Together they hold about twice the model's experts and read prompts about 20% faster (docs/MULTI_GPU.md)." ) 2264if resident : 2265say (" This model runs in the low-RAM mode with its experts kept in RAM, on one GPU (recommended: steady RAM" ) 2266say (" use). On both, the experts the GPUs do not hold are read through the OS file cache instead: faster in" ) 2267say (" two reports (#364, #384), but RAM can fill up to 0 free during long prompts." ) 2268if budget and resident_split (): 2269say (f" This model ( { budget_model ( cfg ) } ) runs on one GPU with a RAM budget of its experts (recommended: the tested" ) 2270say (" setup). On both it keeps the budget: each card caches the experts of its own layers, and the RAM holds" ) 2271say (" the hottest of the rest (#642)." ) 2272elif budget : 2273say (f" This model ( { budget_model ( cfg ) } ) runs on one GPU with a RAM budget of its experts (recommended: the tested" ) 2274say (" setup). On both it has no budget: all its experts are loaded into RAM at start, which this PC's RAM" ) 2275say (" holds - about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s)." ) 2276short = split_short (pair )# #448: one card recommended (asked "n" by default), as for --resident 2277for g in short : 2278say (f" { split_short_note ( g ) } ." ) 2279tk = config_toolkit (cfg ) 2280missing = [g for g in pair if not (engine_runs_on (g )if tk == 13 else engine_runs_on (g ,tk ))] 2281if missing : 2282say (" The installed engine has no code for " + ", " .join (g ["name" ]for g in missing )+ ": to use them " 2283"together, run START-HERE.bat --setup --gpus " + "," .join (str (g ["index" ])for g in pair )) 2284elif ask (" Use both from now on? (you can change it later: START-HERE.bat --gpu N for one card)" , 2285 ["y" ,"n" ],"n" if resident or short or budget else "y" ,yes )== "y" : 2286cfg ["gpu" ]= [g ["index" ]for g in pair ] 2287cfg ["layer_split" ]= cfg .get ("layer_split" )or "auto" 2288split_mmap (cfg ) 2289split_budget (cfg ) 2290recommend_remote_expert_opt (cfg ) 2291ok ("from now on this model runs on " + " + " .join (gpu_name (g )for g in pair )) 2292else : 2293ok ("staying on one GPU (START-HERE.bat --gpus " + "," .join (str (g ["index" ])for g in pair )+ " switches)" ) 2294write_config (cfg_path ,cfg ) 2295return cfg 2296 2297 2298def gpu_info (pick = None ): 2299"""The GPU Strata runs on: `pick` (nvidia-smi's number) if given, else the one with the most VRAM (ties: the 2300lower number). None when there is no NVIDIA GPU. The dict also says how many there are ("count").""" 2301found = gpus () 2302if not found : 2303return None 2304pick = GPU_PICK if pick is None else pick 2305if pick is not None : 2306g = next ((x for x in found if x ["index" ]== pick ),None ) 2307if g is None : 2308fail (f"there is no GPU { pick } : " + ", " .join (f" { x [ 'index' ] } = { x [ 'name' ] } " for x in found )) 2309else : 2310g = max (found ,key = lambda x : (round (x ["vram_gb" ]),- x ["index" ])) 2311return {** g ,"count" :len (found )} 2312 2313 2314def find_nvcc (below = None ): 2315"""The newest CUDA toolkit's nvcc and its (major, minor); with `below`, the newest older than that version. 2316#601: STRATA_NVCC=<path to nvcc> is the only one considered (a newer toolkit beside it that cannot build on this 2317PC - CUDA 12.9 with glibc 2.43 - is not taken instead).""" 2318pick = os .environ .get ("STRATA_NVCC" ) 2319if pick : 2320if not Path (pick ).exists (): 2321warn (f"STRATA_NVCC= { pick } : no such file; looking for a CUDA toolkit as usual" ) 2322else : 2323v = re .search (r"release (\d+)\.(\d+)" ,out ([pick ,"--version" ])) 2324ver = (int (v .group (1 )),int (v .group (2 )))if v else None 2325if ver and below is not None and ver >= below : 2326warn (f"STRATA_NVCC= { pick } is CUDA { ver [ 0 ] } . { ver [ 1 ] } ; this build needs one older than " 2327f" { below [ 0 ] } . { below [ 1 ] } " ) 2328return (None ,None ) 2329return (pick ,ver )if ver else (None ,None ) 2330cands = [shutil .which ("nvcc" )] 2331for var in ("CUDA_PATH" ,"CUDA_HOME" ):# CUDA_HOME: Linux's usual name (#601) 2332if os .environ .get (var ): 2333cands .append (str (Path (os .environ [var ])/ "bin" / ("nvcc.exe" if WIN else "nvcc" ))) 2334if WIN : 2335base = Path (r"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA" ) 2336if base .exists (): 2337cands += [str (p / "bin" / "nvcc.exe" )for p in sorted (base .iterdir (),reverse = True )] 2338else : 2339cands += [str (p / "bin" / "nvcc" )for p in sorted (Path ("/usr/local" ).glob ("cuda*" ),reverse = True )] 2340cands += [str (p / "bin" / "nvcc" )for p in sorted (Path ("/opt" ).glob ("cuda*" ),reverse = True )]# Arch (#46) 2341best = (None ,None ) 2342for c in dict .fromkeys (cands ):# every toolkit found; the newest wins 2343if c and Path (c ).exists (): 2344v = re .search (r"release (\d+)\.(\d+)" ,out ([c ,"--version" ])) 2345ver = (int (v .group (1 )),int (v .group (2 )))if v else None 2346if ver and (below is None or ver < below )and (best [1 ]is None or ver > best [1 ]): 2347best = (c ,ver ) 2348return best 2349 2350 2351def find_vcvars (cuda_v = None ): 2352"""Visual Studio's vcvars64.bat. #985: CUDA 13.0-13.2 accept Visual Studio 2019 and 2022 only, so a newer one 2353(2026 = version 18) is taken only with CUDA 13.3 or newer (`cuda_v`, the toolkit's (major, minor)). 2354 2355The version range is CUDA's requirement alone, so a caller with no CUDA (`cuda_v is None`) asks vswhere for no 2356range at all: the CPU image encoder is built by MSVC, which is happy with any version (tools/hip/build_windows.bat 2357already calls vswhere that way). With the range applied to every caller, a machine whose only C++ tools are 2358Visual Studio 2026 gets None back and nothing can be built there (#881). STRATA_VCVARS=<vcvars64.bat> picks one 2359by hand, for an install vswhere cannot use.""" 2360override = os .environ .get ("STRATA_VCVARS" ) 2361if override : 2362v = Path (override ) 2363return v if v .exists ()else None 2364vswhere = Path (os .environ .get ("ProgramFiles(x86)" ,r"C:\Program Files (x86)" ))/ "Microsoft Visual Studio/Installer/vswhere.exe" 2365if not vswhere .exists (): 2366return None 2367# CUDA 13 accepts Visual Studio 2019 and 2022 only: a newer one (2026 = version 18) installed next to them 2368# must not be picked ("unsupported Microsoft Visual Studio version"); with only a newer one there is none 2369args = [str (vswhere ),"-latest" ,"-products" ,"*" ] 2370if cuda_v is not None : 2371upper = "19.0" if tuple (cuda_v )>= (13 ,3 )else "18.0" 2372args += ["-version" ,f"[17.0, { upper } )" ]# 17 = Visual Studio 2022: the sources are C++20, and nvcc silently drops -std=c++20 under 2019 (#3566) 2373args += ["-requires" ,"Microsoft.VisualStudio.Component.VC.Tools.x86.x64" ,"-property" ,"installationPath" ] 2374p = out (args ).strip () 2375v = Path (p )/ "VC/Auxiliary/Build/vcvars64.bat" if p else None 2376return v if v and v .exists ()else None 2377 2378 2379CMAKE_MIN = (3 ,24 )# CMakeLists.txt: cmake_minimum_required(VERSION 3.24) 2380 2381 2382def _tool_version (path ,name ): 2383"""(ok, version tuple) of `path --version`: ok False when it does not run (a pip launcher whose Python is gone).""" 2384try : 2385done = subprocess .run ([path ,"--version" ],capture_output = True ,text = True ,errors = "replace" ,timeout = 30 ) 2386except (OSError ,subprocess .SubprocessError ): 2387return False , () 2388if done .returncode != 0 : 2389return False , () 2390found = re .search (r"(\d+)\.(\d+)(?:\.(\d+))?" ,done .stdout or "" ) 2391return True ,tuple (int (x )for x in found .groups ()if x )if found else () 2392 2393 2394def find_tool (name ): 2395"""The tool the build uses (cmake, ninja): the one pip installed next to THIS Python first (the virtualenv's own, #3822), then PATH, 2396then ~/.local/bin. One that does not run (a pip launcher whose Python is gone) is skipped, and so is a cmake older than the 2397one CMakeLists.txt needs while another is found; with only an older one it is returned and the build says so.""" 2398exe = name + (".exe" if WIN else "" ) 2399candidates = [str (d / exe )for d in (Path (sys .executable ).parent / "Scripts" ,Path (sys .executable ).parent )if (d / exe ).exists ()] 2400on_path = shutil .which (name ) 2401if on_path and on_path not in candidates : 2402candidates .append (on_path ) 2403local = Path .home ()/ ".local" / "bin" / exe 2404if local .exists ()and str (local )not in candidates : 2405candidates .append (str (local )) 2406older = None 2407for c in candidates : 2408runs ,version = _tool_version (c ,name ) 2409if not runs : 2410continue 2411if name == "cmake" and version and version [:2 ]< CMAKE_MIN : 2412older = older or c 2413continue 2414return c 2415return older 2416 2417 2418def free_gb (path ): 2419path .mkdir (parents = True ,exist_ok = True ) 2420return shutil .disk_usage (path ).free / 1e9 2421 2422 2423def disk_room_problem (models_dir ,pack_dir ,other_gb ,copy_gb ,other_note = "" ,free = None ): 2424"""None when the files this setup run still writes fit, else (message, hint). `other_gb` is what goes to the model folder (a download, the 2425preparation, the picture files); `copy_gb` is the low-RAM mode's copy of the experts, which is written to the data folder's packs folder 2426and not to the model folder (QA 0213: the refusal named the model folder of the person's own files and said to use --data-dir, although the model 2427files were already there and the 51 GB belonged to the copy in the data folder). The copy is measured where it goes; on one drive both add up.""" 2428free = free or free_gb 2429packs = pack_dir .parent 2430free_models = free (models_dir ) 2431models_problem = (f"not enough free disk space in { models_dir } : need ~ { other_gb :.0f } GB, { free_models :.0f } GB free" + other_note , 2432"use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL else "use --models-dir on a bigger drive" ) 2433if free_models < other_gb : 2434return models_problem 2435if not copy_gb : 2436return None 2437free_packs = free (packs ) 2438try : 2439same_drive = os .stat (models_dir ).st_dev == os .stat (packs ).st_dev 2440except OSError : 2441same_drive = False 2442needs = copy_gb + (other_gb if same_drive else 0 ) 2443if free_packs < needs : 2444return (f"not enough free disk space for the low-RAM copy of the experts in { pack_dir } : it needs about { needs :.0f } GB " 2445f"and { free_packs :.0f } GB are free there." , 2446"Free some space, move Strata's data folder to a bigger drive (strata launch --data-dir), or set Low-RAM mode to Automatic to run without the copy." ) 2447return None 2448 2449 2450# ------------------------------------------------------------------------------------------------ downloads 2451def drop_archive (z :Path )-> None : 2452"""An unpacked or refused engine archive and its .done mark go: a refused one kept them, and every later run 2453reused it ("already downloaded") instead of the published one (PR #324).""" 2454z .unlink (missing_ok = True ) 2455z .with_name (z .name + ".done" ).unlink (missing_ok = True ) 2456 2457 2458# Parallel ranged downloads (0.2.0). One TCP stream often cannot fill a fast line (a long or lossy route, a CDN that limits 2459# each connection): download() takes the file in DL_CHUNK pieces over several connections, writes each piece at its own offset, 2460# and keeps the finished pieces in <name>.part.chunks so a stopped download continues where it was. Anything that is not a 2461# ranged file of known length (no Range support, no length, a small file) is one stream, as before. 2462DL_CONNECTIONS = 16 # STRATA_DL_CONNECTIONS=1 restores one stream (for testers) 2463DL_CHUNK = 32 << 20 # bytes per piece: what the piece list records and what a failed request loses at most 2464DL_RUN = 4 # pieces one request asks for (4 x 32 MiB): a new connection per piece spends its first seconds 2465# in TCP slow start (measured: 8 connections 66 MB/s with a request per piece, 73 with 128 MiB) 2466DL_MIN_PARALLEL = 256 << 20 # smaller files are one stream 2467DL_CHUNK_TRIES = 5 # tries per request (1, 2, 4, 8 s apart) before the round is given up and run again 2468DL_ROUNDS = 30 # rounds in a row without a new byte (10 s apart) before the download is given up; and 5 minutes without one (netpolicy) 2469DL_BACKOFF = 1.0 # seconds before the second try of a request, doubled each time (tests set 0) 2470DL_SAVE_EVERY = 5.0 # seconds between writes of the progress file 2471 2472 2473def dl_connections ()-> int : 2474"""How many connections a big download uses: STRATA_DL_CONNECTIONS, else DL_CONNECTIONS (1 = one stream).""" 2475raw = (os .environ .get ("STRATA_DL_CONNECTIONS" )or "" ).strip () 2476try : 2477n = int (raw )if raw else DL_CONNECTIONS 2478except ValueError : 2479n = DL_CONNECTIONS 2480return max (1 ,min (n ,32 )) 2481 2482 2483class _NoRange (Exception ): 2484"""The server does not answer a byte range with that range (no 206, or another range): one stream instead.""" 2485 2486 2487class _DiskError (Exception ): 2488"""The .part file cannot be written (disk full, no permission): retrying would not help.""" 2489 2490 2491class _PieceFailed (Exception ): 2492"""A piece failed DL_CHUNK_TRIES times.""" 2493 2494 2495class _Changed (Exception ): 2496"""The server's file is not the one the first pieces came from (another ETag): what was written cannot be trusted.""" 2497 2498 2499_CONTENT_RANGE = re .compile (r"\s*bytes (\d+)-(\d+)/(\d+)\s*$" ) 2500 2501 2502def _etag (headers )-> str | None : 2503"""The object identity a response names: ETag without the weak mark and quotes; None when it sends none.""" 2504raw = (headers .get ("ETag" )or "" ).strip () 2505if raw [:2 ]in ("W/" ,"w/" ): 2506raw = raw [2 :] 2507return raw .strip ('"' )or None 2508 2509 2510def _check_ranged (r ,pos :int ,end :int ,total :int ,etag :str | None ): 2511"""A ranged answer is trusted only when it is exactly the bytes asked for: status 206, Content-Range `pos-end/total` 2512(a 200 with the whole file, another range or another total is the server not honouring the request), a Content-Length 2513that fits, and the same object (ETag) as the first answer. _NoRange: this server cannot be used with ranges; 2514OSError: a bad answer worth asking again (another edge).""" 2515if r .status != 206 : 2516raise _NoRange (f"HTTP { r . status } " ) 2517m = _CONTENT_RANGE .match (r .headers .get ("Content-Range" )or "" ) 2518if not m or (int (m .group (1 )),int (m .group (2 )),int (m .group (3 )))!= (pos ,end ,total ): 2519raise _NoRange (f"Content-Range { ( r . headers . get ( 'Content-Range' ) or '' )!r } for bytes { pos } - { end } / { total } " ) 2520cl = (r .headers .get ("Content-Length" )or "" ).strip () 2521if cl and cl .isdigit ()and int (cl )!= end - pos + 1 : 2522raise OSError (f"Content-Length { cl } for { end - pos + 1 } bytes asked" ) 2523got = _etag (r .headers ) 2524if etag and got and got != etag : 2525raise OSError ("the server answered with another version of the file" ) 2526 2527 2528def _write_all (f ,pos :int ,data ): 2529"""Write `data` at `pos`; a raw unbuffered file may take fewer bytes than it was given, so go on until all are down.""" 2530view = memoryview (data ) 2531f .seek (pos ) 2532done_n = 0 2533while done_n < len (view ): 2534n = f .write (view [done_n :]) 2535if not n : 2536raise OSError ("the disk took no more bytes" ) 2537done_n += n 2538 2539 2540def _read_exact (f ,pos :int ,n :int )-> bytes : 2541f .seek (pos ) 2542parts = [] 2543while n > 0 : 2544b = f .read (n ) 2545if not b : 2546break 2547parts .append (b ) 2548n -= len (b ) 2549return b"" .join (parts ) 2550 2551 2552def _url_ttl (url :str ): 2553"""Seconds a signed URL (the CDN's, after the redirect) is still valid by its own query, else None.""" 2554q = urllib .parse .parse_qs (urllib .parse .urlsplit (url ).query ) 2555try : 2556if "Expires" in q : 2557ttl = float (q ["Expires" ][0 ])- time .time () 2558elif "X-Amz-Expires" in q and "X-Amz-Date" in q : 2559t0 = calendar .timegm (time .strptime (q ["X-Amz-Date" ][0 ],"%Y%m%dT%H%M%SZ" )) 2560ttl = t0 + float (q ["X-Amz-Expires" ][0 ])- time .time () 2561else : 2562return None 2563except (ValueError ,OverflowError ): 2564return None 2565return ttl if 0 < ttl < 30 * 86400 else None # a PC clock that is far off says nothing: a 403 re-resolves 2566 2567 2568class _Source : 2569"""The URL the pieces are read from: the redirect (Hugging Face answers with a signed, time-limited CDN address) is 2570resolved once and reused; it is resolved again a little before it expires and after a 401/403/410.""" 2571 2572def __init__ (self ,url :str ,total :int ): 2573self .url ,self .total = url ,total 2574self .final ,self .deadline = None ,None 2575self .etag = None # the object the first answer named; every later answer must match 2576self .lock = threading .Lock () 2577 2578def resolve (self ,stale = None )-> str : 2579with self .lock : 2580if stale is not None and self .final is not None and self .final != stale : 2581return self .final # another connection already got a fresh address 2582req = urllib .request .Request (self .url ,headers = {"User-Agent" :"strata-setup" ,"Range" :"bytes=0-0" }) 2583with _urlopen (req ,timeout = netpolicy .RETRY_CONNECT_S )as r : 2584cr = (r .headers .get ("Content-Range" )or "" ).strip () 2585if r .status != 206 or cr != f"bytes 0-0/ { self . total } " : 2586raise _NoRange (f"HTTP { r . status } , Content-Range { cr !r } " ) 2587tag = _etag (r .headers ) 2588if self .etag and tag and tag != self .etag : 2589raise _Changed (f"the file on the server changed while it was downloaded ( { self . etag [: 12 ] } -> { tag [: 12 ] } )" ) 2590self .etag = self .etag or tag 2591r .read (1 ) 2592final = r .geturl ()or self .url 2593ttl = _url_ttl (final ) 2594self .final = final 2595self .deadline = time .monotonic ()+ max (ttl - 120 ,0 )if ttl else None 2596return final 2597 2598def get (self )-> str : 2599with self .lock : 2600cur ,expired = self .final ,self .deadline is not None and time .monotonic ()>= self .deadline 2601return self .resolve (stale = cur )if cur is None or expired else cur 2602 2603 2604class _Pieces : 2605"""The shared state of one parallel download: finished pieces, bytes of the pieces in flight, the stop flags.""" 2606 2607def __init__ (self ,total :int ,done :set ,conns :int = 1 ): 2608self .total ,self .n ,self .conns = total ,- (- total // DL_CHUNK ),conns 2609self .done ,self .flight = set (done ), {} 2610self .lock = threading .Lock () 2611self .stop = threading .Event ()# the whole download stops (Ctrl-C, a fatal error) 2612self .abort_round = threading .Event ()# a piece failed for good: end this round, run the next 2613self .fatal ,self .errors = None , [] 2614 2615def size (self ,i :int )-> int : 2616return min ((i + 1 )* DL_CHUNK ,self .total )- i * DL_CHUNK 2617 2618def add (self ,i :int ,n :int ): 2619with self .lock : 2620self .flight [i ]= self .flight .get (i ,0 )+ n 2621 2622def finish (self ,i :int ): 2623with self .lock : 2624self .flight .pop (i ,None ) 2625self .done .add (i ) 2626 2627def have (self )-> int : 2628with self .lock : 2629return sum (self .size (i )for i in self .done )+ sum (self .flight .values ()) 2630 2631def snapshot (self )-> set : 2632with self .lock : 2633return set (self .done ) 2634 2635 2636def _ranges (done )-> list : 2637out = [] 2638for i in sorted (done ): 2639if out and out [- 1 ][1 ]== i : 2640out [- 1 ][1 ]= i + 1 2641else : 2642out .append ([i ,i + 1 ]) 2643return out 2644 2645 2646def _prefix_bytes (done :set ,total :int )-> int : 2647"""Bytes of the unbroken run of finished pieces from the start of the file.""" 2648i = 0 2649while i in done : 2650i += 1 2651return min (i * DL_CHUNK ,total ) 2652 2653 2654def _load_pieces (part :Path ,total :int )-> set : 2655"""The finished pieces of an earlier run. <name>.part.chunks lists them; a .part without it comes from one stream 2656(an older setup, or STRATA_DL_CONNECTIONS=1): its bytes are a run from the start, so those pieces are finished.""" 2657side = part .with_name (part .name + ".chunks" ) 2658n = - (- total // DL_CHUNK ) 2659try : 2660size = part .stat ().st_size if part .is_file ()else None 2661except OSError : 2662size = None 2663if side .is_file (): 2664try : 2665data = json .loads (side .read_text (encoding = "utf-8" )) 2666if data .get ("v" )== 1 and data .get ("total" )== total and data .get ("chunk" )== DL_CHUNK and size is not None : 2667done = {i for a ,b in data ["done" ]for i in range (int (a ),min (int (b ),n ))} 2668return {i for i in done if min ((i + 1 )* DL_CHUNK ,total )<= size } 2669except (OSError ,ValueError ,TypeError ,KeyError ): 2670pass 2671side .unlink (missing_ok = True )# not this file's list: start the file over 2672part .unlink (missing_ok = True ) 2673return set () 2674if size is None : 2675return set () 2676if size > total : 2677part .unlink (missing_ok = True ) 2678return set () 2679return set (range (n ))if size >= total else set (range (size // DL_CHUNK )) 2680 2681 2682def _save_pieces (part :Path ,total :int ,done :set )-> bool : 2683"""Flush the data first, then record the pieces: a list never names bytes the disk does not have. False when the 2684list could not be written (an older list stays, which only costs re-downloading a few pieces after a stop).""" 2685try : 2686with open (part ,"r+b" )as g : 2687os .fsync (g .fileno ()) 2688side = part .with_name (part .name + ".chunks" ) 2689tmp = side .with_name (side .name + ".tmp" ) 2690tmp .write_text (json .dumps ({"v" :1 ,"total" :total ,"chunk" :DL_CHUNK ,"done" :_ranges (done )}),encoding = "utf-8" ) 2691with open (tmp ,"r+b" )as g : 2692os .fsync (g .fileno ()) 2693atomic .replace (tmp ,side ) 2694return True 2695except OSError : 2696return False 2697 2698 2699def _claim_part (part :Path ,url :str ,etag :str | None = None ): 2700"""Record where a .part's bytes come from (<name>.part.src: the address asked, and the file's ETag when the server 2701names one). A .part written from another address (the other mirror, another revision) or from another version of 2702the file is dropped with its piece list: two sources are not mixed inside one file, even when they should hold the 2703same bytes. A .part from an older setup has no record and is kept as before.""" 2704src = part .with_name (part .name + ".src" ) 2705try : 2706old = json .loads (src .read_text (encoding = "utf-8" ))if src .is_file ()else None 2707except (OSError ,ValueError ): 2708old = {} 2709if old is not None : 2710same = isinstance (old ,dict )and old .get ("url" )== url and not (old .get ("etag" )and etag and old .get ("etag" )!= etag ) 2711if not same : 2712part .unlink (missing_ok = True ) 2713part .with_name (part .name + ".chunks" ).unlink (missing_ok = True ) 2714src .unlink (missing_ok = True ) 2715old = None 2716if old is None or (etag and not old .get ("etag" )): 2717try : 2718src .write_text (json .dumps ({"url" :url ,"etag" :etag }),encoding = "utf-8" ) 2719except OSError : 2720pass 2721 2722 2723def _single_ready (part :Path ): 2724"""Before one stream continues a .part: keep only the unbroken run from the start of the file (what a parallel 2725download left may have gaps behind it) and drop the list.""" 2726side = part .with_name (part .name + ".chunks" ) 2727if not side .is_file (): 2728return 2729try : 2730data = json .loads (side .read_text (encoding = "utf-8" )) 2731keep = _prefix_bytes ({i for a ,b in data ["done" ]for i in range (int (a ),int (b ))},int (data ["total" ])) 2732if data .get ("chunk" )!= DL_CHUNK : 2733keep = 0 2734except (OSError ,ValueError ,TypeError ,KeyError ): 2735keep = 0 2736try : 2737if part .is_file (): 2738with open (part ,"r+b" )as g : 2739g .truncate (min (keep ,part .stat ().st_size )) 2740except OSError : 2741part .unlink (missing_ok = True ) 2742side .unlink (missing_ok = True ) 2743 2744 2745def _take_run (st :_Pieces ,todo :list )-> list : 2746"""The next request's pieces: up to DL_RUN neighbours from the front of `todo`; fewer near the end, so the last pieces 2747are spread over every connection and no single slow one holds the finish.""" 2748with st .lock : 2749if not todo : 2750return [] 2751n = max (1 ,min (DL_RUN ,len (todo )// (2 * st .conns ))) 2752run = [todo .pop (0 )] 2753while len (run )< n and todo and todo [0 ]== run [- 1 ]+ 1 : 2754run .append (todo .pop (0 )) 2755return run 2756 2757 2758def _fetch_run (src :_Source ,st :_Pieces ,f ,run :list ): 2759"""One ranged request for the neighbouring pieces in `run`, written at their offsets; each piece counts as finished 2760when its last byte is down. Every answer is checked to be exactly the range asked for (status, Content-Range, length, 2761ETag); a connection that breaks continues from the byte it reached.""" 2762start = run [0 ]* DL_CHUNK 2763end = min ((run [- 1 ]+ 1 )* DL_CHUNK ,st .total )- 1 2764pos ,tries = start ,0 2765with st .lock : 2766for i in run : 2767st .flight [i ]= 0 2768while True : 2769if st .stop .is_set (): 2770return 2771url ,err ,wait ,ra = None ,None ,None ,0.0 2772attempt_pos = pos 2773try : 2774url = src .get () 2775req = urllib .request .Request (url ,headers = {"User-Agent" :"strata-setup" ,"Range" :f"bytes= { pos } - { end } " }) 2776with _urlopen (req ,timeout = netpolicy .RETRY_CONNECT_S )as r : 2777_check_ranged (r ,pos ,end ,st .total ,src .etag ) 2778while pos <= end : 2779if st .stop .is_set (): 2780return 2781cur = pos // DL_CHUNK 2782cur_end = min ((cur + 1 )* DL_CHUNK ,st .total )# one past the piece's last byte 2783b = r .read (min (1 << 20 ,cur_end - pos )) 2784if not b : 2785raise IOError ("the connection closed early" ) 2786try : 2787_write_all (f ,pos ,b ) 2788except OSError as e : 2789raise _DiskError (str (e ))from e 2790pos += len (b ) 2791st .add (cur ,len (b )) 2792if pos == cur_end : 2793st .finish (cur ) 2794if pos <= end and st .abort_round .is_set ():# a piece failed for good: stop at a piece edge 2795with st .lock : 2796for i in run : 2797if i not in st .done and st .flight .get (i )== 0 : 2798st .flight .pop (i ,None ) 2799return 2800return 2801except (_NoRange ,_DiskError ,_Changed ): 2802raise 2803except urllib .error .HTTPError as e : 2804err = e 2805if e .code in (401 ,403 ,410 )and url is not None :# the signed address ran out: ask for a new one 2806try : 2807src .resolve (stale = url ) 2808wait = 0 2809except (_NoRange ,_Changed ): 2810raise 2811except (OSError ,http .client .HTTPException ): 2812pass 2813elif e .code in (429 ,503 ): 2814try : 2815ra = min (float (e .headers .get ("Retry-After" )or 0 ),60 ) 2816except (TypeError ,ValueError ): 2817pass 2818except (OSError ,http .client .HTTPException )as e : 2819err = e 2820# A try that moved forward is not a failed one. The request goes on from the byte it reached: what came before the 2821# break is exactly the range that was asked for (the answer's status, Content-Range, length and ETag were checked and 2822# every byte was written in full), and writing a piece again from its start would make a route that resets more often 2823# than every DL_CHUNK bytes unable to finish any piece. The whole-file SHA-256 and the repair are the net behind it. 2824tries = 1 if pos > attempt_pos else tries + 1 2825if tries >= DL_CHUNK_TRIES : 2826raise _PieceFailed (str (err )) 2827st .stop .wait (max (DL_BACKOFF * 2 ** (tries - 1 ),ra )if wait is None else wait ) 2828 2829 2830def _piece_worker (src :_Source ,st :_Pieces ,todo :list ,part :Path ): 2831try : 2832with open (part ,"r+b" ,buffering = 0 )as f : 2833while not (st .stop .is_set ()or st .abort_round .is_set ()): 2834run = _take_run (st ,todo ) 2835if not run : 2836return 2837_fetch_run (src ,st ,f ,run ) 2838except _PieceFailed as e : 2839st .errors .append (e ) 2840st .abort_round .set () 2841except (_NoRange ,_DiskError ,_Changed )as e : 2842st .fatal = st .fatal or e 2843st .stop .set () 2844except OSError as e :# the .part itself could not be opened 2845st .fatal = st .fatal or _DiskError (str (e )) 2846st .stop .set () 2847 2848 2849class StallNote : 2850"""A download that gets no byte for a while says so (#3567): "stalled at 69%" instead of a silent line that never moves. `check` is called 2851often with the bytes so far; it answers a sentence at most once a minute while nothing arrives, and None otherwise.""" 2852 2853AFTER = 120.0 2854 2855def __init__ (self ,now :float = 0.0 ): 2856self .have ,self .since ,self .said = - 1 ,now ,0.0 2857 2858def check (self ,have :int ,total :int ,now :float )-> str | None : 2859if have != self .have : 2860self .have ,self .since ,self .said = have ,now ,0.0 2861return None 2862idle = now - self .since 2863if idle < self .AFTER or now - self .said < 60 : 2864return None 2865self .said = now 2866return (f"no data for { int ( idle // 60 ) } min at { 100 * have // max ( 1 , total ) } %: the connection is stuck. It keeps trying; to stop, press Ctrl+C, " 2867"and run the same command again: the download continues where it stopped" ) 2868 2869 2870DL_PROBE_WAITS = (1.0 ,3.0 )# seconds before the 2nd and the 3rd range probe 2871 2872 2873def _probe_retryable (exc :BaseException )-> bool : 2874"""Is a failed range probe worth one more try? A hiccup is (a timeout, a reset or dropped connection, a busy server: 429/5xx); no internet 2875is not (no DNS answer, no route, refused): that fails at once, with no wait and no message (offline users, owner 11-01).""" 2876import errno 2877import socket 2878if isinstance (exc ,urllib .error .HTTPError ): 2879return exc .code in (429 ,500 ,502 ,503 ,504 ) 2880if isinstance (exc ,urllib .error .URLError ): 2881if not isinstance (exc .reason ,BaseException ): 2882return False 2883exc = exc .reason 2884if isinstance (exc , (socket .gaierror ,ConnectionRefusedError )): 2885return False 2886if isinstance (exc ,OSError )and exc .errno in (errno .ENETUNREACH ,errno .EHOSTUNREACH ,errno .ENETDOWN ): 2887return False 2888return isinstance (exc , (TimeoutError ,socket .timeout ,ConnectionResetError ,ConnectionAbortedError ,BrokenPipeError ,http .client .HTTPException )) 2889 2890 2891def _probe_ranges (src :"_Source" ,waits = DL_PROBE_WAITS ,sleep = time .sleep )-> bool : 2892"""The first range request of a parallel download, tried up to len(waits)+1 times when it fails by a hiccup: one failed probe used to make a 289350-100 GB download a single stream. False: the server does not do ranges, or the probe failed (the caller then reads one stream).""" 2894for attempt in range (len (waits )+ 1 ): 2895try : 2896src .resolve () 2897return True 2898except _NoRange : 2899return False 2900except (OSError ,http .client .HTTPException )as exc : 2901if attempt >= len (waits )or not _probe_retryable (exc ): 2902return False 2903sleep (waits [attempt ]) 2904return False 2905 2906 2907def parallel_download (url :str ,part :Path ,total :int ,label :str ,conns :int ,name :str )-> bool : 2908"""Fill `part` (total bytes) over `conns` ranged connections. True when every byte is there; False when the server 2909does not do ranges (the caller reads the file in one stream).""" 2910src = _Source (url ,total ) 2911if not _probe_ranges (src ): 2912return False # the one-stream path has its own retries and messages 2913part .parent .mkdir (parents = True ,exist_ok = True ) 2914_claim_part (part ,url ,src .etag )# a .part from another address or version is dropped here 2915done = _load_pieces (part ,total ) 2916st = _Pieces (total ,done ,conns ) 2917if not part .exists (): 2918part .touch () 2919if not part .with_name (part .name + ".chunks" ).is_file ()and not _save_pieces (part ,total ,done ): 2920return False # no piece list can be kept here: the pieces would not be told from holes 2921last_print = last_save = 0.0 2922stall = StallNote (time .time ()) 2923 2924def report (force = False ): 2925nonlocal last_print ,last_save 2926now = time .time () 2927if now - last_print > 2 or force : 2928last_print = now 2929have = st .have () 2930f"\r { label } : { have / 1e9 :6.2f } / { total / 1e9 :.2f } GB ( { 100 * have / total :.0f } %) " ,end = "" ,flush = True ) 2931note = stall .check (have ,total ,now ) 2932if note : 2933warn (note ) 2935if now - last_save > DL_SAVE_EVERY : 2936last_save = now 2937_save_pieces (part ,total ,st .snapshot ()) 2938 2939# the network rule: rounds go on while bytes keep coming (no cap on how many); DL_ROUNDS rounds in a row without a new byte, or 5 minutes 2940# without one, end it 2941clock = netpolicy .StallClock () 2942idle_rounds ,before = 0 ,- 1 2943try : 2944while True : 2945todo = [i for i in range (st .n )if i not in st .done ] 2946if not todo : 2947break 2948now_have = st .have () 2949clock .progress (now_have ) 2950idle_rounds = 0 if now_have > before else idle_rounds + 1 2951before = now_have 2952if clock .expired ()or idle_rounds >= DL_ROUNDS : 2953break 2954st .abort_round .clear () 2955st .errors .clear () 2956threads = [threading .Thread (target = _piece_worker ,args = (src ,st ,todo ,part ),daemon = True ) 2957for _ in range (min (conns ,len (todo )))] 2958for t in threads : 2959t .start () 2960while any (t .is_alive ()for t in threads ): 2961for t in threads : 2962t .join (0.25 ) 2963report () 2964if st .fatal is not None : 2965break 2966if st .errors : 2967warn (f"download interrupted ( { st . errors [ 0 ] } ); retrying in 10 s ..." ) 2969_save_pieces (part ,total ,st .snapshot ()) 2970time .sleep (10 ) 2971except BaseException : 2972st .stop .set ()# Ctrl-C: let the connections stop, keep what is finished 2973_save_pieces (part ,total ,st .snapshot ()) 2974raise 2975report (force = True ) 2976if isinstance (st .fatal ,_Changed ): 2978part .unlink (missing_ok = True ) 2979part .with_name (part .name + ".chunks" ).unlink (missing_ok = True ) 2980part .with_name (part .name + ".src" ).unlink (missing_ok = True ) 2981fail (f" { name } changed on the server while it was downloading: the part that was there was deleted" , 2982"run it again (the download starts over with the file that is there now)" ) 2983if isinstance (st .fatal ,_DiskError ): 2984_save_pieces (part ,total ,st .snapshot ()) 2985fail (f"cannot write { part . name } : { st . fatal } " ,"free some disk space (or pick another --models-dir) and run it again" ) 2986if isinstance (st .fatal ,_NoRange ): 2987_save_pieces (part ,total ,st .snapshot ()) 2988return False # the server stopped doing ranges: one stream from the unbroken start 2989if len (st .done )< st .n : 2990_save_pieces (part ,total ,st .snapshot ()) 2991have = st .have () 2992if clock .expired ():# no new byte for 5 minutes (W6) 2993fail (* clock .words (netpolicy .what_words (label ),have ,total )) 2994fail (f"could not finish downloading { name } : { have :, } of { total :, } bytes" , 2995"check your internet connection and run it again (the download resumes where it stopped)" ) 2996try : 2997with open (part ,"r+b" )as g : 2998g .truncate (total ) 2999os .fsync (g .fileno ()) 3000except OSError : 3001pass 3002part .with_name (part .name + ".chunks" ).unlink (missing_ok = True ) 3003return True 3004 3005 3006def _repair_piece (src :_Source ,st :_Pieces ,f ,i :int ,stats :dict ): 3007"""Read piece `i` from the server in 1 MiB blocks and compare each with what is on the disk; a block that differs is 3008written again. A broken connection asks again from the block it reached (every block is final once compared).""" 3009pos ,end = i * DL_CHUNK ,min ((i + 1 )* DL_CHUNK ,st .total )- 1 3010tries = 0 3011while pos <= end : 3012if st .stop .is_set (): 3013return 3014url ,wait ,ra = None ,None ,0.0 3015before = pos 3016try : 3017url = src .get () 3018req = urllib .request .Request (url ,headers = {"User-Agent" :"strata-setup" ,"Range" :f"bytes= { pos } - { end } " }) 3019with _urlopen (req ,timeout = netpolicy .RETRY_CONNECT_S )as r : 3020_check_ranged (r ,pos ,end ,st .total ,src .etag ) 3021while pos <= end : 3022if st .stop .is_set (): 3023return 3024b = r .read (min (1 << 20 ,end + 1 - pos )) 3025if not b : 3026raise IOError ("the connection closed early" ) 3027try : 3028if _read_exact (f ,pos ,len (b ))!= b : 3029_write_all (f ,pos ,b ) 3030with st .lock : 3031stats ["bytes" ]+= len (b ) 3032stats ["pieces" ].add (i ) 3033except OSError as e : 3034raise _DiskError (str (e ))from e 3035pos += len (b ) 3036st .add (i ,len (b )) 3037return 3038except (_NoRange ,_DiskError ,_Changed ): 3039raise 3040except urllib .error .HTTPError as e : 3041if e .code in (401 ,403 ,410 )and url is not None : 3042try : 3043src .resolve (stale = url ) 3044wait = 0 3045except (_NoRange ,_Changed ): 3046raise 3047except (OSError ,http .client .HTTPException ): 3048pass 3049elif e .code in (429 ,503 ): 3050try : 3051ra = min (float (e .headers .get ("Retry-After" )or 0 ),60 ) 3052except (TypeError ,ValueError ): 3053pass 3054err = e 3055except (OSError ,http .client .HTTPException )as e : 3056err = e 3057tries = 1 if pos > before else tries + 1 3058if tries >= DL_CHUNK_TRIES : 3059raise _PieceFailed (str (err )) 3060st .stop .wait (max (DL_BACKOFF * 2 ** (tries - 1 ),ra )if wait is None else wait ) 3061 3062 3063def repair_download (url :str ,path :Path ,total :int ,label :str ,conns :int ): 3064"""A finished file whose SHA-256 is wrong is not thrown away: read it again from the server piece by piece, compare 3065each block with the disk and write only the blocks that differ. Returns (damaged pieces, pieces), or None when the 3066server cannot do it (no ranges, or the file there is another one); the caller checks the SHA-256 again.""" 3067if not total or path .stat ().st_size != total : 3068return None 3069src = _Source (url ,total ) 3070try : 3071src .resolve () 3072except (_NoRange ,_Changed ,OSError ,http .client .HTTPException ): 3073return None 3074st = _Pieces (total ,set (),conns ) 3075stats = {"bytes" :0 ,"pieces" :set ()} 3076todo = list (range (st .n )) 3077errors = [] 3078 3079def worker (): 3080try : 3081with open (path ,"r+b" ,buffering = 0 )as f : 3082while not st .stop .is_set (): 3083with st .lock : 3084if not todo : 3085return 3086i = todo .pop (0 ) 3087_repair_piece (src ,st ,f ,i ,stats ) 3088st .finish (i ) 3089except (_PieceFailed ,_NoRange ,_DiskError ,_Changed ,OSError )as e : 3090errors .append (e ) 3091st .stop .set () 3092 3093threads = [threading .Thread (target = worker ,daemon = True )for _ in range (min (conns ,st .n ))] 3094for t in threads : 3095t .start () 3096last = 0.0 3097try : 3098while any (t .is_alive ()for t in threads ): 3099for t in threads : 3100t .join (0.25 ) 3101if time .time ()- last > 2 : 3102last = time .time () 3103have = st .have () 3104f"\r { label } : { have / 1e9 :6.2f } / { total / 1e9 :.2f } GB ( { 100 * have / total :.0f } %) " ,end = "" ,flush = True ) 3105except BaseException : 3106st .stop .set () 3107raise 3108if errors : 3110warn (f"could not compare { path . name } with the server again ( { errors [ 0 ] } )" ) 3111return None 3112try : 3113with open (path ,"r+b" )as g : 3114os .fsync (g .fileno ()) 3115except OSError : 3116pass 3117return len (stats ["pieces" ]),st .n 3118 3119 3120def download_single (url :str ,part :Path ,total :int ,label :str ): 3121"""One stream with a Range resume from the size of `part` (the way every download worked before parallel pieces). 3122A resumed answer is used only when it is a 206 that starts at the byte asked for; anything else starts the file over.""" 3123_single_ready (part ) 3124# the network rule: tried again while bytes keep coming (no cap on how often); 30 tries in a row without a new byte, or 5 minutes without one, end it 3125clock = netpolicy .StallClock () 3126idle ,before = 0 ,- 1 3127while True : 3128have = part .stat ().st_size if part .exists ()else 0 3129clock .progress (have ) 3130idle ,before = (0 if have > before else idle + 1 ),have 3131if clock .expired (): 3132fail (* clock .words (netpolicy .what_words (label ),have ,total )) 3133if idle >= 30 : 3134break 3135if total and have >= total :# stopped after the last byte, before the rename: nothing to 3136break # ask for (a range past the end is a 416, retried 30 times) 3137try : 3138req = urllib .request .Request (url ,headers = {"User-Agent" :"strata-setup" ,"Range" :f"bytes= { have } -" }) 3139with _urlopen (req ,timeout = netpolicy .RETRY_CONNECT_S )as r : 3140if have : 3141m = _CONTENT_RANGE .match (r .headers .get ("Content-Range" )or "" ) 3142if r .status != 206 or not m or int (m .group (1 ))!= have or (total and int (m .group (3 ))!= total ): 3143if r .status != 200 :# another range: its bytes are not the file's; ask again from the start 3144part .unlink (missing_ok = True ) 3145raise OSError (f"the server answered another range than bytes { have } - (HTTP { r . status } )" ) 3146have = 0 # the server ignored the range and sent the whole file: start over 3147elif r .status not in (200 ,206 ): 3148raise OSError (f"HTTP { r . status } " ) 3149with open (part ,"ab" if have else "wb" )as f : 3150last = 0.0 3151while True : 3152b = r .read (8 << 20 ) 3153if not b : 3154break 3155if total and have + len (b )> total : 3156raise OSError ("the server sent more bytes than the file has" ) 3157f .write (b ) 3158have += len (b ) 3159if time .time ()- last > 2 : 3160last = time .time () 3161size = f" { have / 1e9 :6.2f } / { total / 1e9 :.2f } GB ( { 100 * have / total :.0f } %)" if total else f" { have / 1e6 :7.1f } MB" 3162f"\r { label } : { size } " ,end = "" ,flush = True ) 3163f .flush () 3164os .fsync (f .fileno ()) 3165if not total or have >= total : 3167break 3168except (OSError ,http .client .HTTPException )as e : 3169if part .exists ()and total and part .stat ().st_size > total : 3171part .unlink (missing_ok = True )# more than the file has can only be wrong bytes 3172warn (f"download interrupted ( { e } ); retrying in 10 s ..." ) 3173time .sleep (10 ) 3174 3175 3176def range_total (url :str )-> int : 3177"""The file's length from a one-byte ranged GET (Content-Range: bytes 0-0/N), for a server whose HEAD gives none 3178(ModelScope's: #1915); 0 when it does not say. With the length known the file comes over several connections.""" 3179try : 3180req = urllib .request .Request (url ,headers = {"User-Agent" :"strata-setup" ,"Range" :"bytes=0-0" }) 3181with _urlopen (req ,timeout = netpolicy .RETRY_CONNECT_S )as r : 3182m = re .match (r"\s*bytes 0-0/(\d+)\s*$" ,r .headers .get ("Content-Range" )or "" ) 3183return int (m .group (1 ))if r .status == 206 and m else 0 3184except (OSError ,http .client .HTTPException ): 3185return 0 3186 3187 3188def download (url ,dst :Path ,what = None ): 3189"""Resumable HTTP(S) download with a progress line; `file://` and plain paths are copied (tests, mirrors). 3190A finished file gets a <name>.done mark, so a later run skips it without asking the server.""" 3191dst .parent .mkdir (parents = True ,exist_ok = True ) 3192if dst .exists ()and done (dst ): 3193ok (f" { what or dst . name } already downloaded" ) 3194return 3195pin_here = file_pin (url )if url .startswith (("http://" ,"https://" ))else None 3196if pin_here and dst .is_file ()and dst .stat ().st_size == pin_here [0 ]and not dst .with_name (dst .name + ".part" ).exists (): 3197# a file copied in by hand (or whose mark was lost) that is the pinned size: check it here, no network, so a PC with every file 3198# but no internet can start 3199say (f" checking { dst . name } (SHA-256) ..." ) 3200if _hash_file (dst ,pin_here [0 ])== pin_here [1 ]: 3201mark (dst ,f"sha256 { pin_here [ 1 ] } " ) 3202ok (f" { what or dst . name } is already here (checked)" ) 3203return 3204bad = dst .with_name (dst .name + ".bad" ) 3205if pin_here and not dst .exists ()and bad .is_file (): 3206# an earlier run kept this file as .bad (keep_bad): hash it again before anything is downloaded; if it matches the pin now it is the file 3207if bad .stat ().st_size == pin_here [0 ]and _hash_file (bad ,pin_here [0 ])== pin_here [1 ]: 3208os .replace (bad ,dst ) 3209mark (dst ,f"sha256 { pin_here [ 1 ] } " ) 3210ok (f" { what or dst . name } is already here (checked)" ) 3211return 3212acquisition .require (what or dst .name ) 3213if not url .startswith (("http://" ,"https://" )): 3214src = Path (url [7 :]if url .startswith ("file://" )else url ) 3215if not src .exists (): 3216fail (f"not found: { src } " ) 3217shutil .copyfile (src ,dst ) 3218mark (dst ) 3219ok (f" { what or dst . name } copied" ) 3220return 3221ms = ms_file (url )if model_source ()== "modelscope" else None 3222if ms is not None : 3223if reachable (ms_url (* ms ),timeout = netpolicy .FIRST_CONNECT_S ): 3224url = ms_url (* ms ) 3225else : 3226warn (f" { what or dst . name } : ModelScope does not answer; downloading it from { hf_endpoint () } " ) 3227ms = None 3228part = dst .with_name (dst .name + ".part" ) 3229total = 0 3230# the file's pinned size and SHA-256, when it has them (ModelScope's copy is checked against the same pin) 3231pin = REPO_PINS .get (ms [0 ], {}).get (ms [1 ].rsplit ("/" ,1 )[- 1 ])if ms is not None else file_pin (url ) 3232for _unpinned in range (2 ):# the size: one request under the network rule (no more 5 x 60 s in silence) 3233try : 3234req = urllib .request .Request (url ,method = "HEAD" ,headers = {"User-Agent" :"strata-setup" }) 3235with _open_net (req )as r : 3236total = int (r .headers .get ("Content-Length" ,0 )or 0 ) 3237break 3238except urllib .error .HTTPError as e : 3239if e .code == 404 and hf_unpinned (url )!= url :# the pinned revision is gone from the repository 3240if not allow_unpinned (): 3241fail (f"the pinned version of { what or dst . name } is no longer on Hugging Face" , 3242"update Strata: a newer version pins the files that are there now" ) 3243warn (f" { what or dst . name } : not at the pinned revision any more; downloading the repository's " 3244"current file (not checked against a SHA-256)" ) 3245url = hf_unpinned (url ) 3246pin = None 3247continue 3248fail (f"cannot reach { url . split ( '/' )[ 2 ] } ( { e } )" , 3249"check your internet connection and run it again" + proxy_hint ()+ source_hint (url )) 3250except tls .CertificateProblem as e :# the same answer every time: no retry 3251fail (f"cannot download from { url . split ( '/' )[ 2 ] } : its security certificate was not accepted" ,str (e )) 3252except netpolicy .NetFailure as e : 3253net_fail (e ,url ,what ) 3254except (OSError ,http .client .HTTPException )as e : 3255fail (f"cannot reach { url . split ( '/' )[ 2 ] } ( { e } )" , 3256"check your internet connection and run it again" + proxy_hint ()+ source_hint (url )) 3257if not total : 3258total = range_total (url ) 3259meta = ms_meta (* ms )if ms is not None else None 3260if not total :# published size also governs partial-file completion 3261total = pin [0 ]if pin else (meta [0 ]if meta else 0 ) 3262if pin and total and total != pin [0 ]:# not the pinned file: stop before the download, not after 3263fail (f" { what or dst . name } is { total :, } bytes on { url . split ( '/' )[ 2 ] } , not the pinned { pin [ 0 ]:, } " , 3264"update Strata (the file there has changed since this version pinned it)" ) 3265label = what or dst .name 3266if bad .is_file ()and not dst .exists ()and total : 3267try : 3268if shutil .disk_usage (dst .parent ).free < total + (1 << 30 ): 3269bad .unlink ()# no room for the new copy beside the kept one 3270say (f" Not enough free space for a new copy of { dst . name } beside the kept one ( { bad . name } ): the kept file was removed." ) 3271except OSError : 3272pass 3273conns = dl_connections () 3274fixed = pin if pin else (meta if meta is not None and meta [1 ]else None ) 3275again = (lambda :repair_download (url ,dst ,total ,label ,conns ))if total >= DL_MIN_PARALLEL and conns > 1 else None 3276if dst .exists ()and total and dst .stat ().st_size == total :# finished by an older setup (no mark yet), or stopped before the check 3277if fixed :# a file that has a fixed hash is checked, not just marked 3278verify_sha256 (dst ,* fixed ,repair = again ) 3279drop_bad (dst ) 3280else : 3281mark (dst ) 3282ok (f" { what or dst . name } already downloaded" ) 3283return 3284if not (total >= DL_MIN_PARALLEL and conns > 1 and parallel_download (url ,part ,total ,label ,conns ,dst .name )): 3285_claim_part (part ,url ) 3286download_single (url ,part ,total ,label ) 3287if total and part .stat ().st_size != total : 3288fail (f"could not finish downloading { dst . name } : { part . stat (). st_size :, } bytes on disk, the server says { total :, } " , 3289"check your internet connection and run it again (the download resumes where it stopped)" ) 3290try : 3291atomic .replace (part ,dst )# waits a moment for a virus scanner or indexer that holds the file 3292except OSError as e : 3293fail (f"cannot finish { dst . name } : { e } " ,"close any program that has the file open and run setup again" ) 3294for side in (".chunks" ,".src" ): 3295part .with_name (part .name + side ).unlink (missing_ok = True ) 3296if pin : 3297verify_sha256 (dst ,* pin ,repair = again )# the fixed hash: a wrong file is repaired, else kept as .bad and setup stops 3298drop_bad (dst ) 3299elif meta is not None and meta [1 ]: 3300verify_sha256 (dst ,meta [0 ],meta [1 ],repair = again )# ModelScope's published hash; kept in the finish mark 3301drop_bad (dst ) 3302else : 3303if ms is not None : 3304warn (f" { what or dst . name } : ModelScope publishes no SHA-256 for it: the file is not verified" ) 3305mark (dst ) 3306ok (f" { what or dst . name } downloaded" ) 3307 3308 3309def whole_shard (s :Path )-> bool : 3310"""A shard as long as its own tensor directory says (check_shards' test, without stopping setup).""" 3311sys .path .insert (0 ,str (ROOT / "tools" )) 3312from gguf_reader import GGUFFile 3313try : 3314g = GGUFFile (s ) 3315return s .stat ().st_size >= g .data_start + max ((t .offset + (t .expected_bytes ()or 0 )for t in g .tensors ), 3316default = 0 ) 3317except (OSError ,ValueError ,struct .error ): 3318return False 3319 3320 3321def mark_whole_unless_pinned (shards ,hf :str | None ,own :bool )-> None : 3322"""#173's finish mark for a file copied in by hand (it has the length its own tensor directory says), except a file with a pinned SHA-256 (#4088). 3323 3324A run that stopped between the rename of a finished .part and the end of verify_sha256 leaves a full-length shard with no mark. Marking it "whole" 3325made done() true, download() skipped it and the pinned hash was never looked at, so a shard damaged by that crash stayed in place (a deleted mark 3326was written again by the next run). For a file the pin table names, leave it unmarked: download() takes its "finished by an older setup (no mark 3327yet), or stopped before the check" path, hashes it, repairs the damaged parts and writes the finish mark itself. `own` is --gguf-dir: a person's 3328own file is not a download and is not hash-checked here either way, so it keeps the mark; so does a file the pin table does not name, and every file of a 3329family with no Hugging Face folder of its own (`hf` None: the NVFP4 families download a file list, not shards).""" 3330for s in shards : 3331if not (s .exists ()and not done (s )and whole_shard (s )): 3332continue 3333if not own and hf is not None and file_pin (hf + s .name )is not None : 3334continue 3335try : 3336mark (s ,"whole (checked against its own tensor directory)" ) 3337except OSError as e :# a read-only folder (--gguf-dir on a share): the file is still whole 3338warn (f" { s . name } is whole but its finish mark cannot be written ( { e } )" ) 3339 3340 3341SHARD_NAME = re .compile (r"-(\d{5})-of-(\d{5})\.gguf$" ) 3342 3343 3344def gguf_dir_shards (folder :Path ,fam :dict ,model :str )-> list [Path ]: 3345"""--gguf-dir's shards (#305): every -0000i-of-0000N file of the model, N read from the first shard's name as the 3346engine and tools/iq_pack.py do. The published name first; else the one first shard in the folder whose name has 3347the size in it (an upload split or named differently: -00001-of-00003, Unsloth's ...-00001-of-00004.gguf). A 3348missing shard is check_shards' error later, as before.""" 3349first = folder / model_file (fam ,model ,1 ) 3350if not first .exists (): 3351found = sorted (p for p in folder .glob ("*-00001-of-*.gguf" )if SHARD_NAME .search (p .name )) 3352# (not the files of a catalog choice with the same quant name but another layout: the v3.1 UD-IQ4_XS (four shards) is not the pinned UD-IQ4_XS (three)) 3353other = lambda p : (c := gguf_choice (p .name ))is not None and c [1 ]!= model and model_quant (c [1 ]).lower ()== model_quant (model ).lower ()# noqa: E731 3354found = [p for p in found if not other (p )] 3355mine = [p for p in found if model .lower ()in p .name .lower ()or model_quant (model ).lower ()in p .name .lower ()] 3356pick = mine if mine else found 3357if len (pick )== 1 : 3358first = pick [0 ] 3359m = SHARD_NAME .search (first .name ) 3360total = int (m .group (2 ))if m else 1 3361if not m or total < 1 : 3362return [first ] 3363stem = first .name [:m .start ()] 3364return [first .with_name ("%s-%05d-of-%05d.gguf" % (stem ,i ,total ))for i in range (1 ,total + 1 )] 3365 3366 3367# #444: the quantization in a GGUF's name (Unsloth's UD-IQ3_XXS, a K-quant's Q2_K_XL, a GSQ-RCO IQ3_S, ...) 3368GGUF_QUANT = re .compile (r"(?<![A-Za-z0-9])((?:UD-)?(?:I?Q\d+(?:_[A-Za-z0-9]+)*|BF16|F16|F32))" 3369r"(?=-\d{5}-of-\d{5}\.gguf$|\.gguf$)" ,re .I ) 3370SUPPORTED_GGUFS = ("Strata runs ISTA-DASLab's GSQ-RCO files (Qwen3.8-Flash-Next Q2_0, IQ2_XS, IQ3_XXS, IQ3_S; Swift " 3371"1.5's; the Coder's IQ1_M) and Unsloth's UD-IQ1_M, UD-Q2_0, UD-IQ2_XS, UD-Q2_K_XL, UD-IQ3_XXS, UD-Q3_K_XL, " 3372"UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 only: other GGUFs (Unsloth's UD-IQ1_S, other " 3373"K-quant files) cannot be used" ) 3374# why a GGUF of a name Strata knows is still refused (said beside SUPPORTED_GGUFS) 3375UNSUPPORTED_WHY = {"UD-IQ1_S" :"UD-IQ1_S mixes two expert formats in one layer, which Strata cannot load; UD-IQ1_M is the 1-bit choice" } 3376 3377 3378def gguf_unsupported (name :str )-> str | None : 3379"""#444: the quantization a GGUF's name says, when it is one Strata cannot run (not a setup size); else None.""" 3380m = GGUF_QUANT .search (name ) 3381return m .group (1 )if m and m .group (1 ).upper ()not in MODELS and not name .lower ().startswith ("mmproj" )else None 3382 3383 3384def gguf_choice (name :str )-> tuple | None : 3385"""#444: (--family, --model) whose published first shard this file is, or None (the Coder's IQ1_M is named like 3386the original's sizes: the size tells them apart).""" 3387for f ,d in FAMILIES .items (): 3388if d .get ("ready" ):# ready-made packs (NVFP4): no GGUF shards to match 3389continue 3390for m in MODELS : 3391if f in MODELS [m ].get ("families" , ("qwen" ,"swift" ))and name == model_file (d ,m ,1 ): 3392return f ,m 3393return None 3394 3395 3396def gguf_dir_problem (folder :Path ,first :Path ,fam :dict ,model :str )-> tuple | None : 3397"""#444: (message, hint) when --gguf-dir has no file setup can use for this choice: the chosen shard is a GGUF 3398Strata cannot run (Unsloth's UD-IQ3_XXS taken for IQ3_XXS by its name), or it is missing and the folder holds 3399other GGUFs - then the hint names the --family/--model of the usable ones. None otherwise (a missing shard in a 3400folder without GGUFs stays check_shards' "missing").""" 3401bad = gguf_unsupported (first .name )if first .exists ()else None 3402if bad : 3403why = UNSUPPORTED_WHY .get (bad .upper ()) 3404return f" { first . name } is { bad } , a GGUF Strata cannot run" ,SUPPORTED_GGUFS + (".\n " + why if why else "" ) 3405if first .exists (): 3406return None 3407firsts = sorted (p .name for p in folder .glob ("*.gguf" ) 3408if not p .name .lower ().startswith ("mmproj" )and (not SHARD_NAME .search (p .name ) 3409or SHARD_NAME .search (p .name ).group (1 )== "00001" )) 3410usable = list (dict .fromkeys (c for c in map (gguf_choice ,firsts )if c )) 3411unusable = [n for n in firsts if gguf_unsupported (n )] 3412if not usable and not unusable : 3413return None 3414hint = SUPPORTED_GGUFS 3415if unusable : 3416hint += ".\n Not usable here: " + ", " .join (unusable ) 3417for q in dict .fromkeys (gguf_unsupported (n )for n in unusable ): 3418if q and q .upper ()in UNSUPPORTED_WHY : 3419hint += ".\n " + UNSUPPORTED_WHY [q .upper ()] 3420if usable : 3421hint += ".\n Usable here: " + ", " .join (f"--family { f } --model { m } " for f ,m in usable ) 3422return f" { folder } has no { fam [ 'title' ] } { model } file" ,hint 3423 3424 3425def _hash_file (s :Path ,size :int )-> str : 3426h = hashlib .sha256 () 3427seen ,last = 0 ,0.0 3428with open (s ,"rb" )as f : 3429while True : 3430b = f .read (16 << 20 ) 3431if not b : 3432break 3433h .update (b ) 3434seen += len (b ) 3435if time .time ()- last > 2 and size >= (1 << 30 ):# a figure for the app and the Terminal: hashing 60 GB takes minutes 3436last = time .time () 3437f"\r checking { s . name } : { seen / 1e9 :6.2f } / { size / 1e9 :.2f } GB ( { 100 * seen // size } %) " ,end = "" ,flush = True ) 3438if seen >= (1 << 30 ): 3439return h .hexdigest () 3441 3442 3443def own_gguf_is_whole (path :Path )-> bool : 3444"""The person's own GGUF reads as a whole file: its header parses and every tensor lies inside the file (a cut-short copy fails this).""" 3445try : 3446from strata_control import gguf_preflight 3447gguf_preflight .inspect_metadata (Path (path )) 3448return True 3449except Exception :# noqa: BLE001 - anything unreadable is "not whole" 3450return False 3451 3452 3453def keep_bad (s :Path )-> Path | None : 3454"""A downloaded file whose SHA-256 is not the pinned one is not deleted: it is renamed to <name>.bad (no finish mark), so a wrong check, a pin that 3455is out of date or a bad read costs one more hash and not another 50 GB download. The next run of download() hashes the .bad file again and takes it 3456back when it now matches; a successful new download of the file, or too little free space for it, removes the .bad file (drop_bad). 3457Returns the .bad path, or None when the file could not be renamed (it is then deleted, as before).""" 3458bad = s .with_name (s .name + ".bad" ) 3459try : 3460bad .unlink (missing_ok = True )# at most one .bad per file 3461os .replace (s ,bad ) 3462return bad 3463except OSError : 3464s .unlink (missing_ok = True ) 3465return None 3466 3467 3468def drop_bad (dst :Path )-> None : 3469"""The .bad copy of `dst` is not needed any more: a good file is in place.""" 3470try : 3471dst .with_name (dst .name + ".bad" ).unlink (missing_ok = True ) 3472except OSError : 3473pass 3474 3475 3476def verify_sha256 (s :Path ,size :int ,sha :str ,own :bool = False ,repair = None ,also :tuple = ())-> None : 3477"""A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark, 3478so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again. 3479`repair` (a downloaded file's own re-reader, see repair_download): the wrong file is first compared with the server 3480piece by piece and only the damaged pieces are written again, then it is checked a second time. 3481`also`: other SHA-256 values that are the same file for Strata's purposes.""" 3482m = s .with_name (s .name + ".done" ) 3483kept = mark_text (s ) 3484if kept is not None and any (f"sha256 { x } " in kept for x in (sha ,* also )): 3485return 3486have = s .stat ().st_size if s .exists ()else - 1 3487if own and have > 0 and have != size and own_gguf_is_whole (s ): 3488# a fine-tune or another build with the layout of the published file (#3777: 96 bytes apart): recommend, never refuse 3489warn (f" { s . name } is { have :, } bytes; the published file is { size :, } . It is a complete GGUF file, so Strata uses it as it is; " 3490"it may be another version or a fine-tune, so check a few answers before you rely on it" ) 3491return 3492if have != size : 3493if own :# --gguf-dir: the person's own file is never deleted by setup 3494fail (f" { s . name } is { have :, } bytes; the published file is { size :, } " , 3495"it may be cut short or another version; your file was left as it is. Copy the whole published file into the folder" ) 3496fail (f" { s . name } is { have :, } bytes, not { size :, } " ,"delete it and run setup again (the download restarts)" ) 3497say (f" checking { s . name } (SHA-256, { size / 1e9 :.1f } GB) ..." ) 3498digest = _hash_file (s ,size ) 3499server_same = False # the repair read the whole file from the server and found no block that differs 3500if digest != sha and repair is not None and not own : 3501say (f" Some parts of { s . name } were damaged; downloading only those parts again." ) 3502res = repair () 3503server_same = res is not None and res [0 ]== 0 3504if res is not None : 3505say (f" { res [ 0 ] } of { res [ 1 ] } parts were different and have been written again; checking the whole file again ..." ) 3506digest = _hash_file (s ,size ) 3507else : 3508say (" The damaged parts could not be found this way." ) 3509if digest != sha and digest in also : 3510say (f" { s . name } is the converted version ISTA-DASLab published on 2026-10-27 (the same tables in one tensor); it is used as it is" ) 3511mark (s ,f"sha256 { digest } " ) 3512return 3513if digest != sha : 3514if own and own_gguf_is_whole (s ): 3515warn (f" { s . name } is not the published file (SHA-256 { digest [: 12 ] } ..., expected { sha [: 12 ] } ...) but it is a complete GGUF file, so " 3516"Strata uses it as it is; it may be another version or a fine-tune, so check a few answers before you rely on it" ) 3517return 3518if own : 3519fail (f" { s . name } does not match the published file (SHA-256 { digest } , expected { sha } )" , 3520"it may be damaged or another version; your file was left as it is. Copy the whole published file into the folder" ) 3521keep_bad (s )# kept as <name>.bad, not thrown away (see keep_bad) 3522m .unlink (missing_ok = True ) 3523if server_same : 3524hint = ("the server sends exactly the bytes you have (every block was compared), so the file there is not the version this Strata pins: " 3525"update Strata. Run setup again to check the kept file once more" ) 3526else : 3527hint = "run setup again: the kept file is checked once more, and if it still differs it is downloaded again and the kept one is removed" 3528fail (f" { s . name } does not match the pinned SHA-256 (it is { digest } , Strata expects { sha } ); the file was kept as { s . name } .bad" ,hint ) 3529mark (s ,f"sha256 { sha } " ) 3530 3531 3532def ready_files (model :str )-> list : 3533"""A ready-made pack's files (NVFP4_REPOS): (role, repo, revision, path, bytes, sha256) each.""" 3534repo = MODELS [model ]["repo" ] 3535t = NVFP4_REPOS [repo ] 3536return [(role ,repo ,t ["revision" ],path ,size ,sha )for path , (role ,size ,sha )in t ["files" ].items ()] 3537 3538 3539def ready_needed (model :str ,models_dir :Path )-> list : 3540"""ready_files without the checkpoint's tensors once a prepared model (MODELS[..]["prepare"]) is prepared: the 3541engine reads the prepared files only, so the ~95 GB of safetensors need not stay (or come back) on the disk.""" 3542files = ready_files (model ) 3543if MODELS [model ].get ("prepare" )and prepared_done (model ,models_dir ): 3544files = [f for f in files if not f [3 ].startswith ("tensors/" )] 3545return files 3546 3547 3548def ready_where (models_dir :Path ,f )-> Path : 3549"""Where one of them goes: <models>/<owner>--<repo>/<its path in the repository> (the repository's layout, so the 3550pack folder is whole as the engine reads it).""" 3551return Path (models_dir )/ f [1 ].replace ("/" ,"--" )/ f [3 ] 3552 3553 3554def prepared_dir (model :str ,models_dir :Path )-> Path : 3555"""Where a model that is prepared on this PC (MODELS[..]["prepare"]) keeps what it prepared.""" 3556return Path (models_dir )/ MODELS [model ]["repo" ].replace ("/" ,"--" )/ FP4LOCAL_PREPARED 3557 3558 3559def prepared_done (model :str ,models_dir :Path )-> bool : 3560"""Every step of tools/nvfp4_local_pack.py prepare is marked done (its marks, written when each step is whole).""" 3561d = prepared_dir (model ,models_dir ) 3562return all ((d / m ).is_file ()for m in ("ple-nvfp4.gguf.done" ,"dense.gguf.done" ,"pack.done" ,"draft.done" )) 3563 3564 3565def ready_paths (model :str ,models_dir :Path )-> dict : 3566"""What the engine is given: the pack folder and the dense, PLE and embedding GGUFs (a prepared model also has its 3567own draft layer, "mtp", and no separate embedding: the token embedding is in its dense GGUF).""" 3568if MODELS [model ].get ("prepare" ): 3569d = prepared_dir (model ,models_dir ) 3570return {"pack" :d / "pack" ,"dense" :d / "dense.gguf" ,"ple" :d / "ple-nvfp4.gguf" ,"mtp" :d / "mtp" } 3571out = {} 3572for f in ready_files (model ): 3573p = ready_where (models_dir ,f ) 3574if f [0 ]== "pack" and p .name == "index.txt" : 3575out ["pack" ]= p .parent 3576elif f [0 ]in ("dense" ,"ple" ,"embd" ): 3577out [f [0 ]]= p 3578return out 3579 3580 3581def ready_verified (p :Path ,sha :str )-> bool : 3582"""Downloaded whole and checked: its finish mark holds the pinned SHA-256 (verify_sha256).""" 3583try : 3584return p .is_file ()and f"sha256 { sha } " in (mark_text (p )or "" ) 3585except OSError : 3586return False 3587 3588 3589def ready_fetch (model :str ,models_dir :Path )-> None : 3590"""Every file of a ready-made pack: already here and checked; the same file (by SHA-256) checked for another 3591ready-made pack, linked instead of downloaded (the PLE table and the embedding); or downloaded from its pinned 3592revision and checked against its size and SHA-256 (a wrong file is deleted and setup stops).""" 3593others = [(ready_where (models_dir ,g ),g [5 ])for m in MODELS if MODELS [m ].get ("repo" )for g in ready_files (m )] 3594for f in ready_needed (model ,models_dir ): 3595dst ,size ,sha = ready_where (models_dir ,f ),f [4 ],f [5 ] 3596if ready_verified (dst ,sha ): 3597ok (f" { f [ 3 ] } already downloaded" ) 3598continue 3599src = next ((p for p ,s in others if s == sha and p != dst and ready_verified (p ,s )),None ) 3600if src is not None and not dst .exists (): 3601try : 3602dst .parent .mkdir (parents = True ,exist_ok = True ) 3603os .link (src ,dst ) 3604mark (dst ,f"sha256 { sha } " ) 3605ok (f" { f [ 3 ] } : the same file as { src } (linked, not downloaded again)" ) 3606continue 3607except OSError : 3608pass # another drive: downloaded 3609download (f" { hf_endpoint () } / { f [ 1 ] } /resolve/ { f [ 2 ] } / { f [ 3 ] } " ,dst ,f" { f [ 1 ]. split ( '/' )[ - 1 ] } : { f [ 3 ] } " ) 3610verify_sha256 (dst ,size ,sha ) 3611 3612 3613def resident_budget_gib (model ,ram ,kv_ram_gb = 0.0 )-> int : 3614"""UD-Q4_K_XL: the GiB of experts the engine keeps in RAM (--resident-budget-gib): the RAM (GiB, ram_gb()) less 361524 for the OS, the engine and the file cache the other experts are read through, less a KV cache streamed to 3616RAM; at most all of them, at least 8. 64 GB: 40, the measured setting (docs/UNSLOTH_Q4.md).""" 3617gib = round (ram )- UNSLOTH_RAM_LEFT_GB - math .ceil (kv_ram_gb ) 3618return max (8 ,min (gib ,int (MODELS [model ]["arena_gb" ]/ 1.073741824 ))) 3619 3620 3621# MODEL-UPDATE Phase 2: Unsloth's files keep every expert in RAM (a pinned arena, as ISTA's files do) where the experts 3622# and this much more fit the PC's RAM; the RAM budget (--resident-budget-gib: the hottest experts in RAM, the rest read 3623# from the GGUF in place) only below that. The rule and the 16 GiB are sergqwer's fork (sergqwer/strata-nvfp4, 3624# 0.1.42-nvfp4.2, MIT): there, on 128 GB with an RTX 5090, UD-Q4_K_XL decoded at 169 tokens/s and read a 32K prompt in 3625# 4.9 s with every expert in RAM, against 118 tokens/s and 30 s in the budget mode. 3626UNSLOTH_RESIDENT_BESIDE_GB = 16 3627 3628 3629def unsloth_budget (model ,ram ,gpu = None ,asked = None )-> bool : 3630"""Does setup write the RAM-budget mode (--resident-budget-gib) for this Unsloth file: asked for (--resident-budget-gib 3631N), a unified-memory APU (#1715: there the budget and the GPU's cache are the same RAM, and the all-in-RAM mode was 3632measured on discrete cards only), or its experts with UNSLOTH_RESIDENT_BESIDE_GB beside them do not fit this PC's RAM 3633(GiB, ram_gb()). Else every expert is kept in RAM, as for ISTA's files. 3634Round 0214: a unified-memory APU keeps the budget mode (above) except for a set that says "uma_pool_auto" (Unsloth's v3.1 sets) whose experts fit 3635the GPU's shared pool whole (uma_holds_experts): there every expert is in the pool, the cache is `auto` and nothing is pinned. The fixed cache and 3636the pinned RAM part the budget mode wrote for them (367 slots + 35 GiB on a 64 GB Strix Halo) failed the first launch of UD-IQ2_XS three times of three 3637("prefill: the token id buffer (unspecified launch failure)" right after pinning); `--expert-cache auto` with nothing pinned passed (ENG-AMD).""" 3638return asked is not None or (bool ((gpu or {}).get ("uma" ))and not uma_holds_experts (model ,ram ,gpu ))or \ 3639ram < MODELS [model ]["arena_gb" ]/ 1.073741824 + UNSLOTH_RESIDENT_BESIDE_GB 3640 3641 3642def uma_holds_experts (model ,ram ,gpu )-> bool : 3643"""A unified-memory GPU whose shared pool holds every expert of `model` beside everything else the engine keeps there (strata_control/uma_pool.py: the 3644measured fixed part, the experts, a margin) and whose RAM holds them with UNSLOTH_RESIDENT_BESIDE_GB more. Only for a set that asks ("uma_pool_auto"): 3645the sets measured under the budget mode (UD-IQ4_XS, UD-Q4_K_XL, ...) keep their plans.""" 3646if sys .platform == "darwin" or not MODELS .get (model , {}).get ("uma_pool_auto" )or not (gpu or {}).get ("uma" ): 3647return False # (a Mac never reaches this: metal/setup_mac.py and mac_control_setup have their own plans; the check keeps it so) 3648shared = float ((gpu or {}).get ("vram_gb" )or 0.0 ) 3649if shared <= 0 : 3650return False 3651from strata_control import uma_pool 3652arena_gib = MODELS [model ]["arena_gb" ]/ 1.073741824 3653return (uma_pool .FIXED_GIB + arena_gib + uma_pool .MARGIN_GIB <= uma_pool .pool_gib (shared ) 3654and ram >= arena_gib + UNSLOTH_RESIDENT_BESIDE_GB ) 3655 3656 3657def images_default (model ,family ,ram ,gpu = None )-> bool : 3658"""Is "images on" setup's default answer (the question's Enter, and --yes) for this choice? Owner rule 2026-10-18: pictures are on 3659wherever the model can read them - the original Flash-Next, Swift and Coder files, Unsloth's, NVFP4 - on every make of card; which 3660reader runs is strata_control/vision_reader.py's rule (the CPU under 24 GB of VRAM, the GPU from 24 GB). The CPU reader takes no 3661VRAM (no --vram-reserve-mib), so a small card is no exception.""" 3662return MODELS .get (model , {}).get ("vision" ,FAMILIES .get (family , {}).get ("vision" ))is not False 3663 3664 3665unsloth_images_default = images_default # the earlier name 3666 3667 3668IMAGES_GPU_ENCODER_MIN_VRAM_GB = 23.5 # = strata_control/vision_reader.py GPU_MIN_VRAM_GB, the one place for the rule; #2406: below this the images answer "yes" gets the CPU encoder (a card of 12-16 GB: the GPU 3669# encoder's ~1.1-1.4 GB is ~850 expert slots lost, 3-5% of decode and prompt on P100 / A4000 3670# 16 GB (Linux, IQ3_S / IQ3_XXS), and 35-60% on an RTX 4080 SUPER under Windows as reported) 3671 3672 3673def flash_vision_encoder (asked :str ,gpu :dict )-> str : 3674"""#2406: which encoder a Flash-Next images answer gets on NVIDIA. "yes" (the question's y, or --vision yes) means the 3675GPU encoder on a card of 24 GB and more and the CPU encoder below that: a picture then takes a few seconds, the text 3676keeps the ~1 GB of VRAM for experts. --vision gpu is always kept (with a note on a small card); --vision cpu is kept.""" 3677vram = float ((gpu or {}).get ("vram_gb" )or 0.0 ) 3678small = 0 < vram < IMAGES_GPU_ENCODER_MIN_VRAM_GB 3679if asked == "gpu" and small : 3680warn (f"the GPU image encoder keeps ~1.4 GB of VRAM that a { vram :.0f } GB card would use for experts (measured 3-5% " 3681"of decode on 16 GB cards, more on some Windows PCs, #2406): kept as you chose; --vision cpu reads pictures " 3682"on the CPU instead (a few seconds each)" ) 3683if asked == "yes" : 3684return "cpu" if small else "gpu" 3685return asked 3686 3687 3688UMA_EXPERTS = 24576 # the Flash-Next model's experts (48 layers x 512): the most an expert cache can hold 3689 3690 3691def uma_expert_cache (model ,ram ,budget_gib ,kv_ram_gb = 0.0 ): 3692"""#1715: on a unified-memory APU (Strix Halo) the GPU's expert cache and the RAM budget of experts are both RAM. 3693`--expert-cache auto` sizes the cache from the memory the OS can give back at start, which counts all the RAM the 3694budget has not taken yet: a 128 GB box with a 55 GiB budget and the desktop open was killed by the OOM killer. So 3695there setup writes a number, not `auto`: the RAM less UNSLOTH_RAM_LEFT_GB less the budget (and a KV cache streamed 3696to RAM), in slots (an expert is priced at 1.1x the average one: the Q8_0 downs are bigger). None when no room is left 3697(the config keeps `auto`). A recommendation: the number is in the config's args, and --expert-cache N there sets it.""" 3698slot_gib = MODELS [model ]["arena_gb" ]* 1e9 / UMA_EXPERTS * 1.1 / 2 ** 30 3699room = ram - UNSLOTH_RAM_LEFT_GB - budget_gib - math .ceil (kv_ram_gb ) 3700slots = min (UMA_EXPERTS ,int (room / slot_gib )) 3701return slots if slots >= 256 else None 3702 3703 3704def uma_cache_guard (cfg :dict ,model :str ,gpu :dict )-> None : 3705"""A Strix Halo: a numeric --expert-cache the person fixed (kept from their earlier config, or given by hand) beside setup's RAM budget. The 3706cache and the pinned RAM part draw on one pool, the pinned part twice (strata_control/uma_pool.py); a smaller cache with the budget unchanged ended 3707the engine with exit code 1 and no message (STRIX-2Q, 2026-11-01). The cache is the person's and stays; the budget, when it is setup's own, is 3708lowered to what the pool holds, and a budget the person set too is only warned about (recommend, never force).""" 3709try : 3710from strata_control import uma_pool 3711args = cfg .get ("args" ) 3712fixed = uma_pool .fixed_cache_and_budget (args )if gpu .get ("uma" )and isinstance (args ,list )else None 3713if fixed is None : 3714return 3715cache ,budget = fixed 3716arena = MODELS [model ]["arena_gb" ] 3717shared = float (gpu .get ("vram_gb" )or 0.0 ) 3718if shared <= 0 or not uma_pool .too_much (cache ,budget ,arena ,shared ): 3719return 3720fit = uma_pool .safe_budget_gib (cache ,arena ,shared ) 3721own = "--resident-budget-gib" in user_args .flat (user_args .groups (cfg .get (user_args .USER_KEY ))) 3722if fit >= budget : 3723return 3724if own : 3725warn (f"your expert cache of { cache } slots and your { budget :g } GiB RAM budget may need more of this PC's shared graphics memory than it has " 3726f"(the graphics chip uses the RAM, and the RAM part counts twice): the engine can stop at the start with no message. About { fit :g } GiB " 3727f"of budget fits that cache; kept as you chose (--resident-budget-gib in the config's user_args)" ) 3728return 3729args [args .index ("--resident-budget-gib" )+ 1 ]= f" { fit :g } " 3730warn (f"the expert cache is fixed at { cache } slots, so the RAM budget is { fit :g } GiB instead of { budget :g } : this PC's graphics chip shares the RAM, " 3731f"and with a { budget :g } GiB budget the engine would run the shared memory out and stop at the start. " 3732"--resident-budget-gib N in the config's args sets it, or --expert-cache auto lets the engine balance both" ) 3733except Exception as e :# noqa: BLE001 - a recommendation, never a reason to stop setup 3734say (f" (the expert cache and RAM budget were not compared: { e } )" ) 3735 3736 3737def budget_choice (model ,ram ,asked )-> float : 3738"""S4: UD-Q4_K_XL's RAM budget: --resident-budget-gib N as given, else the recommendation (resident_budget_gib). 3739More than the recommendation is kept, with what it risks (the owner's rule: setup recommends, it never forces).""" 3740rec = resident_budget_gib (model ,ram ) 3741if asked is None : 3742return rec 3743if asked > rec : 3744warn (f"a { asked :g } GiB RAM budget is more than setup recommends for this PC ( { rec } GiB: the RAM less " 3745f" { UNSLOTH_RAM_LEFT_GB } GB for the OS, the engine and the file cache that reads the other experts). Kept " 3746"as you chose: the engine clamps it to the RAM it finds free at start (less 4 GB), and the file cache " 3747"gets less room - it may be slower, or run the PC out of RAM under load" ) 3748return int (asked )if asked == int (asked )else asked 3749 3750 3751def check_shards (shards ): 3752"""Every shard present and whole, or setup stops naming the file and the numbers. Whole means as long as 3753its own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part 3754renamed by hand, a download finished by an older setup) otherwise passes as a model file and the engine 3755fails much later, at the first tensor that runs past the end.""" 3756sys .path .insert (0 ,str (ROOT / "tools" )) 3757from gguf_reader import GGUFFile 3758for s in shards : 3759if not s .exists (): 3760fail (f"missing { s } " ) 3761try : 3762g = GGUFFile (s ) 3763except (ValueError ,struct .error )as e : 3764fail (f" { s . name } is not a whole GGUF shard ( { e } )" ,"delete it and run setup again" ) 3765need = g .data_start + max ((t .offset + (t .expected_bytes ()or 0 )for t in g .tensors ),default = 0 ) 3766have = s .stat ().st_size 3767if not g .tensors : 3768# #2346: a metadata-only shard (Unsloth's UD-Q5_K_XL 00001, 10,946,618 bytes) ends at its header: the 3769# alignment padding before an empty data section is not in the file, so data_start can be past its end 3770need = min (need ,have ) 3771if have < need : 3772fail (f" { s . name } is short: { have :, } of { need :, } bytes ( { need - have :, } missing)" , 3773"delete it and run setup again (or copy the whole file into --gguf-dir)" ) 3774if len (g .tensors )== 1 and have - need >= 64 :# (a few bytes may be the last tensor's alignment padding) 3775# #657: a shard that holds one tensor (the PLE table) is exactly as long as that tensor; extra bytes are a 3776# damaged or wrong file that the engine would refuse at start ("PLE table size mismatch") 3777fail (f" { s . name } is longer than its tensor: { have :, } bytes, { need :, } expected ( { have - need :, } extra)" , 3778f"delete { s . name } and its .done mark and run setup again" ) 3779 3780 3781#: gguf-py and llama.cpp's HF converter, vendored at the llama.cpp pin (third_party/strata-gguf-py/UPSTREAM.md): the preparation tools import 3782#: them, so no llama.cpp download is needed to pack a model. The Terminal and Control packages carry this folder (packaging/package_terminal.py). 3783VENDORED_GGUF_PY = ROOT / "third_party" / "strata-gguf-py" 3784#: the llama.cpp sources strata-vision builds (llama, mtmd, the whole ggml), vendored at the same pin (third_party/strata-llama/UPSTREAM.md); phase 3 deletes it 3785VENDORED_LLAMA = ROOT / "third_party" / "strata-llama" 3786 3787 3788def gguf_py_dir ()-> Path : 3789"""The folder that holds llama.cpp's `gguf` package: STRATA_GGUF_PY=<folder> (an override, kept for two releases), else the vendored copy. 3790The preparation tools read and write GGUF with their own tools/strata_gguf.py and no longer need it; only llama.cpp's HF converter 3791(NVFP4-local) imports it, and tools/_paths.py finds the vendored copy for that.""" 3792own = os .environ .get ("STRATA_GGUF_PY" ) 3793if own and (Path (own )/ "gguf" ).is_dir (): 3794return Path (own ) 3795return VENDORED_GGUF_PY 3796 3797 3798def gguf_py_env ()-> dict : 3799"""The environment the preparation tools get for the GGUF library: STRATA_GGUF_PY only when the user named a gguf-py folder (then the tools 3800use llama.cpp's gguf-py instead of tools/strata_gguf.py); empty by default, so the tools use their own.""" 3801own = os .environ .get ("STRATA_GGUF_PY" ) 3802return {"STRATA_GGUF_PY" :str (gguf_py_dir ())}if own and (Path (own )/ "gguf" ).is_dir ()else {} 3803 3804 3805def llama_override (): 3806"""A llama.cpp checkout named by STRATA_GGML_DIR (an override of the vendored ggml, kept for two releases), else None: the engine then builds 3807from third_party/strata-ggml and nothing is downloaded.""" 3808own = os .environ .get ("STRATA_GGML_DIR" ) 3809return Path (own )if own and (Path (own )/ "ggml" / "CMakeLists.txt" ).exists ()else None 3810 3811 3812def ggml_defs (llama )-> list : 3813"""The CMake definition that points an engine build at a llama.cpp checkout: only for the override; the vendored tree is the default.""" 3814return [f"-DSTRATA_GGML_DIR= { llama } " ]if llama else [] 3815 3816 3817def vision_llama (llama )-> Path : 3818"""The llama.cpp tree strata-vision builds from: the override (STRATA_GGML_DIR), else the vendored third_party/strata-llama.""" 3819return Path (llama )if llama else VENDORED_LLAMA 3820 3821 3822def llama_cpp_if_here (): 3823"""The llama.cpp override tree (None by default). The preparation tools have their own GGUF code, so nothing is fetched to prepare a model.""" 3824if (gguf_py_dir ()/ "gguf" ).is_dir (): 3825ok (f"llama.cpp { LLAMA_CPP_COMMIT [: 7 ] } (gguf-py for the preparation tools)" ) 3826return llama_override () 3827 3828 3829def get_llama_cpp (): 3830"""Kept for callers that still name it: the llama.cpp override tree (STRATA_GGML_DIR) or None. Nothing is downloaded any more.""" 3831return llama_override () 3832 3833 3834def req_name (line :str )-> str : 3835"""The distribution name of a requirement line ("numpy==2.5.3; python_version >= '3.12'" -> "numpy").""" 3836return re .split (r"[\s<>=!~;\[]" ,line .strip (),maxsplit = 1 )[0 ].lower ().replace ("_" ,"-" ) 3837 3838 3839def requirement_lines (path :Path | None = None )-> list [str ]: 3840"""A requirements file's requirements, comments and blank lines left out.""" 3841lines = [] 3842for raw in (path or REQUIREMENTS ).read_text (encoding = "utf-8" ).splitlines (): 3843line = raw .split ("#" ,1 )[0 ].strip () 3844if line : 3845lines .append (line ) 3846return lines 3847 3848 3849MONITOR_REQUIREMENTS = ROOT / "requirements-monitor.txt" 3850 3851 3852def runtime_packages ()-> list [str ]: 3853"""The packages setup installs for a run: the pinned runtime ones, plus the Terminal's screens (textual, which brings rich: `strata launch` 3854and `strata monitor` need them; the packaged Terminal bundles them, a source install gets them here).""" 3855base = requirement_lines ()if REQUIREMENTS .exists ()else list (PY_PACKAGES ) 3856if MONITOR_REQUIREMENTS .exists (): 3857base += [r for r in requirement_lines (MONITOR_REQUIREMENTS )if r not in base ] 3858return base 3859 3860 3861def _installed (name :str )-> bool : 3862try : 3863import importlib .metadata as md 3864md .distribution (name ) 3865return True 3866except Exception : 3867return False 3868 3869 3870def control_missing_packages ()-> list : 3871"""The Python packages the preparation tools need that this interpreter does not have (the app bundle has them all).""" 3872import importlib .util 3873return [m for m in ("numpy" ,"jinja2" ,"regex" ,"yaml" ,"tqdm" ,"requests" ,"PIL" ,"psutil" ) 3874if importlib .util .find_spec (m )is None ] 3875 3876 3877def pip_stamp_is_ours (stamp :Path )-> bool : 3878"""The list of installed packages was written for THIS system (#3634). A .venv on a disk that Windows and Linux both start from keeps 3879the stamp of the other one, which then says "already installed" about packages this Python does not have. A marker beside the stamp 3880names the system that wrote it; an older stamp without a marker is believed only while the packages every run needs can be imported.""" 3881marker = stamp .with_name (stamp .name + ".os" ) 3882try : 3883if marker .exists (): 3884return marker .read_text (encoding = "utf-8" ).strip ()== sys .platform 3885except OSError : 3886return False 3887import importlib .util 3888return all (importlib .util .find_spec (m )is not None for m in ("numpy" ,"jinja2" ,"regex" ,"yaml" )) 3889 3890 3891def pip_install (packages ,what ,extra = ()): 3892"""pip install into .venv, skipped when the same list was installed before. An install from before the pinned 3893requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the 3894pinned dependencies it already has count as installed.""" 3895if CONTROL :# the app ships these (hash-locked); nothing is installed here 3896missing = control_missing_packages () 3897if missing : 3898fail ("this copy of Strata Control lacks " + ", " .join (missing ),"reinstall the Strata app" ) 3899ok (f" { what } : bundled with the app" ) 3900return 3901stamp = Path (sys .prefix )/ ".strata-pip.json" 3902have = json .loads (stamp .read_text (encoding = "utf-8" ))if stamp .exists ()and pip_stamp_is_ours (stamp )else [] 3903bare = {p .lower ()for p in have if req_name (p )== p .lower ()} 3904need = [p for p in packages if p not in have and req_name (p )not in bare 3905and not (bare and "==" in p and _installed (req_name (p )))] 3906if not need : 3907ok (f" { what } already installed" ) 3908return 3909acquisition .require (what ) 3910say (f" Installing { what } ..." ) 3911run ([sys .executable ,"-m" ,"pip" ,"install" ,"--quiet" ,"--disable-pip-version-check" ,* extra ,* need ]) 3912stamp .write_text (json .dumps (sorted (set (have )| set (need )),indent = 0 )) 3913stamp .with_name (stamp .name + ".os" ).write_text (sys .platform ,encoding = "utf-8" ) 3914ok (f" { what } installed" ) 3915 3916 3917NVFP4_LOCAL_REQUIREMENTS = ROOT / "requirements-nvfp4-local.txt" 3918NVFP4_LOCAL_MODULES = ("torch" ,"transformers" ,"safetensors" ) 3919 3920 3921def nvfp4_local_packages ()-> list : 3922"""The pinned lines of requirements-nvfp4-local.txt (comments and options left out).""" 3923try : 3924lines = NVFP4_LOCAL_REQUIREMENTS .read_text (encoding = "utf-8" ).splitlines () 3925except OSError : 3926return [] 3927return [l .split ("#" )[0 ].strip ()for l in lines if l .strip ()and not l .lstrip ().startswith (("#" ,"-" ))] 3928 3929 3930def ensure_nvfp4_local_packages ()-> None : 3931"""#3227: NVIDIA's FP4-Local checkpoint is converted on this PC with llama.cpp's converter, which imports torch and transformers 3932(the runtime requirements do not have them: nothing else in setup needs them). Installed only for a prepare that runs; what is 3933already there is kept. The app does not ship them (hundreds of MB): it says so and points at the source installer.""" 3934import importlib .util 3935missing = [m for m in NVFP4_LOCAL_MODULES if importlib .util .find_spec (m )is None ] 3936if not missing : 3937return 3938if CONTROL : 3939fail ("preparing NVIDIA's FP4-Local checkpoint needs PyTorch and transformers, which the app does not include" , 3940"install this model from the source download (SETUP.bat on Windows, ./setup.sh on Linux), or pick another version in the app" ) 3941pkgs = nvfp4_local_packages () 3942if not pkgs : 3943fail ("requirements-nvfp4-local.txt is missing" ,"update Strata, or run: python -m pip install torch transformers safetensors" ) 3944say (" Converting NVIDIA's checkpoint needs PyTorch, transformers and safetensors (a few hundred MB, installed once)." ) 3945pip_install (pkgs ,"PyTorch, transformers and safetensors (for the FP4-Local conversion)" , 3946extra = []if WIN else ["--extra-index-url" ,"https://download.pytorch.org/whl/cpu" ])# Linux: the CPU build, not 3 GB of CUDA libraries 3947importlib .invalidate_caches () 3948 3949 3950def cuda_lib_dirs (toolkit = 13 ): 3951"""Where pip put NVIDIA's CUDA libraries (nvidia/cu13/bin/x86_64 on Windows, nvidia/cu13/lib on Linux). 3952toolkit 12: the CUDA 12 wheels' cuBLAS and runtime, in two folders (nvidia/cublas/bin, nvidia/cuda_runtime/bin).""" 3953if int (toolkit )== 12 : 3954patterns = ("cublas64_12.dll" ,"cudart64_12.dll" )if WIN else ("libcublas.so.12*" ,"libcudart.so.12*" ) 3955else : 3956patterns = ("cublas64_13.dll" ,)if WIN else ("libcublas.so.13*" ,) 3957dirs = [] 3958for sp in {Path (p )for p in sys .path if p .endswith ("site-packages" )}: 3959for pattern in patterns : 3960for hit in (sp / "nvidia" ).rglob (pattern )if (sp / "nvidia" ).is_dir ()else []: 3961if hit .parent not in dirs : 3962dirs .append (hit .parent ) 3963return [str (d )for d in dirs ] 3964 3965 3966# ------------------------------------------------------------------------------------------------ AMD 3967# The RX 7900 XT / XTX (gfx1100) and the RX 9070 series / Radeon AI PRO R9700 (gfx1201) on Linux, through the HIP 3968# backend (docs/AMD_HIP.md); the RX 7800 XT / 7700 XT (gfx1101, #254) and the RX 9060 XT (gfx1200, #256) were run by 3969# their owners; the RX 6800 / 6900 series (gfx1030, #311) and the RX 6700 XT (gfx1031, #524) run but are unvalidated. There is no ready-made AMD engine: ROCm comes from AMD's TheRock Python wheels into .venv (no sudo; 3970# a system ROCm 7 in /opt/rocm is used when it has hipcc and hipBLAS) and the engine is compiled here for the cards. 3971# No images yet. 3972ROCM_INDEXES = {"gfx1100" :"https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/" ,# TheRock's wheels per GPU family 3973"gfx1101" :"https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/" , 3974"gfx1102" :"https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/" , 3975"gfx1200" :"https://rocm.nightlies.amd.com/v2/gfx120X-all/" , 3976"gfx1201" :"https://rocm.nightlies.amd.com/v2/gfx120X-all/" , 3977"gfx1030" :"https://rocm.nightlies.amd.com/v2/gfx103X-all/" , 3978"gfx1031" :"https://rocm.nightlies.amd.com/v2/gfx103X-all/" , 3979"gfx1151" :"https://rocm.nightlies.amd.com/v2/gfx1151/" ,# Strix Halo (docs/STRIX_HALO.md) 3980"gfx1150" :"https://rocm.nightlies.amd.com/v2/gfx1150/" ,# Strix Point: only with STRATA_EXPERIMENTAL_GFX1150=1 3981"gfx1103" :"https://rocm.nightlies.amd.com/v2/gfx110X-all/" }# Radeon 780M: only with STRATA_EXPERIMENTAL_GFX1103=1 3982# The TheRock nightly indexes are pruned and move on, and each GPU family's index holds its own range (#1103: gfx103X-all 3983# starts at 7.13.0a20260422 and has no 7.10; #1267: the 7.10 wheel segfaults on a Strix Halo with kernel 7.2.8), so one 3984# version for every card cannot work. The wheel is chosen per index (the family): a preferred version, tried first; when 3985# the index no longer offers it, the newest one of the same 7.x line, else of the same major, with a warning (rocm_pick). 3986# STRATA_ROCM_VERSION still forces one exact version (no lookup). 3987ROCM_VERSION_DEFAULT = "7.10.0a20251120" # what Strata's HIP build was tested with (gfx120X, gfx110X) 3988ROCM_FAMILY_PINS = {"gfx103X-all" :"7.13.0a20260515" ,# #1103: 7.13.0a20260515 runs; the 7.14 nightlies time out 3989"gfx110X-all" :"7.10.0a20251121" ,# the experimental gfx1103: this index has no ...20251120 3990"gfx1151" :"7.14.0a20260608" }# #1267: 7.14.0a20260529 to 20260608 run on kernel 7.2.8; the 7.10 wheel segfaults 3991ROCM_VERSION_OVERRIDE = os .environ .get ("STRATA_ROCM_VERSION" )or None 3992ROCM_VERSION = ROCM_VERSION_OVERRIDE or ROCM_VERSION_DEFAULT # kept for callers that read one version 3993ROCM_SYSTEM_MIN = (7 ,0 )# an older system ROCm is passed over for the wheels (gfx1201 needs ROCm 6.4 or newer) 3994# STRATA_EXPERIMENTAL_GFX1103=1 (opt-in, unsupported): the Radeon 780M / 760M / 740M iGPU (Ryzen 7040 / 8040, gfx1103) is taken 3995# as a unified-memory AMD card like Strix Halo, with the native dot4 and gfx11 WMMA kernels, the gfx1103 exact speed switches 3996# and a hipBLASLt table when one matches (measured on one machine: Ryzen 7 8745HS). Unset: unchanged. 3997GFX1103_OPT_IN = os .environ .get ("STRATA_EXPERIMENTAL_GFX1103" )== "1" 3998# STRATA_EXPERIMENTAL_GFX1150=1 (opt-in, unvalidated): the Radeon 890M / 880M iGPU (Ryzen AI 300, Strix Point, gfx1150) 3999# is taken as a unified-memory AMD card like Strix Halo. The engine builds and runs for gfx1150 from 0.1.40.2 (#1217; 4000# tools/hip/gfx1150-hipblaslt-100401.txt is calibrated on it), but no release ships a ready-made Windows engine for it: 4001# build one with `STRATA_HIP_ARCHS=gfx1150 tools\hip\build_windows.bat` and start setup with `--prebuilt dist\`. 4002# Unset: unchanged. 4003GFX1150_OPT_IN = os .environ .get ("STRATA_EXPERIMENTAL_GFX1150" )== "1" 4004AMD_ARCHS = ("gfx1100" ,"gfx1101" ,"gfx1102" ,"gfx1200" ,"gfx1201" ,"gfx1030" ,"gfx1031" ,"gfx1151" ) \ 4005+ (("gfx1103" ,)if GFX1103_OPT_IN else ())+ (("gfx1150" ,)if GFX1150_OPT_IN else ()) 4006# The exact (bit-identical) speed switches the engine turns on by default on gfx1151 (src/core/arch_defaults.cpp), less 4007# STRATA_HCD_EXACT: that one copies the gfx1151 hipBLASLt table's solutions 1176 / 1177, and the gfx1103 table 4008# (tools/hip/gfx1103-hipblaslt-100401.txt) picks others, so it would only report that it cannot run. A gfx1103 install 4009# takes them from here (setup writes them into the config's "env"), the same way the table is written: one 780M measured 4010# the same greedy answers with all 17 on and with all 17 off, +13% to +15% prompt and decode +3.2% (the decode half 4011# alone). The engine keeps gfx1103 out of its own arch defaults (src/core/arch_defaults_test.cpp asserts it stays 4012# empty), so this keeps the default path byte-identical. 4013GFX1103_SWITCHES = { 4014# prompt 4015"STRATA_GDN_HEAD" :"1" ,"STRATA_GDN_PP" :"2" ,"STRATA_GDN_CONVL2" :"1" ,"STRATA_GDN_NOY" :"1" , 4016"STRATA_CVEC_FUSE" :"1" ,"STRATA_PF_PAD" :"1" , 4017# decode 4018"STRATA_Q8_PACKED" :"1" ,"STRATA_Q6_PACKED" :"1" ,"STRATA_MMVF_ROWS" :"1" ,"STRATA_ATTN_LANECELL" :"1" , 4019"STRATA_EXPERT_V2" :"1" ,"STRATA_TSUM" :"1" ,"STRATA_LFUSE" :"1" ,"STRATA_GDN_SPLIT" :"1" , 4020"STRATA_QFUSE" :"1" ,"STRATA_PLE_BATCH" :"1" ,"STRATA_SH_STREAM" :"1" , 4021} 4022# The same set for a gfx1150 install (Radeon 890M / 880M): less STRATA_HCD_EXACT as well, because a gfx1150 table picks other 4023# solutions than the gfx1151 one. The Radeon 890M report (docs/AMD_HIP.md; bench/results/2026-10-07-community-gfx1150) measured the 4024# same greedy answers with all 17 on and with all 17 off, decode +2% and prompts +3-6%. The engine's arch defaults are not used 4025# for gfx1150 (src/core/arch_defaults_test.cpp asserts gfx1150 stays empty), so this keeps the default path byte-identical. 4026GFX1150_SWITCHES = dict (GFX1103_SWITCHES ) 4027AMD_NAMES = {"gfx1100" :"AMD Radeon RX 7900 series (gfx1100)" ,# when sysfs has no product name 4028"gfx1101" :"AMD Radeon RX 7800 XT / 7700 XT (gfx1101)" , 4029"gfx1102" :"AMD Radeon RX 7600 / 7600 XT (gfx1102)" , 4030"gfx1200" :"AMD Radeon RX 9060 series (gfx1200)" , 4031"gfx1201" :"AMD Radeon RX 9070 series / AI PRO R9700 (gfx1201)" , 4032"gfx1030" :"AMD Radeon RX 6800 / 6900 series (gfx1030)" , 4033"gfx1031" :"AMD Radeon RX 6700 XT series (gfx1031)" , 4034"gfx1151" :"AMD Radeon 8060S / 8050S / 8040S (Ryzen AI Max, Strix Halo, gfx1151)" , 4035# integrated Radeons of other Ryzen families: named so they are not taken for Strix Halo (not supported) 4036"gfx1150" :"AMD Radeon 890M / 880M (Ryzen AI 300, Strix Point, gfx1150)" , 4037"gfx1152" :"AMD Radeon 860M / 840M (Ryzen AI 300, Krackan Point, gfx1152)" , 4038"gfx1103" :"AMD Radeon 780M / 760M / 740M (Ryzen 7040 / 8040, Phoenix / Hawk Point, gfx1103)" } 4039AMD_CARDS = ("the RX 7900 XT / XTX (gfx1100), RX 7800 XT / 7700 XT (gfx1101), RX 9060 XT (gfx1200) and " 4040"RX 9070 / 9070 XT / Radeon AI PRO R9700 (gfx1201), and the RX 6800 / 6900 series (gfx1030) and RX 6700 XT " 4041"(gfx1031, #524), and the RX 7600 / 7600 XT (gfx1102, one run reported, #942), all unvalidated, and the Ryzen AI Max \"Strix Halo\" APU (Radeon 8060S / 8050S / 8040S, " 4042"gfx1151: experimental, docs/STRIX_HALO.md)" ) 4043 4044 4045def rocm_index (arch ): 4046return os .environ .get ("STRATA_ROCM_INDEX" )or ROCM_INDEXES [arch ] 4047 4048 4049def rocm_family (index ): 4050"""The family name of a TheRock index url (.../v2/gfx103X-all/ -> gfx103X-all).""" 4051return index .rstrip ("/" ).rsplit ("/" ,1 )[- 1 ] 4052 4053 4054def rocm_vkey (version ): 4055"""Sort key of a TheRock version: 7.13.0a20260515 -> (7, 13, 0, 20260515); None when it is not one.""" 4056m = re .fullmatch (r"(\d+)\.(\d+)\.(\d+)(?:[a-z]+(\d+))?" ,version ) 4057return tuple (int (g or 0 )for g in m .groups ())if m else None 4058 4059 4060def rocm_index_versions (html ): 4061"""The versions of the `rocm` package that a TheRock index page (<index>/rocm/) lists, oldest first.""" 4062return sorted ({m for m in re .findall (r"rocm-(\d+\.\d+\.\d+(?:[a-z]+\d+)?)\.(?:tar\.gz|whl)" ,html or "" ) 4063if rocm_vkey (m )},key = rocm_vkey ) 4064 4065 4066def rocm_pick (available ,preferred ): 4067"""(version, note) for an index that lists `available`: `preferred` when it is there, else the newest of the same 40687.x line, else the newest of the same major (the note says so); `preferred` unchanged when the list is empty (the 4069index could not be read: pip then reports its own error) or nothing of that major exists (the note says so).""" 4070if not available or preferred in available : 4071return preferred ,None 4072want = rocm_vkey (preferred ) 4073for same ,what in ((lambda k :k [:2 ]== want [:2 ],"line" ), (lambda k :k [0 ]== want [0 ],"major" )): 4074hits = [v for v in available if same (rocm_vkey (v ))] 4075if hits : 4076got = max (hits ,key = rocm_vkey ) 4077return got , (f"ROCm { preferred } is not on this index any more: using { got } , the newest of the same { what } " 4078f"(set STRATA_ROCM_VERSION to choose another)" ) 4079return preferred , (f"ROCm { preferred } is not on this index and nothing of its major version is: " 4080f" { available [ 0 ] } to { available [ - 1 ] } are (set STRATA_ROCM_VERSION to one of them)" ) 4081 4082 4083def rocm_wanted (index ,listing = None ): 4084"""(ROCm wheel version, warning or None) for a TheRock index (see ROCM_FAMILY_PINS). `listing` is the index 4085page's html (None: fetched from <index>/rocm/; a failed fetch keeps the preferred version).""" 4086if ROCM_VERSION_OVERRIDE : 4087version ,note = ROCM_VERSION_OVERRIDE ,None 4088else : 4089preferred = ROCM_FAMILY_PINS .get (rocm_family (index ),ROCM_VERSION_DEFAULT ) 4090if listing is None : 4091try : 4092req = urllib .request .Request (index .rstrip ("/" )+ "/rocm/" ,headers = {"User-Agent" :"strata-setup" }) 4093with _urlopen (req ,timeout = 30 )as r : 4094listing = r .read ().decode ("utf-8" ,"replace" ) 4095except (OSError ,ValueError ): 4096listing = "" 4097version ,note = rocm_pick (rocm_index_versions (listing ),preferred ) 4098if rocm_family (index )== "gfx1151" and (rocm_vkey (version )or (9 ,0 ))[:2 ]< (7 ,11 ): 4099note = ((note + "; " )if note else "" )+ ( 4100"the ROCm 7.10 wheels segfault in the HSA runtime on a Strix Halo with a new kernel (7.2.8, #1267): " 4101"the 7.14 line (docs/STRIX_HALO.md) is the one that works" ) 4102return version ,note 4103 4104 4105# Strix Halo (Ryzen AI Max 380 / 385 / 390 / 395 + PRO: Radeon 8040S / 8050S / 8060S, RDNA 3.5, gfx1151) and the other 4106# integrated Radeons it must never be taken for. pci.ids lists ONE device id for the whole Strix Halo family 4107# ("1586 Strix Halo [Radeon Graphics / Radeon 8050S Graphics / Radeon 8060S Graphics]"; the 8040S shares it: the 4108# three differ by their CU count, 40 / 32 / 16, not by id). Aurora's real answers (tools/test_setup_strix_halo.py): 4109# KFD gfx_target_version 110501, vendor_id 4098, device_id 5510 (0x1586), simd_count 80. 4110STRIX_HALO_ARCH = "gfx1151" 4111STRIX_HALO_PCI_IDS = frozenset ({0x1586 }) 4112AMD_IGPU_PCI = {0x1586 :"gfx1151" ,# Strix Halo 41130x150E :"gfx1150" ,# Strix Point: Radeon 880M / 890M 41140x1114 :"gfx1152" ,0x1902 :"gfx1152" ,# Krackan Point (Krackan2): Radeon 840M / 860M 41150x15BF :"gfx1103" ,0x15C8 :"gfx1103" ,0x164F :"gfx1103" ,# Phoenix: Radeon 740M / 760M / 780M 41160x1900 :"gfx1103" ,0x1901 :"gfx1103" }# Hawk Point 4117STRIX_HALO_BY_SIMDS = {80 :"8060S" ,64 :"8050S" ,32 :"8040S" }# KFD simd_count (2 per CU): 40 / 32 / 16 CUs 4118UMA_OS_LEFT_GB = 6 # the share of the unified memory kept for the OS: what the engine's device_free_bytes() leaves 4119 4120 4121def gfx_arch_is (arch ,name )-> bool : 4122"""include/strata/kernels/gfx_arch.hpp's gfx_arch_is: `arch` (gcnArchName, "gfx1151" or "gfx1151:sramecc-:xnack-") 4123is exactly `name`, never a prefix: gfx1150 and gfx1152 are not gfx1151 (and gfx1151 is not gfx115).""" 4124arch = str (arch or "" ) 4125return arch == name or arch .startswith (name + ":" ) 4126 4127 4128def is_strix_halo (g )-> bool : 4129return isinstance (g ,dict )and gfx_arch_is (g .get ("arch" ),STRIX_HALO_ARCH ) 4130 4131 4132RDNA2_ARCHS = ("gfx1030" ,"gfx1031" )# RX 6800 / 6900 / 6950 series and RX 6700 XT: the cards of the ready-made RX 6000 engine package 4133 4134 4135def is_rdna2 (g )-> bool : 4136"""A discrete RX 6000 card the ready-made RX 6000 engine package covers (gfx1030 / gfx1031); never an RX 7000 / 9000 or an APU.""" 4137return isinstance (g ,dict )and any (gfx_arch_is (g .get ("arch" ),a )for a in RDNA2_ARCHS ) 4138 4139 4140RDNA2_PACKAGE_NOTE = ("RX 6000 series (RDNA2, {arch}): Strata has a ready-made engine package for these cards, built, not tested on a real " 4141"RX 6000 card. It runs plain kernels (this chip has no matrix cores, so the RX 7000 / RX 9000 prompt paths stay off) " 4142"and plain hipBLAS (no hipBLASLt tuning table for it). If something goes wrong, open an issue with the end of " 4143"strata-<model>.log: docs/AMD_HIP.md, \"RDNA2\"." ) 4144 4145 4146def rdna2_notes (gpu )-> list [str ]: 4147"""What setup tells the owner of an RX 6000 card (gfx1030 / gfx1031); nothing for any other card.""" 4148if not is_rdna2 (gpu ): 4149return [] 4150return [" " + RDNA2_PACKAGE_NOTE .format (arch = str (gpu .get ("arch" )).split (":" )[0 ])] 4151 4152 4153def is_uma_apu (g )-> bool : 4154"""A unified-memory AMD APU whose "VRAM" is a BIOS carve-out plus shared system memory: Strix Halo (gfx1151), and 4155the opt-in gfx1150 (Strix Point) / gfx1103 (Phoenix / Hawk Point) iGPUs. Everything else is a discrete card.""" 4156arch = g .get ("arch" )if isinstance (g ,dict )else None 4157return (is_strix_halo (g ) 4158or (GFX1150_OPT_IN and gfx_arch_is (arch ,"gfx1150" )) 4159or (GFX1103_OPT_IN and gfx_arch_is (arch ,"gfx1103" ))) 4160 4161 4162def apu_hides_chunk_tip (g ,line :str )-> bool : 4163"""The bench tip for --prefill auto:32768 is not said on an APU: its prompt buffers share the pool with the expert cache, a 32768 chunk can take the last of it 4164(Strix Halo with UD-Q4_K_XL: the engine ends at the start, round0212), and the tip was measured on discrete cards.""" 4165return is_uma_apu (g )and line .startswith ("tip" )and "auto:32768" in line 4166 4167 4168def amd_apply_uma (g :dict ,gtt_gb :float = 0.0 ,ram :float | None = None )-> dict : 4169"""Strix Halo is an APU with unified memory. Its "dedicated VRAM" is a BIOS carve-out (512 MB to 96 GB; 2 GB on the 4170maintainers' box) and the GPU also reaches shared system memory (Linux: the GTT pool, `mem_info_gtt_total`, half the 4171RAM unless the kernel was told otherwise; Windows: "shared GPU memory", half the RAM). The shared part IS the RAM 4172the model's experts live in, so it is not extra room beside the RAM. g gets: uma, dedicated_gb (the carve-out: the 4173only part that adds to the RAM, which the low-RAM mode counts) and vram_gb = the memory the GPU can use in all 4174(the carve-out plus the shared pool less what the OS keeps), which sizes the context and the parallel slots.""" 4175if g .get ("uma" )or not is_uma_apu (g ): 4176return g 4177ram = ram_gb ()if ram is None else ram 4178carve = max (0.0 ,float (g .get ("vram_gb" )or 0.0 )) 4179shared = gtt_gb if gtt_gb > 0 else ram / 2 4180shared = max (0.0 ,min (shared ,ram - UMA_OS_LEFT_GB )) 4181g .update ({"uma" :True ,"dedicated_gb" :carve ,"shared_gb" :shared ,"vram_gb" :carve + shared }) 4182return g 4183 4184 4185def low_ram_vram (g )-> float : 4186"""The GPU memory the low-RAM mode may count as room beside the RAM: a discrete card's VRAM; an APU's BIOS 4187carve-out only (its shared memory is the RAM itself).""" 4188return g .get ("dedicated_gb" ,0.0 )if g .get ("uma" )else g ["vram_gb" ] 4189 4190 4191def amd_mem_text (g )-> str : 4192"""How setup says a card's memory: "24 GB VRAM", or for an APU its unified memory.""" 4193if g .get ("uma" ): 4194return (f"unified memory: { g [ 'dedicated_gb' ]:.1f } GB BIOS carve-out + { g [ 'shared_gb' ]:.0f } GB shared with the " 4195f"RAM, { g [ 'vram_gb' ]:.0f } GB usable by the GPU" ) 4196return f" { g [ 'vram_gb' ]:.0f } GB VRAM" 4197 4198 4199STRIX_HALO_FAMILY ,STRIX_HALO_MODEL = "unsloth" ,"UD-IQ4_XS" # the model docs/STRIX_HALO.md measures 4200STRIX_HALO_MIN_GB = 80 # UD-IQ4_XS keeps all of its experts in memory from ~80 GB (its menu line says so) 4201 4202 4203RECOMMENDED_SIZES = {"qwen" : ("IQ3_S" ,),"swift" : ("IQ3_S" ,),"unsloth" : ("UD-Q4_K_XL" ,"UD-IQ4_XS" )}# owner's pick, 0.1.44 4204 4205 4206def mem_have (model :str ,ram :float ,vram :float = 0.0 )-> float : 4207"""The memory this PC offers a model, in the unit of its MODELS "ram_gb": RAM, or for a "mem_total" model (Gyro) the 4208VRAM and the RAM together.""" 4209return ram + vram if MODELS [model ].get ("mem_total" )else ram 4210 4211 4212# 0.2.0, the owner's memory tiers (README "The other sizes"): RAM + VRAM together pick the size. The floors sit 2 GB 4213# below the tiers' names (40 / 48 / 64 GB) because the OS reports a little less than the installed memory. 64 GB and 4214# up: IQ3_S (the original; Swift 1.5's IQ3_S is an equal choice), 48 GB: IQ3_XXS, 40 GB: Swift 1.5's IQ2_XS, with Gyro-M 4215# (35 GB) as the other choice. Below 40 GB the older rules stand (Gyro-S, or the Coder for code). The Mac has its own 4216# rules (strata_control/mac_fit.py). tools/strata_mcp.py's recommend() holds the same floors (the app and `strata launch`). 4217MEMORY_TIERS = ((62.0 ,"qwen" ,"IQ3_S" ), (46.0 ,"qwen" ,"IQ3_XXS" ), (38.0 ,"swift" ,"IQ2_XS" )) 4218# #3425 (owner's rule): the tiers count RAM + VRAM less this much, which Windows and the system keep for themselves. A PC 4219# with a 16 GB card and 32 GB of RAM used to land in the 48 GB tier and then read ~11 GB of it from the SSD on every answer. 4220# tools/strata_mcp.py has the same constant; the Mac (strata_control/mac_fit.py) keeps its own macOS share and does not use it. 4221TIER_SYSTEM_RESERVE_GB = 5.0 4222 4223 4224def tier_pick (ram :float ,vram :float = 0.0 ): 4225"""(family, size) for this PC's RAM + VRAM by MEMORY_TIERS, or None below the lowest tier (then the older rules pick: 4226Gyro-S, or the Coder). With less RAM than the size's own figure the low-RAM mode starts by itself and the model is 4227slower. A recommendation: every size stays a choice.""" 4228for floor ,fam ,m in MEMORY_TIERS : 4229if ram + vram - TIER_SYSTEM_RESERVE_GB >= floor : 4230return fam ,m 4231return None 4232 4233 4234def tier_note (ram :float ,vram :float = 0.0 ,gyro :bool = True )-> str : 4235"""The sentence under the model menu for the lowest tier: Gyro-M is the other choice there (NVIDIA and AMD only).""" 4236pick = tier_pick (ram ,vram ) 4237if not gyro or pick != ("swift" ,"IQ2_XS" ): 4238return "" 4239return ("this PC's RAM + VRAM is in the 40 GB tier: Swift 1.5's IQ2_XS is the pick; Gyro-M (35 GB) is the other choice, " 4240"close to IQ3_XXS in quality but 16-21% slower at writing answers than Q2_0" ) 4241 4242 4243def recommended_size (family :str ,names :list ,ram :float ,vram :float = 0.0 )-> str : 4244"""The size the menu pre-selects (and --yes takes): the memory tier's size (RAM + VRAM, MEMORY_TIERS) when this 4245family has it, else the family's recommended size when this PC's RAM fits it (UD-Q4_K_XL before UD-IQ4_XS), else 4246the largest size that fits, else the first. Recommend, never force: every other size stays a choice.""" 4247tier = tier_pick (ram ,vram ) 4248if tier and tier [1 ]in names and family in ("qwen" ,"swift" ): 4249return tier [1 ] 4250for m in RECOMMENDED_SIZES .get (family , ()): 4251if m in names and mem_have (m ,ram ,vram )>= MODELS [m ]["ram_gb" ]: 4252return m 4253fitting = [m for m in names if mem_have (m ,ram ,vram )>= MODELS [m ]["ram_gb" ]] 4254if fitting : 4255return max (fitting ,key = lambda m :MODELS [m ]["download_gb" ]) 4256return "UD-IQ4_XS" if family == "unsloth" and "UD-IQ4_XS" in names else names [0 ] 4257 4258 4259def size_tag (family :str ,m :str ,installed :str | None = None )-> str : 4260rec ,have = m in RECOMMENDED_SIZES .get (family , ()),m == installed 4261return " (recommended, installed)" if rec and have else " (recommended)" if rec else " (installed)" if have else "" 4262 4263 4264def installed_size (family :str ,names :list ,have :list )-> str | None : 4265"""0.1.44.1: the size of this family that is already installed (the most recently used config first), or None. Setup 4266run again (SETUP.bat, --setup) pre-selects it: the 0.1.44 recommendation (IQ3_S, about 15% slower than IQ3_XXS and 42677 GB more RAM) is for a first install, and Enter must not move an installed model to another size.""" 4268for c in have : 4269try : 4270ch = choices_from_config (c ) 4271except (OSError ,ValueError ,KeyError ,TypeError ,IndexError ): 4272continue 4273if ch .get ("family" )== family and ch .get ("model" )in names : 4274return ch ["model" ] 4275return None 4276 4277 4278def unsloth_default_env (family :str ,model :str ,hip :bool ,in_budget :bool ,arch :str = "" )-> dict : 4279"""0.1.44 (owner, review-quants.md section 5): the run-config "env" setup writes for Unsloth's files. 4280STRATA_MMQ_KQ=1 (the K-quant MMQ prompt kernels) for UD-Q5_K_XL and UD-Q6_K_XL, where its prompt-path KL is equal 4281or better than the FP16 path's; UD-Q4_K_XL keeps it opt-in here (the Linux gfx12 engine takes it by itself since 0.2.10.1). 4282STRATA_HC_Q8 on CUDA for the UD-* files is the ENGINE's default now (it sees the Q8_0 hyper-connection projections in the GGUF); setup 4283writes nothing for it. 4284STRATA_ROUTE_TAIL_SKIP=0 where every expert is in RAM (the skip costs KL there); the RAM-budget mode keeps it. 42850.2.10.1 (owner 11-03, "3 Yes"): NOT on Linux gfx12 (``arch`` "gfx1200"/"gfx1201", the R9700 and RX 9000): there the engine's own default 4286(rank 7, STRATA_ROUTE_TAIL_SKIP=0 still turns it off) stays, which decodes UD-Q4_K_XL 6-16% faster at an unchanged 61-task suite 4287(phaseA-tests/round0212/RESULTS-TAILSKIP.md). Windows and every other card keep the 0.""" 4288env = {} 4289if family != "unsloth" : 4290return env 4291if model in ("UD-Q5_K_XL" ,"UD-Q6_K_XL" ): 4292env ["STRATA_MMQ_KQ" ]= "1" 4293gfx12_linux = hip and not WIN and str (arch or "" ).lower ().startswith (("gfx1200" ,"gfx1201" )) 4294if not in_budget and not gfx12_linux : 4295env ["STRATA_ROUTE_TAIL_SKIP" ]= "0" 4296return env 4297 4298 4299def menu_families (hip :bool )-> list : 4300"""The families the model menu lists, in menu order. The NVFP4 packs run on NVIDIA cards only (the AMD and Intel 4301engines have no NVFP4 kernels), so on those the menu does not offer them; `--family nvfp4` still says why not.""" 4302return [f for f in FAMILIES if not (hip and FAMILIES [f ].get ("ready" ))] 4303 4304 4305def nvfp4_card_note (gpu )-> str : 4306"""What the NVFP4 menu line says about this NVIDIA card: RTX 50 (Blackwell, sm_120) has FP4 tensor cores; on older 4307RTX cards the experts run at 8-bit precision, which measured slower than UD-IQ4_XS (docs/NVFP4.md).""" 4308try : 4309arch = int ((gpu or {}).get ("arch" )or 0 ) 4310except (TypeError ,ValueError ): 4311arch = 0 4312if arch >= 120 : 4313return "native FP4 on this card" 4314return "runs, but UD-IQ4_XS is faster on this card" 4315 4316 4317def nvfp4_cpu_note (avx2 :bool ,avx512 :bool )-> str : 4318"""What the NVFP4 menu line and the install step say about this CPU (#2347). Its experts that stay on the CPU run 4319on AVX-512 rows when the CPU has them, else on AVX2 rows (bit-equal to ggml's AVX2 dot). Measured (docs/NVFP4.md): 4320per core the AVX2 rows are ~10% slower, and on a whole pool that reads DRAM the two are the same speed up to two 4321tokens a window (Ryzen 7 255: 58.9 vs 58.7 GB/s) and ~12% apart at four. A note only: nothing is refused.""" 4322if avx512 or not avx2 : 4323return "" # no AVX2 at all: the older-CPU build's own warning says it 4324return ("this CPU has no AVX-512, so NVFP4's CPU rows run on AVX2: about as fast when memory-bound, up to ~12% " 4325"slower on 4-token windows" ) 4326 4327 4328def family_menu_note (family :str ,hip :bool ,gpu ,avx2 :bool = True ,avx512 :bool = True )-> str : 4329"""The card-, CPU- and RAM-dependent tail of a family's line in the model menu.""" 4330if family == "nvfp4" : 4331d = MODELS ["NVFP4" ] 4332cpu = nvfp4_cpu_note (avx2 ,avx512 ) 4333return (f" [ { nvfp4_card_note ( gpu ) } ; { d [ 'download_gb' ]:.0f } GB download, ~ { d [ 'ram_gb' ] } GB of RAM keeps every " 4334"expert in RAM" + (f"; { cpu } " if cpu else "" )+ "]" ) 4335if family == "unsloth" and hip : 4336return " [UD-IQ4_XS is the 4-bit choice on AMD and Intel cards; NVFP4 runs on NVIDIA only]" 4337if family == "gyro" : 4338return (" [for PCs with little memory: VRAM + RAM together 27.6 GB (Gyro-S) or 35 GB (Gyro-M)" 4339+ ("; AMD is experimental, not for Intel Arc" if hip else "" )+ "]" ) 4340return "" 4341 4342 4343def strix_halo_recommends (gpu ,ram )-> bool : 4344"""Is UD-IQ4_XS the recommended model here: a Strix Halo whose unified memory (the OS's RAM plus the BIOS carve-out) 4345holds it - the model docs/STRIX_HALO.md measures. A recommendation only: the menus still list every size.""" 4346return is_strix_halo (gpu )and bool (gpu .get ("uma" ))and ram + gpu .get ("dedicated_gb" ,0.0 )>= STRIX_HALO_MIN_GB 4347 4348 4349def amd_device_access_problem (dev = "/dev" ,access = os .access ,listing = glob .glob )-> str | None : 4350"""Linux AMD: /dev/kfd and the render nodes must be readable and writable by this user (the render / video groups). 4351None when they are, else a sentence for the user. A missing /dev/kfd is not this problem (no driver / no ROCm).""" 4352kfd = os .path .join (dev ,"kfd" ) 4353if not os .path .exists (kfd ): 4354return None 4355bad = [kfd ]if not access (kfd ,os .R_OK | os .W_OK )else [] 4356bad += [n for n in sorted (listing (os .path .join (dev ,"dri" ,"renderD*" )))if not access (n ,os .R_OK | os .W_OK )] 4357if not bad : 4358return None 4359return (f"this user cannot open { ', ' . join ( bad ) } : ROCm will find no GPU and the engine will fail with 'no ROCm-capable " 4360"device' although nothing else holds the GPU. Add your user to the render and video groups: " 4361"sudo usermod -aG render,video $USER, then log out and in again" ) 4362 4363 4364def gfx1103_notes (gpu ,ram )-> list [str ]: 4365"""What setup tells the owner of a Radeon 780M / 760M / 740M (Phoenix / Hawk Point, gfx1103, unified memory): never 4366the Strix Halo text, which is about another chip (gfx1151). Opt-in only (STRATA_EXPERIMENTAL_GFX1103=1).""" 4367notes = [f" Radeon 780M / 760M class (gfx1103, Ryzen 7040 / 8040): the CPU and the GPU share one memory pool ( { ram :.0f } GB " 4368f"seen by the OS + a { gpu . get ( 'dedicated_gb' , 0.0 ):.1f } GB BIOS carve-out), so the model's experts live in " 4369"that pool and the expert cache is sized from the memory the OS can give back." ] 4370notes .append (" " + ("The engine is compiled here for gfx1103" if not WIN else "This GPU has no ready-made Windows engine" ) 4371+ " with the native dot4 and WMMA kernels and the 780M's exact speed switches" 4372+ " (experimental opt-in, STRATA_EXPERIMENTAL_GFX1103=1; measured on one machine, not validated on a real " 4373"card): see docs/AMD_HIP.md and docs/RADEON_780M.md. This is not a Strix Halo." ) 4374if not WIN and gpu .get ("shared_gb" ,0 )< 0.75 * ram - 1 : 4375notes .append (f"!the GPU can reach { gpu . get ( 'shared_gb' , 0 ):.0f } GB of shared memory (the GTT pool; the kernel's " 4376"default is about half of the RAM). The kernel option ttm.pages_limit raises it; setup changes no " 4377"host setting - a bigger model needs the room, a smaller one runs as it is" ) 4378return notes 4379 4380 4381def gfx1150_notes (gpu ,ram )-> list [str ]: 4382"""What setup tells the owner of a Radeon 890M / 880M (Ryzen AI 300, Strix Point, gfx1150, unified memory): never 4383the Strix Halo text, which is about another chip (gfx1151). Opt-in only (STRATA_EXPERIMENTAL_GFX1150=1).""" 4384notes = [f" Radeon 890M / 880M class (gfx1150, Strix Point): the CPU and the GPU share one memory pool ( { ram :.0f } GB " 4385f"seen by the OS + a { gpu . get ( 'dedicated_gb' , 0.0 ):.1f } GB BIOS carve-out), so the model's experts live in " 4386"that pool and the expert cache is sized from the memory the OS can give back." ] 4387notes .append (" " + ("The engine is compiled here for gfx1150" if not WIN else 4388"Windows has no ready-made engine for gfx1150: build one with STRATA_HIP_ARCHS=gfx1150 " 4389"tools\\hip\\build_windows.bat and start setup with --prebuilt dist\\" ) 4390+ " (experimental opt-in, STRATA_EXPERIMENTAL_GFX1150=1, unvalidated: docs/AMD_HIP.md)." ) 4391if not WIN and gpu .get ("shared_gb" ,0 )< 0.75 * ram - 1 : 4392notes .append (f"!the GPU can reach { gpu . get ( 'shared_gb' , 0 ):.0f } GB of shared memory (the GTT pool; the kernel's " 4393"default is about half of the RAM). The kernel option ttm.pages_limit raises it; setup changes no " 4394"host setting - a bigger model needs the room, a smaller one runs as it is" ) 4395return notes 4396 4397 4398def igpu_notes (gpu ,ram )-> list [str ]: 4399"""The unified-memory notes for exactly this chip: Strix Halo (gfx1151) or the gfx1150 / gfx1103 opt-in, nothing else.""" 4400if is_strix_halo (gpu ): 4401return strix_halo_notes (gpu ,ram ) 4402if GFX1150_OPT_IN and gfx_arch_is (gpu .get ("arch" ),"gfx1150" ): 4403return gfx1150_notes (gpu ,ram ) 4404if gfx_arch_is (gpu .get ("arch" ),"gfx1103" ): 4405return gfx1103_notes (gpu ,ram ) 4406return [] 4407 4408 4409def unused_apu_notes (chosen ,amd ,ram )-> list [str ]: 4410"""A Strix Halo / APU that is NOT in the run but sits beside the card that is (a Radeon AI PRO R9700 and the 8060S): its BIOS carve-out is memory 4411the OS does not have, and it is the RAM the experts live in. Nothing is changed: a "!" line says what is lost and what to set.""" 4412out = [] 4413used = {g ["index" ]for g in chosen } 4414for g in amd : 4415if g .get ("uma" )and g ["index" ]not in used and g .get ("dedicated_gb" ,0.0 )> 16 : 4416out .append (f"!the BIOS gives { g [ 'dedicated_gb' ]:.0f } GB of your memory to { g [ 'name' ] } , which this run does not use: the OS has " 4417f" { ram :.0f } GB left for the experts and the desktop, and the engine can run out of RAM. A small carve-out (512 MB - 2 GB, " 4418"'UMA Frame Buffer Size' in the BIOS) gives it back; the GPU reaches the shared memory anyway" ) 4419return out 4420 4421 4422def strix_halo_notes (gpu ,ram )-> list [str ]: 4423"""What setup tells a Strix Halo owner (a leading "!" = a warning): the unified memory, the build, the guide, and the 4424memory settings that give the GPU room. Nothing is changed or refused: recommend, never force.""" 4425notes = [f" Strix Halo (gfx1151, Ryzen AI Max): the CPU and the GPU share one memory pool ( { ram :.0f } GB seen by the " 4426f"OS + a { gpu . get ( 'dedicated_gb' , 0.0 ):.1f } GB BIOS carve-out), so the model's experts live in that pool " 4427"and the expert cache is sized from the memory the OS can give back, not from the carve-out." ] 4428notes .append (" " + ("The engine is compiled here for gfx1151" if not WIN else "Windows uses the ready-made AMD engine, " 4429"which must be built for gfx1151" ) 4430+ " (experimental, measured on one machine): see docs/STRIX_HALO.md." ) 4431if not WIN and gpu .get ("shared_gb" ,0 )< 0.75 * ram - 1 : 4432notes .append (f"!the GPU can reach { gpu . get ( 'shared_gb' , 0 ):.0f } GB of shared memory (the GTT pool; the kernel's " 4433f"default is about half of the RAM). docs/STRIX_HALO.md boots with ttm.pages_limit and " 4434"ttm.page_pool_size to give it most of the RAM; setup changes no host setting - a bigger model " 4435"needs the room, a smaller one runs as it is" ) 4436if gpu .get ("dedicated_gb" ,0.0 )> 16 : 4437notes .append (f"!the BIOS carve-out is { gpu [ 'dedicated_gb' ]:.0f } GB: that memory is taken from the OS, while the GPU " 4438"reaches the shared memory anyway. A small carve-out (the BIOS's default or 512 MB - 2 GB) leaves " 4439"the RAM to the model" ) 4440if strix_halo_recommends (gpu ,ram ): 4441notes .append (f" Recommended model: { STRIX_HALO_MODEL } (the one docs/STRIX_HALO.md measures); the menus list the " 4442"others." ) 4443return notes 4444 4445 4446def amd_rank (g ): 4447"""The order setup picks a card in, best first: a discrete card before an APU (its own GDDR is faster than the 4448shared LPDDR5X), then the most memory. A Strix Halo beside a Radeon RX / PRO card is therefore left to --gpu N.""" 4449return (bool (g .get ("uma" )),- round (g ["vram_gb" ]),g ["index" ]) 4450 4451 4452def amd_pci_devices (sysfs = "/sys" )-> list [dict ]: 4453"""The AMD (vendor 0x1002) display devices the kernel lists in /sys/class/drm/card*/device, as [{"pci_id", 4454"vram_gb", "gtt_gb", "arch"}] with the arch AMD_IGPU_PCI knows ("" when it does not). The KFD topology answers the 4455same without ROCm; this one only names a card the topology does not list (a kernel without /dev/kfd).""" 4456found = [] 4457base = Path (sysfs )/ "class/drm" 4458if not base .is_dir (): 4459return found 4460for card in sorted (base .glob ("card[0-9]*" )): 4461if not card .name [4 :].isdigit (): 4462continue 4463try : 4464dev = card / "device" 4465if int ((dev / "vendor" ).read_text ().strip (),16 )!= 0x1002 : 4466continue 4467did = int ((dev / "device" ).read_text ().strip (),16 ) 4468except (OSError ,ValueError ): 4469continue 4470row = {"pci_id" :did ,"arch" :AMD_IGPU_PCI .get (did ,"" ),"vram_gb" :0.0 ,"gtt_gb" :0.0 } 4471for key ,f in (("vram_gb" ,"mem_info_vram_total" ), ("gtt_gb" ,"mem_info_gtt_total" )): 4472try : 4473row [key ]= int ((dev / f ).read_text ())/ 2 ** 30 4474except (OSError ,ValueError ): 4475pass 4476found .append (row ) 4477return found 4478 4479 4480def amd_gpus (sysfs = "/sys" ): 4481"""AMD GPUs from the kernel's KFD topology (the amdgpu driver; no ROCm needed), numbered as HIP numbers them: 4482the GPU nodes in order, the CPU nodes skipped. Integrated GPUs are listed too (not supported). 4483sysfs: the tree to read (tools/test_setup_amd.py passes a mocked one). Windows: amd_gpus_win.""" 4484if WIN : 4485return amd_gpus_win () 4486base = Path (sysfs )/ "class/kfd/kfd/topology/nodes" 4487found = [] 4488if not base .is_dir (): 4489return found 4490for node in sorted ((p for p in base .iterdir ()if p .name .isdigit ()),key = lambda p :int (p .name )): 4491try : 4492props = {} 4493for line in (node / "properties" ).read_text ().splitlines (): 4494k ,_ ,v = line .partition (" " ) 4495props [k ]= v .strip () 4496ver = int (props .get ("gfx_target_version" )or 0 ) 4497if ver == 0 or int (props .get ("simd_count" )or 0 )== 0 : 4498continue 4499except (OSError ,ValueError ): 4500continue 4501arch = f"gfx { ver // 10000 } {( ver // 100 ) % 100 :x } { ver % 100 :x } " 4502dev = Path (sysfs )/ f"class/drm/renderD { props . get ( 'drm_render_minor' , '' ) } /device" 4503try : 4504vram = int ((dev / "mem_info_vram_total" ).read_text ())/ 2 ** 30 4505except (OSError ,ValueError ): 4506vram = 0.0 4507try : 4508name = (dev / "product_name" ).read_text ().strip ()or f"AMD Radeon ( { arch } )" 4509except OSError : 4510name = f"AMD Radeon ( { arch } )" 4511if name == f"AMD Radeon ( { arch } )" and arch in AMD_NAMES : 4512name = AMD_NAMES [arch ] 4513if gfx_arch_is (arch ,STRIX_HALO_ARCH )and int (props .get ("simd_count" )or 0 )in STRIX_HALO_BY_SIMDS : 4514name = (f"AMD Radeon { STRIX_HALO_BY_SIMDS [ int ( props [ 'simd_count' ])] } " 4515"(Ryzen AI Max, Strix Halo, gfx1151)" )# the CU count tells the 8060S / 8050S / 8040S apart 4516try : 4517gtt = int ((dev / "mem_info_gtt_total" ).read_text ())/ 2 ** 30 4518except (OSError ,ValueError ): 4519gtt = 0.0 4520g = {"index" :len (found ),"name" :name ,"vram_gb" :vram ,"arch" :arch ,"driver" :"amdgpu" ,"vendor" :"amd" } 4521try : 4522g ["pci_id" ]= int ((dev / "device" ).read_text ().strip (),16 ) 4523except (OSError ,ValueError ): 4524pass 4525found .append (amd_apply_uma (g ,gtt ))# Strix Halo: unified memory (carve-out + shared) 4526return found 4527 4528 4529def amd_problem (g ): 4530if g ["arch" ]not in AMD_ARCHS : 4531return (f"not supported - Strata's AMD backend runs on { AMD_CARDS } only, this is { g [ 'arch' ] } " 4532+ (" (an integrated Radeon, not Strix Halo)" if g ["arch" ]in ("gfx1150" ,"gfx1152" ,"gfx1103" )else "" )) 4533if g .get ("cannot_run" ):# Windows: the installed engine's own check (--list-devices) 4534return g ["cannot_run" ] 4535return None 4536 4537 4538def amd_gpus_win ()-> list [dict ]: 4539"""Windows: the AMD GPUs as the HIP runtime numbers them once the HIP engine is installed (hip_devices), else in 4540the display-adapter order (amd_gpus_windows).""" 4541hip = hip_devices () 4542if not hip : 4543return amd_gpus_windows () 4544halo = [g for g in hip if is_uma_apu (g )] 4545if halo :# an APU: the HIP runtime's figure is not the BIOS carve-out 4546reg = [r for r in amd_gpus_windows ()if is_uma_apu (r )] 4547for k ,g in enumerate (halo ): 4548reported = g ["vram_gb" ] 4549g ["vram_gb" ]= reg [k ]["dedicated_gb" ]if k < len (reg )else 0.0 4550amd_apply_uma (g ) 4551g ["vram_gb" ]= max (g ["vram_gb" ],reported ) 4552return hip 4553 4554 4555def amd_parse_gpus (text ,amd )-> list : 4556"""--gpus with AMD cards, numbered as HIP numbers them (setup's list): "1,0", or "all" (every supported card, the 4557most VRAM first). Every chosen card must be one Strata supports (AMD_ARCHS; they may be of different 4558architectures: the engine is compiled for each). Returns the cards, the main one first.""" 4559usable = [g for g in amd if amd_problem (g )is None ] 4560if str (text ).strip ().lower ()== "all" : 4561# "all" means the cards that help: a Strix Halo / APU beside a card with memory of its own adds no memory (its memory is the RAM), 4562# draws the desktop, and as a stage it only slows the split down. Named by number (--gpus 1,0) it is still taken as asked. 4563own = [g for g in usable if not g .get ("uma" )] 4564sel = [g ["index" ]for g in sorted (own if len (own )>= 2 else usable ,key = amd_rank )] 4565left = [g for g in usable if g ["index" ]not in sel ] 4566if left and len (own )>= 2 : 4567say (" --gpus all leaves out " + ", " .join (f"GPU { g [ 'index' ] } ( { g [ 'name' ] } )" for g in left ) 4568+ ": it shares the system memory and draws the desktop. Name it (--gpus ...) to use it anyway" ) 4569else : 4570try : 4571sel = [int (x )for x in str (text ).split ("," )if x .strip ()] 4572except ValueError : 4573fail (f"--gpus takes AMD GPU numbers as setup lists them, e.g. --gpus 1,0 (or --gpus all), not { text !r } " ) 4574if len (sel )< 2 or len (set (sel ))!= len (sel ): 4575fail ("--gpus takes two or more different GPUs, e.g. --gpus 1,0 (one GPU: --gpu 1)" , 4576"this PC has " + (f" { len ( usable ) } AMD card { 's' if len ( usable ) != 1 else '' } Strata can use" 4577+ (": " + ", " .join (f"GPU { g [ 'index' ] } ( { g [ 'name' ] } )" for g in usable )if usable else "" ))) 4578byid = {g ["index" ]:g for g in amd } 4579for i in sel : 4580g = byid .get (i ) 4581p = "not found on this PC" if g is None else amd_problem (g ) 4582if p is not None : 4583fail (f"AMD GPU { i } { '' if g is None else ' (' + g [ 'name' ] + ')' } cannot be used: { p } " , 4584 ("use these together: --gpus " + "," .join (str (x ["index" ])for x in usable ))if len (usable )>= 2 else 4585 ("use one card: --gpu " + str (usable [0 ]["index" ]))if usable else f"the AMD backend runs on { AMD_CARDS } " ) 4586return [byid [i ]for i in sel ] 4587 4588 4589# ------------------------------------------------------------------------------------------------ AMD on Windows 4590# Windows has no KFD topology: the cards are found from the display adapters (Win32_VideoController: the ones present, 4591# with their PCI ids) and the display-class registry (each adapter's 64-bit VRAM size), before any AMD software is 4592# needed. The engine is the ready-made HIP one (WIN_HIP_ASSET: strata.exe, strata-device.exe and the ROCm libraries it 4593# loads, built by tools/hip/build_windows.bat); it needs only the AMD driver. Once it is installed, the cards are 4594# numbered as the HIP runtime numbers them (`strata-device --list-devices`): an integrated Radeon takes HIP's device 0 4595# and pushes the discrete card to 1, which the display-adapter order does not show (#325). 4596WIN_HIP_ASSET = "strata-windows-x64-hip.zip" # releases up to 0.1.45; 0.2 releases publish per-card packages in the signed feed (engine_from_feed) 4597WIN_HIP_MIN_ENGINE = max (MIN_ENGINE , (0 ,1 ,33 ))# the first release with a Windows HIP engine 4598WIN_AMD_DRIVER = "https://www.amd.com/en/support/download/drivers.html" 4599# PCI device ids (VEN_1002) of the cards the AMD backend knows; the names below cover a card whose id is not listed 4600_WIN_AMD_DID = {0x744C :"gfx1100" ,0x7448 :"gfx1100" ,0x745E :"gfx1100" ,# RX 7900 XTX/XT/GRE, W7900, W7800 46010x747E :"gfx1101" ,# RX 7800 XT / 7700 XT 46020x7480 :"gfx1102" ,# RX 7600 / 7600 XT 46030x7590 :"gfx1200" ,# RX 9060 XT 46040x7550 :"gfx1201" ,0x7551 :"gfx1201" ,# RX 9070 / 9070 XT, AI PRO R9700 46050x73BF :"gfx1030" ,0x73AF :"gfx1030" ,0x73A5 :"gfx1030" ,# RX 6800 / 6800 XT / 6900 XT / 6950 XT 46060x73DF :"gfx1031" ,# RX 6700 XT / 6750 XT / 6800M (#881) 4607** AMD_IGPU_PCI }# Ryzen APUs: 0x1586 = Strix Halo (gfx1151) 4608_WIN_AMD_NAME = ((re .compile (r"\b80[456]0S\b" ,re .I ),"gfx1151" ),# Radeon 8060S / 8050S / 8040S 4609 (re .compile (r"\b8[89]0M\b" ,re .I ),"gfx1150" ),# Radeon 890M / 880M 4610 (re .compile (r"\b8[46]0M\b" ,re .I ),"gfx1152" ),# Radeon 860M / 840M 4611 (re .compile (r"\b7[468]0M\b" ,re .I ),"gfx1103" ),# Radeon 780M / 760M / 740M 4612 (re .compile (r"\b9070\b|R9700" ,re .I ),"gfx1201" ), 4613 (re .compile (r"\b9060\b" ,re .I ),"gfx1200" ), 4614 (re .compile (r"RX\s*7900|W7900|W7800" ,re .I ),"gfx1100" ), 4615 (re .compile (r"RX\s*7800|RX\s*7700(?!\s*S)|W7700" ,re .I ),"gfx1101" ), 4616 (re .compile (r"RX\s*7600|W7600|W7500" ,re .I ),"gfx1102" ), 4617 (re .compile (r"RX\s*6800(?!\s*[MS])|RX\s*6900|RX\s*6950|W6800" ,re .I ),"gfx1030" )) 4618_DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" 4619 4620 4621def _win_display_adapters ()-> list [dict ]: 4622"""The display adapters present ({"name", "pnp"}), from Win32_VideoController.""" 4623ps = ("[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; " # the pipe is read as UTF-8 (#4675) 4624"Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name + '|' + $_.PNPDeviceID + '|' + " 4625"$_.AdapterRAM }" ) 4626text = out (["powershell" ,"-NoProfile" ,"-NonInteractive" ,"-Command" ,ps ]) 4627found = [] 4628for line in (text or "" ).splitlines (): 4629parts = line .strip ().split ("|" ) 4630if len (parts )>= 2 and parts [1 ]: 4631ram = parts [2 ]if len (parts )> 2 else "" 4632found .append ({"name" :parts [0 ].strip (),"pnp" :parts [1 ].strip (), 4633"ram" :int (ram )if ram .strip ().isdigit ()else 0 }) 4634return found 4635 4636 4637def _win_display_registry ()-> list [dict ]: 4638"""Each display driver instance's description, matching PCI id and VRAM size (the 64-bit value; the WMI one stops 4639at 4 GB), from the display-class registry key - readable without admin.""" 4640found = [] 4641try : 4642import winreg 4643cls = winreg .OpenKey (winreg .HKEY_LOCAL_MACHINE ,_DISPLAY_CLASS ) 4644except (ImportError ,OSError ): 4645return found 4646i = 0 4647while True : 4648try : 4649sub = winreg .EnumKey (cls ,i ) 4650except OSError : 4651break 4652i += 1 4653if not sub .isdigit (): 4654continue 4655try : 4656key = winreg .OpenKey (cls ,sub ) 4657except OSError : 4658continue 4659vals = {} 4660for name in ("DriverDesc" ,"MatchingDeviceId" ,"HardwareInformation.qwMemorySize" ,"DriverVersion" ): 4661try : 4662vals [name ]= winreg .QueryValueEx (key ,name )[0 ] 4663except OSError : 4664pass 4665found .append (vals ) 4666return found 4667 4668 4669def _pci_device_id (text :str )-> int | None : 4670m = re .search (r"VEN_1002&DEV_([0-9A-F]{4})" ,str (text or "" ),re .I ) 4671return int (m .group (1 ),16 )if m else None 4672 4673 4674def win_amd_arch (device_id :int | None ,name :str )-> str : 4675"""A Windows AMD adapter's architecture from its PCI device id, else its name; "" when it is none Strata knows 4676(an integrated Radeon, an older card).""" 4677if device_id in _WIN_AMD_DID : 4678return _WIN_AMD_DID [device_id ] 4679return next ((a for rx ,a in _WIN_AMD_NAME if rx .search (name or "" )),"" ) 4680 4681 4682def amd_gpus_windows (adapters = None ,registry = None )-> list [dict ]: 4683"""The AMD display adapters present, in display-adapter order (setup's numbering until the HIP engine is 4684installed), with the arch Strata would run them as ("" = unknown: listed, not supported). adapters / registry: 4685tools/test_setup_amd.py passes mocked ones.""" 4686adapters = _win_display_adapters ()if adapters is None else adapters 4687registry = _win_display_registry ()if registry is None else registry 4688if not adapters :# no WMI answer: the registry alone (it can list removed cards) 4689adapters = [{"name" :r .get ("DriverDesc" ,"" ),"pnp" :r .get ("MatchingDeviceId" ,"" ),"ram" :0 }for r in registry ] 4690used = set () 4691found = [] 4692for ad in adapters : 4693did = _pci_device_id (ad .get ("pnp" )) 4694if did is None : 4695continue # not an AMD (VEN_1002) PCI device 4696vram ,driver = 0.0 ,"" 4697for k ,r in enumerate (registry ):# the same card's driver instance: its 64-bit VRAM size 4698if k in used or _pci_device_id (r .get ("MatchingDeviceId" ))!= did : 4699continue 4700if (r .get ("DriverDesc" )and ad .get ("name" )and "\ufffd" not in ad ["name" ] 4701and r ["DriverDesc" ].strip ()!= ad ["name" ].strip ()): 4702continue 4703used .add (k ) 4704mem = r .get ("HardwareInformation.qwMemorySize" ) 4705if isinstance (mem ,bytes ): 4706mem = int .from_bytes (mem [:8 ],"little" ) 4707vram = int (mem )/ 2 ** 30 if isinstance (mem ,int )and mem > 0 else 0.0 4708driver = str (r .get ("DriverVersion" )or "" ) 4709break 4710if vram == 0.0 and ad .get ("ram" ,0 )> 0 : 4711vram = ad ["ram" ]/ 2 ** 30 # WMI's 32-bit figure (at most 4 GB) 4712arch = win_amd_arch (did ,ad .get ("name" ,"" )) 4713name = ad .get ("name" )or AMD_NAMES .get (arch ,f"AMD Radeon (device { did :04X } )" ) 4714g = {"index" :len (found ),"name" :name ,"vram_gb" :vram ,"arch" :arch or f"unknown (PCI { did :04X } )" , 4715"driver" :driver or "amd" ,"vendor" :"amd" ,"pci_id" :did } 4716found .append (amd_apply_uma (g ))# Strix Halo: the registry's figure is the BIOS carve-out only 4717return found 4718 4719 4720def engine_env (eng :Path )-> dict : 4721"""The environment for running an installed engine's own programs (`strata --families`, `strata-device 4722--list-devices`): the engine's ROCm library folders (its BUILD.json "lib_dirs") first on the dynamic-library path - 4723on Windows that is PATH, where the ready-made HIP engine keeps hipblas.dll / libhipblaslt.dll in its rocm/bin and the 4724loader finds them only through PATH (#2372: a launch without it shows a "not found" dialog per DLL and prints 4725nothing); on Linux and elsewhere it is LD_LIBRARY_PATH, where a probe without it exits 127 on libhipblas.so.3 and 4726prints nothing.""" 4727env = dict (os .environ ) 4728dirs = [str (d )for d in hip_lib_dirs (eng )] 4729if dirs : 4730var = "PATH" if os .name == "nt" else "LD_LIBRARY_PATH" 4731env [var ]= os .pathsep .join (dirs + ([env [var ]]if env .get (var )else [])) 4732return env 4733 4734 4735def hip_probe_path ()-> Path : 4736"""Where the installed engine's `strata-device` is: engine/ beside setup.py (a checkout), else the HIP engine package in the 4737component folder (the app and `strata update` keep it there, #3418: with only engine/ looked at, the app numbered the cards in 4738display-adapter order and an iGPU on HIP ordinal 0 made "GPU 0" the wrong card).""" 4739name = "strata-device.exe" if WIN else "strata-device" 4740own = ROOT / "engine" / name 4741if own .exists (): 4742return own 4743try : 4744from strata_control import engine_component as EC 4745found = EC .resolve (backend = "hip" ,full = False ) 4746return Path (found .root )/ name 4747except Exception :# noqa: BLE001 - no component, a damaged one: the old answer 4748return own 4749 4750 4751def hip_devices (probe :Path | None = None ,text :str | None = None )-> list [dict ]| None : 4752"""The GPUs the HIP runtime enumerates, numbered as HIP_VISIBLE_DEVICES numbers them, from the installed engine's 4753`strata-device --list-devices`; None when there is no HIP engine here or it does not answer. text: its output 4754(tests).""" 4755if text is None : 4756probe = probe or hip_probe_path () 4757hip_engine = False 4758for record in ("BUILD.json" ,"engine-component.json" ):# a checkout's build record, or a component's manifest 4759try : 4760hip_engine = json .loads ((probe .parent / record ).read_text (encoding = "utf-8-sig" )).get ("backend" )== "hip" 4761except (OSError ,ValueError ,AttributeError ): 4762continue 4763if hip_engine : 4764break 4765if not probe .exists ()or not hip_engine : 4766return None 4767try : 4768hip_runtime_beside_exe (probe .parent )# #468 #461: not the driver's System32 copy 4769r = subprocess .run ([str (probe ),"--list-devices" ],capture_output = True ,text = True ,errors = "replace" ,timeout = 120 , 4770cwd = str (probe .parent ),env = engine_env (probe .parent )) 4771except (OSError ,subprocess .TimeoutExpired ): 4772return None 4773if r .returncode != 0 : 4774return None 4775text = r .stdout 4776found = [] 4777for line in text .splitlines (): 4778m = re .match (r"device\s+(\d+):\s*(.*)$" ,line .strip ()) 4779if m : 4780found .append ({"index" :int (m .group (1 )),"name" :m .group (2 ).strip (),"vram_gb" :0.0 ,"arch" :"" , 4781"driver" :"hip" ,"vendor" :"amd" }) 4782continue 4783if not found : 4784continue 4785a = re .match (r"arch\s+(gfx[0-9a-f]+)\s*,\s*([\d.]+)\s*GiB" ,line .strip ()) 4786if a and not found [- 1 ]["arch" ]: 4787found [- 1 ]["arch" ],found [- 1 ]["vram_gb" ]= a .group (1 ),float (a .group (2 )) 4788elif line .strip ().startswith ("cannot run:" ): 4789found [- 1 ]["cannot_run" ]= line .strip ()[len ("cannot run:" ):].strip () 4790for g in found : 4791if not g ["arch" ]: 4792g ["arch" ]= "unknown" 4793if g ["arch" ]in AMD_NAMES and g ["name" ]in ("" ,"AMD Radeon Graphics" ): 4794g ["name" ]= AMD_NAMES [g ["arch" ]] 4795return found 4796 4797 4798def hip_lib_dirs (eng :Path )-> list [Path ]: 4799"""Where the ready-made Windows HIP engine's ROCm DLLs are (its BUILD.json "lib_dirs", relative to engine/).""" 4800try : 4801rel = json .loads ((eng / "BUILD.json" ).read_text (encoding = "utf-8" )).get ("lib_dirs" )or [] 4802except (OSError ,ValueError ): 4803rel = [] 4804return [eng / d for d in rel if (eng / d ).is_dir ()] 4805 4806 4807# #468 #461: the HIP runtime the ready-made engine was built with, next to strata.exe. Windows looks for an imported 4808# DLL in the exe's folder, then System32, and only then on PATH (where rocm/bin is): an AMD driver that installs its own 4809# amdhip64_7.dll in System32 won, and the bundled rocBLAS/hipBLAS ran on that runtime - an access violation (W7900) or 4810# hipErrorInvalidDeviceFunction (7900 XTX) on the first prompt. Only the runtime and the compiler it loads by name: 4811# rocBLAS/hipBLASLt stay in rocm/bin, where they find their kernel libraries and ../.kpack. 4812HIP_RUNTIME_DLLS = ("amdhip64_*.dll" ,"amd_comgr*.dll" ) 4813 4814 4815def hip_runtime_closure (d :Path )-> list [str ]: 4816"""The DLLs of `d` (the engine's rocm/bin) that amdhip64_7.dll and amd_comgr.dll need, the two included, read from 4817their PE import tables and followed recursively (tools/hip/dll_closure.py). #461: amdhip64_7.dll imports 4818rocm_kpack.dll, which imports the MSVC runtime; with only the two DLLs beside strata.exe the full-path load fails 4819(error 126), Windows falls back to System32's copy of the runtime, and the first big prompt dies with 4820hipErrorInvalidDeviceFunction. Falls back to the names above when the helper cannot be read.""" 4821roots = sorted ({p .name for pat in HIP_RUNTIME_DLLS for p in d .glob (pat )}) 4822try : 4823sys .path .insert (0 ,str (ROOT / "tools" / "hip" )) 4824from dll_closure import dll_closure 4825return dll_closure (d ,roots ) 4826except Exception :# noqa: BLE001 - a missing helper must not stop setup 4827return roots 4828finally : 4829if str (ROOT / "tools" / "hip" )in sys .path : 4830sys .path .remove (str (ROOT / "tools" / "hip" )) 4831 4832 4833def hip_runtime_beside_exe (eng :Path )-> None : 4834"""Copy the bundled HIP runtime DLLs and everything they import from rocm/bin next to the engine's exes when 4835missing or different (a 0.1.34 install, whose zip had them in rocm/bin only, is fixed on its next start; a 48360.1.40.2 install, which got only the two runtime DLLs, gets rocm_kpack.dll and the C++ runtime now, #461).""" 4837for d in hip_lib_dirs (eng ): 4838for name in hip_runtime_closure (d ): 4839src = d / name 4840dst = eng / src .name 4841try : 4842if dst .exists ()and dst .stat ().st_size == src .stat ().st_size and \ 4843dst .stat ().st_mtime >= src .stat ().st_mtime : 4844continue 4845shutil .copy2 (src ,dst ) 4846except OSError as e :# e.g. the engine is running and holds the old copy 4847warn (f"could not put { src . name } next to the AMD engine ( { e } ); if the engine stops on its first " 4848"request, close Strata and run START-HERE.bat again" ) 4849 4850 4851def hip_match (card :dict ,listed :list [dict ],hip :list [dict ])-> dict | None : 4852"""The HIP device that is setup's `card` (from `listed`, the display-adapter order): the k-th device of the same 4853architecture, k = the card's rank among the listed cards of that architecture. None when HIP has no such card.""" 4854same = [g ["index" ]for g in listed if g ["arch" ]== card ["arch" ]] 4855k = same .index (card ["index" ])if card ["index" ]in same else 0 4856cand = [g for g in hip if g ["arch" ]== card ["arch" ]] 4857return cand [k ]if k < len (cand )else None 4858 4859 4860def hip_card (eng :Path ,gpu :dict ,listed :list [dict ])-> dict : 4861"""Windows: setup's chosen AMD card as the installed HIP engine numbers it (HIP_VISIBLE_DEVICES), checked by the 4862engine itself before the model download: an integrated Radeon is HIP's device 0 (#325), and a PC without a 4863working AMD driver stops here with what to install.""" 4864hip = hip_devices (eng / "strata-device.exe" ) 4865hint = (f"install or update the AMD driver (AMD Software: Adrenalin Edition) from { WIN_AMD_DRIVER } , restart the " 4866f"PC and run this again; { eng / 'strata-device.exe' } --list-devices shows what the HIP runtime sees" ) 4867if not hip : 4868fail ("the AMD HIP runtime finds no GPU (the ready-made engine's device check)" ,hint ) 4869m = hip_match (gpu ,listed ,hip )if gpu .get ("driver" )!= "hip" else \ 4870next ((x for x in hip if x ["index" ]== gpu ["index" ]),None ) 4871if m is None : 4872fail (f"the HIP runtime does not list your { gpu [ 'name' ] } ( { gpu [ 'arch' ] } )" ,hint ) 4873if amd_problem (m ): 4874fail (f"HIP device { m [ 'index' ] } ( { m [ 'name' ] } ) cannot be used: { amd_problem ( m ) } " ) 4875if gpu .get ("driver" )!= "hip" and m ["index" ]!= gpu ["index" ]: 4876ok (f"HIP numbers this card { m [ 'index' ] } (an integrated GPU comes first): the engine is pointed at it" ) 4877vram = gpu ["vram_gb" ]if gpu .get ("uma" )else (m ["vram_gb" ]or gpu ["vram_gb" ])# an APU: not the runtime's figure 4878return {** gpu ,"index" :m ["index" ],"count" :len (hip ),"vram_gb" :vram ,"driver" :"hip" } 4879 4880 4881def engine_from_feed (eng :Path ,updating :bool = False )-> Path | None : 4882"""#3469 #3437: the 0.2 releases no longer carry the flat engine zips (strata-windows-x64*.zip); they publish one package 4883per card in the signed update feed. `strata update --no-control` fetches, verifies and test-starts the package for this PC 4884(into a folder of its own under the install), and its files then become the installed engine in `eng`, the same way a 4885zip's do. None when it cannot be had (no internet, nothing for this card): the caller goes on as before.""" 4886acquisition .require ("the ready-made engine" ) 4887from strata_control import engine_component as ec 4888store = home ()/ "engine-feed" 4889env = dict (os .environ ) 4890env .pop ("STRATA_NO_ACQUIRE" ,None ) 4891env ["STRATA_COMPONENTS_DIR" ]= str (store ) 4892say (" Fetching the ready-made engine from the signed update feed ..." ) 4893try : 4894run = subprocess .run ([sys .executable ,str (ROOT / "strata.py" ),"update" ,"--no-control" ,"--output" ,"json" ], 4895env = env ,cwd = str (ROOT ),capture_output = True ,text = True ,errors = "replace" ,timeout = 3600 ) 4896except (OSError ,subprocess .SubprocessError )as e : 4897warn (f"the update feed could not be run ( { e } )" ) 4898return None 4899if run .returncode != 0 : 4900why = (run .stderr or run .stdout or "" ).strip ().splitlines ()[- 1 :]or [f"exit { run . returncode } " ] 4901warn (f"no engine from the update feed: { why [ 0 ][: 200 ] } " ) 4902return None 4903try : 4904component = ec .resolve (store ,full = True ) 4905except ec .ComponentProblem as e : 4906warn (f"the engine from the update feed is not usable: { e } " ) 4907return None 4908eng .mkdir (exist_ok = True ) 4909tmp = eng / "_unpack" 4910shutil .rmtree (tmp ,ignore_errors = True ) 4911shutil .copytree (component .root ,tmp ) 4912try : 4913meta = json .loads ((tmp / "BUILD.json" ).read_text (encoding = "utf-8" )) 4914except (OSError ,ValueError ): 4915meta = {} 4916if meta .get ("source" )!= "prebuilt" :# the setup's own books: a ready-made engine, not one compiled here 4917meta ["source" ]= "prebuilt" 4918 (tmp / "BUILD.json" ).write_text (json .dumps (meta ,indent = 1 ),encoding = "utf-8" ) 4919 (eng / "BUILD.json" ).replace (eng / "BUILD.json.prev" )if (eng / "BUILD.json" ).exists ()else None 4920install_unpacked (tmp ,eng ) 4921shutil .rmtree (tmp ,ignore_errors = True ) 4922if not (eng / EXE ).exists (): 4923fail ("the engine package from the update feed has no " + EXE ) 4924if not WIN : 4925for x in (EXE ,VEXE ): 4926if (eng / x ).exists (): 4927 (eng / x ).chmod (0o755 ) 4928ok (f"ready-made engine { meta . get ( 'version' , '' ) } from the update feed ( { component . root . name } )" ) 4929return eng 4930 4931 4932def get_prebuilt_hip (url_base ,gpu ,updating = False )-> Path | None : 4933"""The ready-made Windows HIP engine (WIN_HIP_ASSET) in engine/, kept between runs; None when it cannot be had 4934(not published for this version, no internet) or has no code for the card.""" 4935acquisition .require ("the ready-made AMD engine" ) 4936eng = ROOT / "engine" 4937info = eng / "BUILD.json" 4938if info .exists ()and (eng / EXE ).exists (): 4939try : 4940meta = json .loads (info .read_text (encoding = "utf-8" )) 4941except ValueError : 4942meta = {} 4943ver = tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ()) 4944if meta .get ("backend" )== "hip" and meta .get ("source" )== "prebuilt" and ver >= WIN_HIP_MIN_ENGINE and \ 4945gpu ["arch" ]in arch_names (meta .get ("archs" ))and not updating : 4946ok ("ready-made AMD engine already installed" ) 4947return eng 4948if not url_base : 4949return None 4950eng .mkdir (exist_ok = True ) 4951z = eng / WIN_HIP_ASSET 4952bases = prebuilt_bases (url_base ) 4953for i ,base in enumerate (bases ): 4954if not base .startswith (("http://" ,"https://" )): 4955break 4956try : 4957req = urllib .request .Request (base + WIN_HIP_ASSET ,method = "HEAD" ,headers = {"User-Agent" :"strata-setup" }) 4958_urlopen (req ,timeout = 60 ).close () 4959break 4960except OSError as e : 4961if i + 1 < len (bases ): 4962say (f" No ready-made AMD engine for v { source_version () } ( { e } ): the latest release instead" ) 4963continue 4964warn (f"no ready-made AMD engine at { base } ( { e } )" ) 4965return engine_from_feed (eng ,updating ) 4966say (" Downloading the ready-made Strata engine for AMD GPUs (with the ROCm libraries it uses) ..." ) 4967download (base + WIN_HIP_ASSET ,z ,"Strata AMD engine" ) 4968try : 4969verify_engine_archive (z ,WIN_HIP_ASSET ,base ) 4970except UnverifiedEngine as e : 4971engine_refused (WIN_HIP_ASSET ,e ,updating ) 4972return None 4973tmp = eng / "_unpack" 4974shutil .rmtree (tmp ,ignore_errors = True ) 4975with zipfile .ZipFile (z )as f : 4976f .extractall (tmp ) 4977try : 4978meta = json .loads ((tmp / "BUILD.json" ).read_text (encoding = "utf-8" )) 4979except (OSError ,ValueError ): 4980meta = {} 4981ver = tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ()) 4982why = None 4983if meta .get ("backend" )!= "hip" or not (tmp / EXE ).exists (): 4984why = "it is not a HIP engine" 4985elif ver < WIN_HIP_MIN_ENGINE : 4986why = f"it is version { meta . get ( 'version' ) } ; this setup needs { '.' . join ( map ( str , WIN_HIP_MIN_ENGINE )) } " 4987elif gpu ["arch" ]not in arch_names (meta .get ("archs" )): 4988why = (f"it is built for { ', ' . join ( arch_names ( meta . get ( 'archs' ))) } ; your GPU is { gpu [ 'arch' ] } . A card it has no code " 4989"for runs from a self-build of the engine: see docs/AMD_HIP.md (--build)" )# #881 4990if is_strix_halo (gpu ):# never a zip without gfx1151 code: say so, and what to do 4991why = (f"it is built for { ', ' . join ( arch_names ( meta . get ( 'archs' ))) or 'other GPUs' } and has no gfx1151 code: your " 4992f" { gpu [ 'name' ] } (Strix Halo) needs a ready-made engine from Strata 0.1.40 or newer, whose zip is " 4993"built for gfx1151 too. Until then: the Linux guide docs/STRIX_HALO.md, or compile the engine " 4994"here with tools\\hip\\build_windows.bat (its default list has gfx1151) and start setup with " 4995"--prebuilt <its dist folder>" ) 4996if why : 4997warn (f"the ready-made AMD engine at { base } cannot be used: { why } " ) 4998shutil .rmtree (tmp ,ignore_errors = True ) 4999drop_archive (z ) 5000return None 5001install_unpacked (tmp ,eng ) 5002shutil .rmtree (tmp ,ignore_errors = True ) 5003drop_archive (z ) 5004hip_runtime_beside_exe (eng )# #468 #461 5005ok (f"ready-made AMD engine { meta . get ( 'version' , '' ) } for { ', ' . join ( arch_names ( meta . get ( 'archs' ))) } " 5006f"(ROCm { meta . get ( 'rocm' , '?' ) } )" ) 5007return eng 5008 5009 5010def rocm_version (root ): 5011"""(major, minor) of a ROCm install, from rocm-core's header; None when it has none.""" 5012try : 5013text = (Path (root )/ "include" / "rocm-core" / "rocm_version.h" ).read_text (encoding = "utf-8" ) 5014return tuple (int (re .search (rf"#define\s+ROCM_VERSION_ { k } \s+(\d+)" ,text ).group (1 ))for k in ("MAJOR" ,"MINOR" )) 5015except (OSError ,AttributeError ,ValueError ): 5016return None 5017 5018 5019def rocm_dev_missing (sysroot :Path )-> list : 5020"""#446: the HIP development files the engine's build needs that a system ROCm lacks (a runtime-only install has 5021hipcc and libhipblas but not these, and cmake's enable_language(HIP) then fails on the hip-lang package).""" 5022lang = "cmake/hip-lang/hip-lang-config.cmake" # where CMake's HIP support looks for it 5023need = {"lib/" + lang : [sysroot / d / lang for d in ("lib" ,"lib64" ,"lib/x86_64-unknown-linux-gnu" )], 5024"include/hip/hip_runtime.h" : [sysroot / "include" / "hip" / "hip_runtime.h" ]} 5025return [name for name ,paths in need .items ()if not any (p .is_file ()for p in paths )] 5026 5027 5028def rocm_root (archs ): 5029"""ROCm for compiling and running the HIP engine for `archs` (one arch or a list: the cards of a layer split): 5030(root, library folders). A system ROCm 7 with hipcc, hipBLAS and the HIP development files (#446), else AMD's 5031TheRock wheels (rocm_wanted: a version per card family, from the family's index) installed into .venv.""" 5032archs = [archs ]if isinstance (archs ,str )else list (archs ) 5033sysroot = Path (os .environ .get ("ROCM_PATH" )or "/opt/rocm" ) 5034if (sysroot / "bin" / "hipcc" ).exists ()and list ((sysroot / "lib" ).glob ("libhipblas.so*" )): 5035ver = rocm_version (sysroot ) 5036missing = rocm_dev_missing (sysroot ) 5037if (ver is None or ver >= ROCM_SYSTEM_MIN )and not missing : 5038return sysroot , [str (sysroot / "lib" )] 5039if ver is not None and ver < ROCM_SYSTEM_MIN : 5040warn (f"the ROCm in { sysroot } is { ver [ 0 ] } . { ver [ 1 ] } ; Strata needs { ROCM_SYSTEM_MIN [ 0 ] } . { ROCM_SYSTEM_MIN [ 1 ] } " 5041"or newer: using AMD's wheels in .venv instead" ) 5042else :# #446: a runtime-only ROCm (no -dev packages): cmake would fail 5043warn (f"the ROCm in { sysroot } has no HIP development files ( { ', ' . join ( missing ) } ): using AMD's wheels in " 5044".venv instead (or install them, e.g. AMD's amdrocm-core-dev package for your ROCm and card)" ) 5045indexes = list (dict .fromkeys (rocm_index (a )for a in archs )) 5046if len (indexes )> 1 :# TheRock's wheels hold one GPU family's libraries 5047fail (f"cards of two GPU families ( { ', ' . join ( archs ) } ) need a system ROCm 7 (in /opt/rocm): AMD's Python " 5048"wheels come per family" ,"install ROCm 7 system-wide, or use cards of one family (--gpu N for one card)" ) 5049index = indexes [0 ] 5050stamp = Path (sys .prefix )/ ".strata-rocm.json" 5051have = json .loads (stamp .read_text (encoding = "utf-8" ))if stamp .exists ()else {} 5052wheel = None 5053if have .get ("index" )== index and have .get ("version" )and not ROCM_VERSION_OVERRIDE \ 5054and (Path (sys .executable ).parent / "rocm-sdk" ).exists ()and have ["version" ]== ROCM_FAMILY_PINS .get (rocm_family (index ),ROCM_VERSION_DEFAULT ): 5055wheel = have ["version" ]# the family's pin is installed: no lookup 5056if wheel is None : 5057wheel ,note = rocm_wanted (index ) 5058if note : 5059warn (note ) 5060if have .get ("version" )!= wheel or have .get ("index" )!= index : 5061say (f" Installing ROCm { wheel } for AMD GPUs into .venv (AMD's TheRock wheels, ~10 GB, no sudo) ..." ) 5062pip = [sys .executable ,"-m" ,"pip" ,"install" ,"--quiet" ,"--disable-pip-version-check" ,"--index-url" ,index ] 5063if have .get ("version" )== wheel :# the same version for another GPU family: its own libraries 5064run (pip + ["--force-reinstall" ,"--no-deps" ,f"rocm== { wheel } " ]) 5065run (pip + [f"rocm[libraries,devel]== { wheel } " ]) 5066stamp .write_text (json .dumps ({"version" :wheel ,"index" :index })) 5067sdk = Path (sys .executable ).parent / "rocm-sdk" 5068root = Path (out ([str (sdk ),"path" ,"--root" ]).strip ()) 5069if not (root / "llvm" / "bin" / "clang++" ).exists (): 5070fail (f"ROCm was installed but its compiler is missing ( { root } )" , 5071f"remove { stamp } and run this again; or install ROCm 7 system-wide" ) 5072# the card family's libraries only (gfx120X-all -> _rocm_sdk_libraries_gfx120X_all): another family's 5073# libhipblaslt.so first on the path would have no kernels for this card 5074family = "_rocm_sdk_libraries_" + index .rstrip ("/" ).rsplit ("/" ,1 )[- 1 ].replace ("-" ,"_" ) 5075dirs = [str (root / "lib" )] 5076for sp in {Path (p )for p in sys .path if p .endswith ("site-packages" )}: 5077libs = sorted (sp .glob ("_rocm_sdk_libraries_*" )) 5078libs = [d for d in libs if d .name .lower ()== family .lower ()]or libs 5079dirs += [str (d / "lib" )for d in libs if (d / "lib" ).is_dir ()] 5080ok (f"ROCm: { root } " ) 5081return root ,list (dict .fromkeys (dirs )) 5082 5083 5084def hipblaslt_version (lib_dirs ): 5085"""The installed hipBLASLt's version as the engine reads it (hipblasLtGetVersion: 1.4.1 -> 100401), from the 5086header of the ROCm whose libraries the engine loads; None when not found.""" 5087for d in lib_dirs : 5088try : 5089text = (Path (d ).parent / "include" / "hipblaslt" / "hipblaslt-version.h" ).read_text (encoding = "utf-8" ) 5090v = [int (re .search (rf"#define\s+HIPBLASLT_VERSION_ { k } \s+(\d+)" ,text ).group (1 )) 5091for k in ("MAJOR" ,"MINOR" ,"PATCH" )] 5092except (OSError ,AttributeError ,ValueError ): 5093continue 5094return v [0 ]* 100000 + v [1 ]* 100 + v [2 ] 5095return None 5096 5097 5098def hipblaslt_table (arch ,lib_dirs ,ver = None ,extra_dirs = ()): 5099"""<arch>-hipblaslt-<version>.txt for this card AND the installed hipBLASLt, else None: its solution 5100ids are valid only for that pair (the engine refuses any other table and uses plain hipBLAS). ver: the 5101hipBLASLt version the ready-made engine ships (its BUILD.json), else read from the installed headers. extra_dirs: the 5102engine folder's own tuning/ first (a ready-made engine carries its tables), then tools/hip of this checkout. 5103STRATA_HIPBLASLT_TABLE=off: none (strata_control/hipblaslt_tuning.py).""" 5104from strata_control import hipblaslt_tuning as HT 5105if HT .switched_off (): 5106say (f" hipBLASLt tuning table: off ( { HT . SWITCH } =off); the prompt's dense matrix products use plain hipBLAS" ) 5107return None 5108ver = ver or hipblaslt_version (lib_dirs ) 5109for folder in (* extra_dirs ,ROOT / "tools" / "hip" ): 5110table = Path (folder )/ HT .table_name (arch ,ver or 0 ) 5111if ver is not None and table .exists ()and HT .header_ok (table ,arch ,ver ): 5112ok (f"hipBLASLt tuning table: { table . name } (faster prompts)" ) 5113return table 5114have = sorted (p .name for p in (ROOT / "tools" / "hip" ).glob (f" { arch } -hipblaslt-*.txt" )) 5115warn (f"no hipBLASLt tuning table for { arch } with hipBLASLt { ver or '(version unknown)' } " 5116+ (f" (have: { ', ' . join ( have ) } )" if have else "" ) 5117+ ": the prompt's dense matrix products use plain hipBLAS (tools/hip/tune_hipblaslt makes a table: " 5118"docs/AMD_HIP.md, Tuning table)" ) 5119return None 5120 5121 5122def build_engine_hip (gpu ,llama ,vision = "none" )-> Path : 5123"""Compile the HIP engine for this AMD GPU into engine/ (again only when its source changed: a `git pull`). 5124gpu["archs"]: every architecture it needs code for (the cards of a layer split), else gpu["arch"]. vision "cpu" 5125(#304): the image encoder too, for the CPU (there is no HIP encoder build yet).""" 5126acquisition .require ("an engine build" ) 5127eng = ROOT / "engine" 5128eng .mkdir (exist_ok = True ) 5129stamp = eng / "BUILD.json" 5130meta = json .loads (stamp .read_text (encoding = "utf-8" ))if stamp .exists ()else {} 5131src ,vsrc = source_hash (ENGINE_SOURCES ),source_hash (VISION_SOURCES ) 5132archs = sorted (set (gpu .get ("archs" )or [gpu ["arch" ]])) 5133has_archs = set (archs )<= set (arch_names (meta .get ("archs" ))) 5134floor = cpu_floor (cpu_info ()[1 ])# "" on an AVX2 CPU: the normal engine 5135engine_ok = meta .get ("backend" )== "hip" and (eng / EXE ).exists ()and meta .get ("src" )== src and has_archs and \ 5136 (meta .get ("isa_floor" )or "" )== floor and not stale_binary (eng / EXE ) 5137vision_ok = vision == "none" or ((eng / VEXE ).exists ()and meta .get ("vision_src" )== vsrc and 5138 (vision != "gpu" or ((eng / HVEXE ).exists ()and set (archs )<= set (arch_names (meta .get ("vision_archs" )))))) 5139if engine_ok and vision_ok : 5140ok ("engine already built for this PC" ) 5141return eng 5142if engine_ok : 5143return build_vision_hip (eng ,stamp ,meta ,llama ,vsrc ,archs ,vision ) 5144if not (shutil .which ("c++" )or shutil .which ("g++" ))or not shutil .which ("git" ): 5145fail ("a C++ compiler and git are needed to compile the AMD engine" , 5146"Ubuntu/Debian: sudo apt install build-essential git Fedora: sudo dnf install gcc-c++ git" ) 5147root ,dirs = rocm_root (archs ) 5148libs = [str (Path (d ).parent )for d in dirs [1 :]] 5149bitcode = next ((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode" ,root / "amdgcn" / "bitcode" )if p .is_dir ()), 5150root / "amdgcn" / "bitcode" ) 5151os .environ .update ({"HIP_PLATFORM" :"amd" ,"HIP_COMPILER" :"clang" ,"HIP_RUNTIME" :"rocclr" ,"ROCM_PATH" :str (root ), 5152"HIP_PATH" :str (root )}) 5153os .environ ["LD_LIBRARY_PATH" ]= os .pathsep .join (dirs + [os .environ .get ("LD_LIBRARY_PATH" ,"" )]).rstrip (os .pathsep ) 5154os .environ ["PATH" ]= os .pathsep .join ([str (root / "bin" ),str (root / "llvm" / "bin" ),os .environ .get ("PATH" ,"" )]) 5155say (" The engine's source changed: compiling it again (only what changed, a few minutes) ..." 5156if meta .get ("backend" )== "hip" and (eng / EXE ).exists ()and has_archs 5157else f" Compiling the Strata engine for your AMD GPU { 's' if len ( archs ) > 1 else '' } ( { ', ' . join ( archs ) } ; " 5158"10-20 minutes, once) ..." ) 5159cmake_build (ROOT ,ROOT / "build-hip" ,"strata" , 5160 ["-DSTRATA_ENABLE_HIP=ON" ,"-DSTRATA_ENABLE_CUDA=OFF" ,"-DSTRATA_BUILD_TESTS=OFF" , 5161"-DSTRATA_PREFILL_MMQ=ON" ,"-DSTRATA_Q6K_EXPERTS=ON" ,"-DSTRATA_MMQ_KQUANTS=ON" ,"-DCMAKE_HIP_ARCHITECTURES=" + ";" .join (archs ), 5162"-DSTRATA_MMQ=OFF" ,# without llama.cpp's MMQ, also in a build folder configured before (its cache says ON) 5163f"-DCMAKE_HIP_COMPILER= { root / 'llvm' / 'bin' / 'clang++' } " ,f"-DCMAKE_HIP_COMPILER_ROCM_ROOT= { root } " , 5164"-DCMAKE_PREFIX_PATH=" + ";" .join ([str (root ),* libs ]), 5165f"-DCMAKE_HIP_FLAGS=--rocm-path= { root } --rocm-device-lib-path= { bitcode } " , 5166* ggml_defs (llama ),* isa_floor_defs (floor ,ROOT / "build-hip" ,meta )],None ,"" ) 5167if stale_binary (ROOT / "build-hip" / EXE ):# #2054: no stamp for a binary of another version 5168fail (f"the engine build finished without a new engine ( { EXE } is version " 5169f" { binary_engine_version ( ROOT / 'build-hip' / EXE ) } , this source is { source_version () } ): " 5170"the installed engine is left as it was" ,"delete the folder build-hip and run this again" ) 5171shutil .copy2 (ROOT / "build-hip" / EXE ,eng / EXE ) 5172meta = {"source" :"local-hip" ,"backend" :"hip" ,"version" :source_version (),"archs" :archs ,"vision" :"none" , 5173"lib_dirs" :dirs ,"src" :src ,** ({"isa_floor" :floor }if floor else {})} 5174if vision != "none" : 5175return build_vision_hip (eng ,stamp ,meta ,llama ,vsrc ,archs ,vision ) 5176stamp .write_text (json .dumps (meta ,indent = 1 )) 5177ok (f"engine compiled: { eng / EXE } " ) 5178return eng 5179 5180 5181def hip_vision (asked ,vram_gb :float = 0.0 )-> str : 5182"""The picture reader wanted with the AMD backend (--vision): when nothing was asked or "yes" (pictures are on by default) the 5183default of strata_control/vision_reader.py for this card - the CPU reader under 24 GB, the GPU reader from 24 GB (owner decision 51842026-10-18, every make of card); "gpu" / "cpu" as asked (#304), "none" for no. "gpu" is a wish: hip_reader() settles it against 5185what the engine folder carries (the HIP reader, else the CPU one) once the engine is known.""" 5186from strata_control import vision_reader as VR 5187return VR .wanted (asked ,vram_gb ) 5188 5189 5190def reader_archs (eng :Path )-> list : 5191"""The GPU architectures the engine folder's HIP picture reader was built for: its BUILD.json (vision_archs, else archs), 5192else the component manifest's archs; [] when neither says (the reader then checks the card itself when it starts).""" 5193for name ,keys in (("BUILD.json" , ("vision_archs" ,"archs" )), ("engine-component.json" , ("archs" ,))): 5194try : 5195data = json .loads ((eng / name ).read_text (encoding = "utf-8-sig" )) 5196except (OSError ,ValueError ): 5197continue 5198for key in keys : 5199if isinstance (data ,dict )and arch_names (data .get (key )): 5200return arch_names (data .get (key )) 5201return [] 5202 5203 5204def hip_reader (eng :Path ,vision :str ,gpu :dict ): 5205"""AMD: the picture reader this engine folder gets for `vision` ("gpu" or "cpu"; strata_control/vision_reader.py): the HIP 5206reader with the CPU reader to fall back on, else the CPU reader. Returns (vision, Reader); a Reader of mode "none" means 5207the folder has no reader. The one plain note (a card the HIP reader has no code for, no HIP reader in this engine) is said.""" 5208from strata_control import vision_reader as VR 5209r = VR .choose (eng ,vision ,windows = WIN ,gpu_arch = str (gpu .get ("arch" )or "" ),archs = reader_archs (eng )) 5210if r .note : 5211warn (r .note ) 5212return r .mode ,r 5213 5214 5215def build_vision_hip (eng :Path ,stamp :Path ,meta :dict ,llama ,vsrc ,archs :list ,vision :str )-> Path : 5216"""The picture readers beside the HIP engine: the CPU reader always (the fallback), and for "gpu" the HIP reader 5217(tools/vision, STRATA_VISION_HIP) for the same architectures. The HIP reader needs the ROCm environment the engine build 5218sets; a build that fails leaves the CPU reader and says so (pictures still work, on the CPU).""" 5219if vision == "gpu" and not (shutil .which ("hipconfig" )or os .environ .get ("ROCM_PATH" )): 5220root ,dirs = rocm_root (archs )# the engine was built earlier: set the same environment again 5221os .environ .update ({"HIP_PLATFORM" :"amd" ,"HIP_COMPILER" :"clang" ,"HIP_RUNTIME" :"rocclr" ,"ROCM_PATH" :str (root ), 5222"HIP_PATH" :str (root )}) 5223os .environ ["LD_LIBRARY_PATH" ]= os .pathsep .join (dirs + [os .environ .get ("LD_LIBRARY_PATH" ,"" )]).rstrip (os .pathsep ) 5224os .environ ["PATH" ]= os .pathsep .join ([str (root / "bin" ),str (root / "llvm" / "bin" ),os .environ .get ("PATH" ,"" )]) 5225build_vision_cpu (eng ,stamp ,meta ,llama ,vsrc ) 5226meta = json .loads (stamp .read_text (encoding = "utf-8" )) 5227if vision != "gpu" : 5228return eng 5229root ,dirs = rocm_root (archs ) 5230libs = [str (Path (d ).parent )for d in dirs [1 :]] 5231bitcode = next ((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode" ,root / "amdgcn" / "bitcode" )if p .is_dir ()), 5232root / "amdgcn" / "bitcode" ) 5233say (" Compiling the picture reader for your AMD GPU (a few minutes, once) ..." ) 5234try : 5235cmake_build (ROOT / "tools" / "vision" ,ROOT / "build-vision-hip" ,"strata-vision" , 5236 [f"-DLLAMA_DIR= { vision_llama ( llama ) } " ,"-DSTRATA_VISION_HIP=ON" ,"-DSTRATA_VISION_HIP_ARCHS=" + ";" .join (archs ), 5237"-DSTRATA_PORTABLE=OFF" ,f"-DCMAKE_HIP_COMPILER= { root / 'llvm' / 'bin' / 'clang++' } " , 5238f"-DCMAKE_HIP_COMPILER_ROCM_ROOT= { root } " ,"-DCMAKE_PREFIX_PATH=" + ";" .join ([str (root ),* libs ]), 5239f"-DCMAKE_HIP_FLAGS=--rocm-path= { root } --rocm-device-lib-path= { bitcode } " ],None ,"" ) 5240shutil .copy2 (ROOT / "build-vision-hip" / "bin" / HVEXE ,eng / HVEXE ) 5241except SystemExit : 5242raise 5243except Exception as e :# noqa: BLE001 - the CPU reader is there; pictures work without the GPU one 5244warn (f"the GPU picture reader did not compile ( { e } ): pictures are read on the CPU" ) 5245return eng 5246stamp .write_text (json .dumps ({** meta ,"vision" :"gpu" ,"vision_archs" :archs ,"vision_gpu" :HVEXE ,"vision_cpu" :VEXE },indent = 1 )) 5247ok (f"picture reader (GPU): { eng / HVEXE } , (CPU fallback): { eng / VEXE } " ) 5248return eng 5249 5250 5251def build_vision_cpu (eng :Path ,stamp :Path ,meta :dict ,llama ,vsrc )-> Path : 5252"""#304: the CPU image encoder beside the HIP engine (tools/vision without CUDA), recorded in its BUILD.json.""" 5253if not ((eng / VEXE ).exists ()and meta .get ("vision_src" )== vsrc ): 5254say (" Compiling the image encoder (for the CPU) ..." ) 5255cmake_build (ROOT / "tools" / "vision" ,ROOT / "build-vision" ,"strata-vision" , 5256 [f"-DLLAMA_DIR= { vision_llama ( llama ) } " ,"-DSTRATA_VISION_CUDA=OFF" ,"-DSTRATA_PORTABLE=OFF" ], 5257find_vcvars ()if WIN else None , 5258"build-vision-cpu.bat" if WIN else "" )# #881: MSVC's environment on Windows, as the CUDA path has 5259shutil .copy2 (ROOT / "build-vision" / "bin" / VEXE ,eng / VEXE ) 5260stamp .write_text (json .dumps ({** meta ,"vision" :"cpu" ,"vision_src" :vsrc },indent = 1 )) 5261ok (f"engine: { eng / EXE } , image encoder (CPU): { eng / VEXE } " ) 5262return eng 5263 5264 5265# ------------------------------------------------------------------------------------------------ image generation 5266IMAGE_ENGINE = ROOT / "engine-image" # sd-cli for Qwen-Image-2.1-Turbo (tools/image/qimage.py), --images 5267 5268 5269def _qimage (): 5270if str (ROOT / "tools" / "image" )not in sys .path : 5271sys .path .insert (0 ,str (ROOT / "tools" / "image" )) 5272import qimage 5273return qimage 5274 5275 5276def get_sd_cpp ()-> Path : 5277"""stable-diffusion.cpp and its ggml at the pinned commits (tools/image/qimage.py), as zips: no git.""" 5278QI = _qimage () 5279src = ROOT / "third_party" / "stable-diffusion.cpp" 5280if QI .source_ok (src ): 5281return src 5282z1 = ROOT / "third_party" / f"stable-diffusion.cpp- { QI . SD_CPP_COMMIT [: 7 ] } .zip" 5283z2 = ROOT / "third_party" / f"sd-ggml- { QI . SD_GGML_COMMIT [: 7 ] } .zip" 5284download (QI .SD_CPP_ZIP ,z1 ,"stable-diffusion.cpp source" ) 5285download (QI .SD_GGML_ZIP ,z2 ,"stable-diffusion.cpp's ggml source" ) 5286try : 5287src = QI .unpack_source (ROOT / "third_party" ,z1 ,z2 ) 5288except zipfile .BadZipFile : 5289for z in (z1 ,z2 ): 5290drop_archive (z ) 5291raise 5292for z in (z1 ,z2 ): 5293z .unlink (missing_ok = True ) 5294z .with_name (z .name + ".done" ).unlink (missing_ok = True ) 5295return src 5296 5297 5298def vulkan_sdk ()-> Path | None : 5299"""What a Vulkan build of sd-cli needs (the Vulkan headers and glslc): $VULKAN_SDK, the distribution's packages, 5300else (Linux) the LunarG SDK unpacked into third_party (no sudo, ~370 MB). Returns the SDK folder it put on PATH, 5301None when the system's files are used.""" 5302QI = _qimage () 5303have = os .environ .get ("VULKAN_SDK" ) 5304if have and Path (have ).is_dir (): 5305return None 5306if not WIN and shutil .which ("glslc" )and Path ("/usr/include/vulkan/vulkan.h" ).exists (): 5307return None 5308if WIN : 5309fail ("compiling the image generator for this GPU (Vulkan) needs the Vulkan SDK" , 5310"install it from https://vulkan.lunarg.com/sdk/home#windows, open a new window and run setup again " 5311"(or --image-backend cpu)" ) 5312base = ROOT / "third_party" / "vulkan-sdk" 5313sdk = base / QI .VULKAN_SDK_VERSION / "x86_64" 5314if not (sdk / "bin" / "glslc" ).exists (): 5315import tarfile 5316tar = ROOT / "third_party" / f"vulkansdk- { QI . VULKAN_SDK_VERSION } .tar.xz" 5317download (QI .VULKAN_SDK_URL ,tar ,f"the Vulkan SDK { QI . VULKAN_SDK_VERSION } (LunarG, for compiling only)" ) 5318verify_sha256 (tar ,QI .VULKAN_SDK_SIZE ,QI .VULKAN_SDK_SHA256 ) 5319shutil .rmtree (base ,ignore_errors = True ) 5320base .mkdir (parents = True ) 5321with tarfile .open (tar )as t : 5322t .extractall (base ,** ({"filter" :"data" }if hasattr (tarfile ,"data_filter" )else {})) 5323tar .unlink (missing_ok = True ) 5324tar .with_name (tar .name + ".done" ).unlink (missing_ok = True ) 5325os .environ ["VULKAN_SDK" ]= str (sdk ) 5326os .environ ["PATH" ]= os .pathsep .join ([str (sdk / "bin" ),os .environ .get ("PATH" ,"" )]) 5327os .environ ["LD_LIBRARY_PATH" ]= os .pathsep .join ([str (sdk / "lib" / "VulkanLoader" / "lib" ), 5328os .environ .get ("LD_LIBRARY_PATH" ,"" )]).rstrip (os .pathsep ) 5329ok (f"Vulkan SDK: { sdk } " ) 5330return sdk 5331 5332 5333def apply_native_runner (src :Path )-> None : 5334"""I2: tools/image/sdcpp_native's runner into the stable-diffusion.cpp source (idempotent).""" 5335import importlib .util 5336QI = _qimage () 5337spec = importlib .util .spec_from_file_location ("strata_sdcpp_native_apply" ,QI .NATIVE_DIR / "apply.py" ) 5338mod = importlib .util .module_from_spec (spec ) 5339spec .loader .exec_module (mod ) 5340mod .apply (src ) 5341 5342 5343def apply_noise_generator (src :Path )-> None : 5344"""OWN-5 step 1: tools/image/sdcpp_noise's noise generator into the stable-diffusion.cpp source (idempotent; any 5345backend; sd-cli uses it only with --model-args strata_noise=1).""" 5346import importlib .util 5347QI = _qimage () 5348spec = importlib .util .spec_from_file_location ("strata_sdcpp_noise_apply" ,QI .NOISE_DIR / "apply.py" ) 5349mod = importlib .util .module_from_spec (spec ) 5350spec .loader .exec_module (mod ) 5351mod .apply (src ) 5352 5353 5354def apply_vae_decoder (src :Path )-> None : 5355"""OWN-5 step 2: Strata's VAE decoder (src/image/vae via tools/image/sdcpp_vae) into the stable-diffusion.cpp 5356source (idempotent; CUDA / HIP builds; sd-cli uses it only with --model-args strata_vae=1).""" 5357import importlib .util 5358QI = _qimage () 5359spec = importlib .util .spec_from_file_location ("strata_sdcpp_vae_apply" ,QI .VAE_DIR / "apply.py" ) 5360mod = importlib .util .module_from_spec (spec ) 5361spec .loader .exec_module (mod ) 5362mod .apply (src ) 5363 5364 5365def build_image_engine (backend :str ,gpu :dict ,noise :bool = False ,vae :bool = False )-> tuple [Path ,list [str ]]: 5366"""Compile sd-cli for `backend` into engine-image/ (again only when the pins or the backend changed, or, with 5367`noise`, the noise generator's sources) -> (its path, the library folders it runs with). `noise`: Strata's noise 5368generator is patched in (images "noise": "strata"); off, the build and its stamp are what they always were.""" 5369QI = _qimage () 5370IMAGE_ENGINE .mkdir (exist_ok = True ) 5371exe ,stamp = IMAGE_ENGINE / QI .SD_EXE ,IMAGE_ENGINE / "BUILD.json" 5372arch = gpu .get ("arch" )if backend in ("cuda" ,"hip" )else None 5373vae = vae and backend in QI .VAE_BACKENDS 5374want = QI .build_stamp (backend ,arch ,noise ,vae ) 5375meta = json .loads (stamp .read_text (encoding = "utf-8" ))if stamp .exists ()else {} 5376lib_dirs = [d for d in meta .get ("lib_dirs" )or []if Path (d ).is_dir ()] 5377if exe .exists ()and {k :meta .get (k )for k in want }== want : 5378ok (f"image generator already built ( { backend } )" ) 5379return exe ,lib_dirs 5380src = get_sd_cpp () 5381if backend in QI .NATIVE_BACKENDS :# Strata's DiT runner (inert unless the config asks for it) 5382apply_native_runner (src ) 5383if noise :# Strata's noise generator (inert unless the config asks for it) 5384apply_noise_generator (src ) 5385if vae :# Strata's VAE decoder (inert unless the config asks for it) 5386apply_vae_decoder (src ) 5387vcvars ,lib_dirs = None , [] 5388if backend == "cuda" : 5389nvcc ,cuda_v = find_nvcc () 5390if nvcc is None : 5391fail ("compiling the image generator for NVIDIA needs the CUDA Toolkit (nvcc)" , 5392"install it from https://developer.nvidia.com/cuda-downloads and run setup again " 5393"(or --image-backend vulkan / cpu)" ) 5394root = Path (nvcc ).resolve ().parent .parent 5395defs = QI .cmake_defs ("cuda" ,arch = arch ,cuda_root = root )+ [f"-DCMAKE_CUDA_COMPILER= { nvcc } " ]+ \ 5396host_compiler_defs (True ) 5397vcvars = find_vcvars (cuda_v )if WIN else None 5398lib_dirs = [str (root / "bin" )]if WIN else [str (d )for d in (root / "lib64" ,root / "lib" )if d .is_dir ()] 5399elif backend == "hip" : 5400root ,dirs = rocm_root ([arch ]) 5401os .environ .update ({"HIP_PLATFORM" :"amd" ,"ROCM_PATH" :str (root ),"HIP_PATH" :str (root )}) 5402os .environ ["LD_LIBRARY_PATH" ]= os .pathsep .join (dirs + [os .environ .get ("LD_LIBRARY_PATH" ,"" )]).rstrip (os .pathsep ) 5403defs = QI .cmake_defs ("hip" ,arch = arch ,rocm = root ) 5404lib_dirs = list (dirs ) 5405elif backend == "vulkan" : 5406sdk = vulkan_sdk () 5407defs = QI .cmake_defs ("vulkan" ) 5408vcvars = find_vcvars ()if WIN else None 5409if sdk is not None :# the SDK's loader (lib/VulkanLoader): CMake does not look there 5410loader = sdk / "lib" / "VulkanLoader" / "lib" 5411defs += [f"-DVulkan_LIBRARY= { loader / 'libvulkan.so' } " ,f"-DVulkan_INCLUDE_DIR= { sdk / 'include' } " , 5412f"-DVulkan_GLSLC_EXECUTABLE= { sdk / 'bin' / 'glslc' } " ] 5413import ctypes .util 5414if not ctypes .util .find_library ("vulkan" ): 5415lib_dirs = [str (loader )]# no system Vulkan loader to run with: the SDK's 5416else : 5417defs = QI .cmake_defs ("cpu" ) 5418vcvars = find_vcvars ()if WIN else None 5419say (f" Compiling the image generator (stable-diffusion.cpp { QI . SD_CPP_COMMIT [: 7 ] } , { backend } ; 5-20 minutes, " 5420"once) ..." ) 5421bdir = ROOT / f"build-image- { backend } " 5422cmake_build (src ,bdir ,"sd-cli" ,defs ,vcvars ,f"build-image- { backend } .bat" if WIN else "" ) 5423built = bdir / "bin" / QI .SD_EXE 5424if not built .exists (): 5425fail (f"the image generator's build finished without { built } " ,f"delete the folder { bdir . name } and run again" ) 5426shutil .copy2 (built ,exe ) 5427stamp .write_text (json .dumps ({** want ,"lib_dirs" :lib_dirs },indent = 1 )) 5428ok (f"image generator compiled: { exe } " ) 5429return exe ,lib_dirs 5430 5431 5432def image_backend_choice (a ,gpu :dict | None ,hip :bool )-> tuple [str ,str ,float ]: 5433"""--images: (backend, quant, the GPU memory in GB the quant was picked for). An explicit --image-quant above the 5434recommendation is kept, with a warning (recommend, never force).""" 5435QI = _qimage () 5436vendor = "amd" if hip else ((gpu or {}).get ("vendor" )or "nvidia" ) 5437backend = a .image_backend or QI .pick_backend ({** gpu ,"vendor" :vendor }if gpu else None ,WIN ) 5438gb = float ((gpu or {}).get ("vram_gb" )or 0.0 )if backend != "cpu" else 0.0 5439rec = QI .pick_quant (gb )if backend != "cpu" else "Q4_K_M" 5440quant = a .image_quant or rec 5441if QI .QUANTS .index (quant )> QI .QUANTS .index (rec ): 5442warn (f"image model { quant } : setup recommends { rec } for { gb :.0f } GB of GPU memory; kept as you chose " 5443"(stable-diffusion.cpp then keeps part of it in RAM, which is slower)" ) 5444return backend ,quant ,gb 5445 5446 5447def setup_images (a ,gpu :dict ,hip :bool ,models_dir :Path )-> dict | None : 5448"""--images qwen-image: sd-cli for this GPU and Qwen-Image-2.1-Turbo's three files -> the run config's "images" 5449section (serve/images.py); None for --images no, or when not wanted after all.""" 5450if not a .images or a .images == "no" : 5451return None 5452QI = _qimage () 5453backend ,quant ,_ = image_backend_choice (a ,gpu ,hip ) 5454say (f" Image generation: Qwen-Image-2.1-Turbo { quant } on { backend } (8 steps, CFG 1; POST /v1/images/generations)" ) 5455say (" " + QI .LICENSE_NOTE ) 5456need = sum (QI .FILES [k ][2 ]for k in (quant ,"vae" ,"llm" ))/ 1e9 5457if ask (f"Download the image model ( { need :.1f } GB) and set up image generation?" , ["y" ,"n" ],"y" ,a .yes )!= "y" : 5458return None 5459models_dir .mkdir (parents = True ,exist_ok = True ) 5460if free_gb (models_dir )< need + 5 : 5461warn (f"less than { need + 5 :.0f } GB free for the image model: the download may run out of disk space" ) 5462noise = getattr (a ,"image_noise" ,None )== "on" 5463vae = getattr (a ,"image_vae" ,None )== "on" 5464if vae and backend not in QI .VAE_BACKENDS :# the owner's wording, 11-11 5465warn (f"Strata's own picture decoder runs with CUDA or ROCm only; image generation on { backend } keeps " 5466"stable-diffusion.cpp's decoder" ) 5467vae = False 5468exe ,lib_dirs = build_image_engine (backend ,gpu or {},noise ,vae ) 5469for name in (quant ,"vae" ,"llm" ): 5470repo ,path ,size ,sha = QI .FILES [name ] 5471dst = QI .local_path (models_dir ,name ) 5472download (QI .file_url (name ,hf_endpoint ()),dst ,f"image model: { Path ( path ). name } " ) 5473verify_sha256 (dst ,size ,sha ) 5474cfg = QI .image_config (backend ,quant ,exe ,models_dir ,uma = QI .is_apu (gpu ),lib_dirs = lib_dirs , 5475policy = a .image_gpu_policy or "auto" ,native = getattr (a ,"image_native" ,None )== "on" , 5476noise = noise ,vae = vae ) 5477ok (f"image generation: { quant } on { backend } , GPU policy { cfg [ 'gpu_policy' ] } " ) 5478return cfg 5479 5480 5481# ------------------------------------------------------------------------------------------------ the engine 5482def driver_major (gpu ): 5483try : 5484return int (gpu ["driver" ].split ("." )[0 ]) 5485except (ValueError ,KeyError ): 5486return 0 5487 5488 5489class UnverifiedEngine (Exception ): 5490"""The engine archive could not be verified, with the reason. 5491 5492Raised rather than `fail()`-ed on purpose. The engine-UPDATE paths wrap their download in 5493`except Exception` and fall back to the engine already installed, so a refusal has to be an Exception: 5494`fail()` ends in `sys.exit(1)`, and SystemExit is a BaseException, so it flies past that guard and 5495kills the start instead. Measured on this change before the fix - a wrong hash, a wrong size and a 5496missing digest each escaped get_prebuilt(updating=True) as SystemExit(1). 5497""" 5498 5499 5500def release_of (base :str )-> tuple [str ,str | None ]| None : 5501"""("github", tag) for a GitHub release URL, or None when the URL is not one. 5502 5503`base` is one of the bases from `prebuilt_bases`: a `releases/download/v0.1.40/` URL (which names its 5504tag), the `releases/latest/download/` URL, or something else entirely - a local folder, a plain mirror. 5505That last case matters: it has no published digest, so treating it as "latest" would check the file 5506against a release the user did not ask for, over the network, which is wrong twice over. 5507 5508The repository comes out of the URL when it names one, so a fork's own releases are checked against 5509the fork rather than against Niko1221/Strata (which never has the fork's tags, so the check would 5510always fail). 5511""" 5512m = re .search (r"https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/releases/(?:download/v([^/]+)|latest)/" , 5513base ) 5514if not m : 5515return None 5516return f"https://api.github.com/repos/ { m . group ( 1 ) } / { m . group ( 2 ) } /releases" ,m .group (3 ) 5517 5518 5519def is_local (base :str )-> bool : 5520"""True for a path on this machine - `C:/mirror`, `/mnt/mirror`, `//share/engine`, `file://...`. 5521 5522A local folder is the user's own file on their own disk, the same trust decision as `--gguf-dir`, and 5523there is no published digest for it to be checked against. It is treated differently from a remote 5524mirror on purpose: nothing is between the file and setup, whereas a remote mirror has a network in the 5525middle and still no release to check it against. 5526""" 5527b = base .strip () 5528if b .lower ().startswith ("file://" ): 5529return True 5530return not re .match (r"^[a-z][a-z0-9+.\-]*://" ,b ,re .I ) 5531 5532 5533def engine_digest (asset :str ,base :str )-> tuple [int ,str ]| None : 5534"""(size, "sha256:<hex>") for `asset` in the release `base` points at, or None if GitHub will not say. 5535 5536The size and hash come from the releases API - a different origin from the download, which is the 5537whole point: a mirrored, substituted or TLS-intercepted download does not come with a matching digest, 5538while a compromised release does (see `verify_engine_archive` for what that leaves uncovered). 5539 5540GitHub populates `digest` for every asset, including ones uploaded before the field existed 5541(measured on v0.1.34 through v0.1.40.1). None means no answer - no network, a rate limit, or a 5542release that does not publish one - and the caller warns and installs anyway (never refuses). 5543""" 5544where = release_of (base ) 5545if where is None :# a local folder or a plain mirror: nothing published to check against 5546return None 5547releases ,tag = where 5548url = f" { releases } /tags/v { tag } " if tag else f" { releases } /latest" 5549try : 5550req = urllib .request .Request (url ,headers = {"User-Agent" :"strata-setup" , 5551"Accept" :"application/vnd.github+json" }) 5552with _urlopen (req ,timeout = 60 )as r : 5553rel = json .loads (r .read ().decode ("utf-8" )) 5554except Exception : 5555return None # offline, rate-limited, or the release is not there 5556for a in rel .get ("assets" )or []: 5557if a .get ("name" )== asset and a .get ("digest" )and str (a .get ("digest" )).startswith ("sha256:" ): 5558return int (a .get ("size" )or 0 ),str (a ["digest" ]).split (":" ,1 )[1 ] 5559return None 5560 5561 5562def drop_download (z :Path )-> None : 5563"""The archive and its finish mark. A refused engine is not left where a later run would reuse it.""" 5564z .unlink (missing_ok = True ) 5565z .with_name (z .name + ".done" ).unlink (missing_ok = True ) 5566 5567 5568def verify_engine_archive (z :Path ,asset :str ,base :str )-> None : 5569"""The downloaded engine archive against the published size and SHA-256, before it is unpacked. 5570 5571Without this, a ready-made engine is installed on nothing more than the byte count matching the 5572server's Content-Length - and a substituted file of the same length passes that. It runs before the 5573archive is opened, so a wrong engine never reaches `_unpack`, let alone the engine directory. 5574 5575Raises UnverifiedEngine on a refusal; the caller decides whether that stops setup (a first install, 5576with nothing to fall back to) or keeps the engine that is already there (an update). 5577 5578Where the hash comes from, and where it cannot: 5579 5580- a GitHub release URL: the tag is read out of the URL, so the exact release the bytes claim to come 5581from is the one checked rather than "latest" (setup tries the checkout's own release first, #214), 5582and the repository comes out of the URL too, so a fork's releases are checked against the fork; 5583- a local folder (`--prebuilt D:/mirror`): nothing published to check against. This warns and goes 5584ahead - it is the user's own file, the same trust decision as `--gguf-dir`, and there is nothing an 5585API could say about it; 5586- any other remote mirror: nothing published to check against either, but a network is in the middle, 5587so it warns and installs anyway (no digest is never a reason to refuse). 5588 5589What a digest from the API does NOT cover, stated plainly: it proves the bytes are the ones GitHub 5590published for that asset, so it catches a corrupted transfer, a mirror or proxy that substituted the 5591file, and a hostile network. It does not make a malicious RELEASE safe - if whoever can publish a 5592release publishes a hostile engine, the digest matches it. Only a hash pinned in this file closes 5593that, at the cost of a commit per release; a dict of tag -> sha next to `engine_digest` is where one 5594would go. 5595 5596The size and the hashing below are spelled out rather than delegated to `verify_sha256`, for two 5597reasons, both measured here. That function ends in `fail()`, and a refusal has to be an Exception so 5598the update paths can fall back. And it keeps a `.done` mark so 111 GB of Unsloth shards is hashed 5599once; the engine archive is 190 MB, which hashes in 0.79 s at 242 MB/s on this machine, against 3.0 s 5600to download the same file. A mark that saves 0.8 s is not worth a class of hole - anything that 5601changes the file after it was verified, at any length - so there is no mark here. 5602""" 5603if os .environ .get ("STRATA_SKIP_SHA256" )== "1" : 5604warn (f"STRATA_SKIP_SHA256=1: NOT checking { asset } against its SHA-256. If the file is corrupt or " 5605f"tampered with, it will be installed anyway. Unset it to get the check back." ) 5606return 5607want = engine_digest (asset ,base )# one API call: this is a rate-limited API 5608if not want : 5609# no published digest (offline, rate limit, a mirror or folder): install anyway, never refuse 5610warn (f"could not get a SHA-256 for { asset } from GitHub (offline, rate limited, or not a release " 5611f"URL), so it was NOT verified. Installing it as it is." ) 5612return 5613size ,sha = want 5614have = z .stat ().st_size if z .exists ()else - 1 5615if have != size : 5616drop_download (z ) 5617raise UnverifiedEngine (f" { z . name } is { have :, } bytes, not the published { size :, } " ) 5618h = hashlib .sha256 () 5619with open (z ,"rb" )as f : 5620while True : 5621b = f .read (16 << 20 ) 5622if not b : 5623break 5624h .update (b ) 5625if h .hexdigest ()!= sha : 5626got = h .hexdigest () 5627drop_download (z ) 5628raise UnverifiedEngine (f" { z . name } has the wrong SHA-256 ( { got } , expected { sha } )" ) 5629ok (f" { z . name } : SHA-256 checksum verified against GitHub's ( { sha [: 12 ] } ...)" ) 5630 5631 5632def engine_refused (asset :str ,e :Exception ,updating :bool )-> None : 5633"""Report a refusal and either stop setup or keep the engine that is installed. 5634 5635A first install has nothing to fall back to, so it stops. An update does: the engine already in 5636place is untouched by a refusal (nothing has been unpacked), it works, and stopping the model from 5637starting over a hash is worse than keeping what is there - which is the whole reason that call site 5638catches what the download can throw. 5639""" 5640if not updating : 5641fail (f"the downloaded Strata engine does not match GitHub's checksum: { e } " , 5642"the bad download has been deleted (corrupt or tampered), so the next run fetches the " 5643"published file again. Set STRATA_SKIP_SHA256=1 only if you insist on installing it anyway" ) 5644return 5645warn (f"keeping the engine that is installed: { e } " ) 5646say (" Nothing was replaced. The bad download was deleted; run setup again to fetch it afresh." ) 5647 5648 5649def prebuilt_bases (url_base )-> list [str ]: 5650"""Where to look for the ready-made engine, in order (each ending in a slash). The default: the release of this 5651checkout's version first, then the latest (#214); an explicit --prebuilt / STRATA_PREBUILT_URL: only that.""" 5652base = url_base if url_base .endswith (("/" ,"\\" ))else url_base + "/" 5653if base != PREBUILT_URL : 5654return [base ] 5655version = source_version () 5656if version == "0" :# no source tree to name a release by (the packaged Terminal): the latest release 5657return [base ] 5658return [PREBUILT_TAG_URL .format (version = version ),base ] 5659 5660 5661PREVIOUS_ENGINE = ".previous" 5662 5663 5664def engine_version_of (folder :Path )-> str : 5665try : 5666return str (json .loads ((folder / "BUILD.json" ).read_text (encoding = "utf-8" )).get ("version" ,"?" )) 5667except (OSError ,ValueError ): 5668return "?" 5669 5670 5671def install_unpacked (tmp :Path ,eng :Path )-> None : 5672"""#670: the unpacked engine (tmp) replaces the installed one in `eng`, which is kept, one generation, in 5673eng/.previous (about 210 MiB): a new engine that turns out bad has a way back (`setup.py --rollback-engine`). The 5674swap is all or nothing: a failure part-way puts the old files back instead of leaving a mix of old and new.""" 5675prev = eng / PREVIOUS_ENGINE 5676new = list (tmp .iterdir ()) 5677old = [eng / p .name for p in new if p .name != PREVIOUS_ENGINE and (eng / p .name ).exists ()] 5678if (eng / KQ_LIB ).exists ()and all (p .name != KQ_LIB for p in new ):# a zip without strata_kq: an older one of 5679old .append (eng / KQ_LIB )# another build would only be refused (kept in .previous too) 5680shutil .rmtree (prev ,ignore_errors = True ) 5681moved ,placed = [], [] 5682try : 5683if old : 5684prev .mkdir () 5685for dst in old : 5686shutil .move (str (dst ),str (prev / dst .name )) 5687moved .append (dst ) 5688for p in new : 5689p .replace (eng / p .name ) 5690placed .append (eng / p .name ) 5691except OSError : 5692for dst in placed :# back to the old engine, whole 5693shutil .rmtree (dst )if dst .is_dir ()else dst .unlink (missing_ok = True ) 5694for dst in moved : 5695shutil .move (str (prev / dst .name ),str (dst )) 5696shutil .rmtree (prev ,ignore_errors = True ) 5697raise 5698# #1403 debt: get_prebuilt moved the old BUILD.json aside (BUILD.json.prev) instead of deleting it; it goes with the 5699# engine it describes, so engine_version_of(.previous) says the version instead of "?" 5700kept = eng / "BUILD.json.prev" 5701if kept .exists (): 5702try : 5703if moved and not (prev / "BUILD.json" ).exists (): 5704shutil .move (str (kept ),str (prev / "BUILD.json" )) 5705else : 5706kept .unlink () 5707except OSError : 5708pass 5709if moved : 5710ok (f"the engine it replaced ( { engine_version_of ( prev ) } ) is kept in { prev } ; " 5711"setup.py --rollback-engine puts it back" ) 5712 5713 5714def rollback_engine (toolkit = 13 )-> int : 5715"""#670: `setup.py --rollback-engine`: the engine kept in engine/.previous becomes the installed one again, and the 5716one it replaces is kept in its place (run it again to go forward).""" 5717eng = engine_dir (toolkit ) 5718prev = eng / PREVIOUS_ENGINE 5719if not prev .is_dir ()or not any (prev .iterdir ()): 5720warn (f"no earlier engine is kept in { prev } (one is kept when an update replaces the engine)" ) 5721return 1 5722swap = eng / ".swap" 5723shutil .rmtree (swap ,ignore_errors = True ) 5724swap .mkdir () 5725was = engine_version_of (eng ) 5726for p in list (prev .iterdir ()):# what the earlier engine has: the current copy goes aside 5727cur = eng / p .name 5728if cur .exists (): 5729shutil .move (str (cur ),str (swap / p .name )) 5730shutil .move (str (p ),str (cur )) 5731for p in list (swap .iterdir ()): 5732shutil .move (str (p ),str (prev / p .name )) 5733shutil .rmtree (swap ,ignore_errors = True ) 5734ok (f"engine { engine_version_of ( eng ) } is installed again (it replaced { was } , which is kept in { prev } )" ) 5735return 0 5736 5737 5738def get_prebuilt (url_base ,gpu ,vision ,updating = False ,toolkit = 13 )-> Path | None : 5739"""The ready-made engine in engine/ (kept between runs), or None when there is none for this PC. 5740updating: called to replace an installed engine, which starts instead when this fails (no compile). 5741toolkit 12: the experimental CUDA 12 engine (CUDA12_ASSET) in engine-cuda12/.""" 5742acquisition .require ("the ready-made engine" ) 5743eng = engine_dir (toolkit ) 5744asset = CUDA12_ASSET if int (toolkit )== 12 else PREBUILT_ASSET 5745info = eng / "BUILD.json" 5746if info .exists ()and (eng / EXE ).exists ()and json .loads (info .read_text (encoding = "utf-8" )).get ("backend" )!= "hip" : 5747meta = json .loads (info .read_text (encoding = "utf-8" )) 5748ver = tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ()) 5749if meta .get ("source" )== "local" :# compiled here: build_engine checks its source and cards 5750return None 5751have = arch_numbers (meta .get ("archs" )) 5752miss = [int (x )for x in gpu .get ("archs" , [gpu ["arch" ]]) 5753if have and int (x )not in have and not (meta .get ("ptx" )and int (x )> max (have ))] 5754if miss :# a card it has no code for (#128): compiled here instead 5755warn (f"the installed engine is built for { ', ' . join ( str ( a ) for a in have ) } ; your GPU is " 5756f" { ', ' . join ( str ( x ) for x in miss ) } : compiling instead" ) 5757return None 5758if ver >= MIN_ENGINE : 5759ok ("ready-made engine already installed" ) 5760return eng 5761say (f" Updating the ready-made engine ( { meta . get ( 'version' ) } -> { '.' . join ( map ( str , MIN_ENGINE )) } or newer) ..." ) 5762info .replace (eng / "BUILD.json.prev" )# kept for the .previous copy 5763if is_arm64 ()and sys .platform .startswith ("linux" ): 5764# a DGX Spark: the release has no flat engine zip for it (and the CUDA 12 engine is x86). The signed feed has the linux-aarch64 5765# package when the release carries one; without it the caller compiles (spark/build_engine.sh does the same by hand) 5766got = engine_from_feed (eng ,updating )if int (toolkit )!= 12 else None 5767if got is None : 5768warn (f"no ready-made engine for { sysinfo . machine () } in the update feed" + ("" if updating else ": compiling it here, once" )) 5769return got 5770if not url_base : 5771return None 5772eng .mkdir (exist_ok = True ) 5773z = eng / asset 5774bases = prebuilt_bases (url_base ) 5775for i ,base in enumerate (bases ): 5776if not base .startswith (("http://" ,"https://" )): 5777break 5778try :# not published (yet), or no internet: compile instead 5779req = urllib .request .Request (base + asset ,method = "HEAD" ,headers = {"User-Agent" :"strata-setup" }) 5780_urlopen (req ,timeout = 60 ).close () 5781break 5782except OSError as e : 5783if i + 1 < len (bases ):# #214: this checkout's release is not published (yet) 5784say (f" No ready-made engine for v { source_version () } ( { e } ): the latest release instead" ) 5785continue 5786if int (toolkit )!= 12 :# 0.2 releases: the signed feed has it (#3469) 5787got = engine_from_feed (eng ,updating ) 5788if got is not None : 5789return got 5790warn (f"no ready-made engine at { base } ( { e } )" + ("" if updating else ": compiling instead" )) 5791return None 5792say (" Downloading the ready-made Strata engine" + (" (CUDA 12, experimental)" if int (toolkit )== 12 else "" )+ " ..." ) 5793download (base + asset ,z ,"Strata engine" ) 5794try : 5795verify_engine_archive (z ,asset ,base ) 5796except UnverifiedEngine as e : 5797engine_refused (asset ,e ,updating ) 5798return None 5799tmp = eng / "_unpack" 5800shutil .rmtree (tmp ,ignore_errors = True ) 5801try : 5802with zipfile .ZipFile (z )as f : 5803f .extractall (tmp ) 5804except zipfile .BadZipFile :# not a zip, or a damaged one: a kept .done mark would make 5805drop_archive (z )# every later run fail on it instead of downloading it again 5806raise 5807meta = json .loads ((tmp / "BUILD.json" ).read_text (encoding = "utf-8" )) 5808if tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ())< MIN_ENGINE : 5809need = "." .join (map (str ,MIN_ENGINE )) 5810if updating :# these files are newer than the published release (#58) 5811warn (f"engine { need } is not published yet (the release may still be uploading): run this again " 5812f"in a few minutes to update it" ) 5813else : 5814warn (f"the ready-made engine at { base } is version { meta . get ( 'version' ) } ; this setup needs " 5815f" { need } : compiling instead" ) 5816shutil .rmtree (tmp ,ignore_errors = True ) 5817drop_archive (z ) 5818return None 5819archs = arch_numbers (meta .get ("archs" )) 5820miss = [int (x )for x in gpu .get ("archs" , [gpu ["arch" ]]) 5821if int (x )not in archs and not (meta .get ("ptx" )and int (x )> max (archs ))] 5822if miss : 5823warn (f"the ready-made engine is built for { ', ' . join ( str ( a ) for a in archs ) } ; your GPU is " 5824f" { ', ' . join ( str ( x ) for x in miss ) } " + ("" if updating else ": compiling instead" )) 5825shutil .rmtree (tmp ,ignore_errors = True ) 5826drop_archive (z ) 5827return None 5828install_unpacked (tmp ,eng ) 5829shutil .rmtree (tmp ,ignore_errors = True ) 5830drop_archive (z ) 5831if not (eng / EXE ).exists (): 5832fail ("the ready-made engine archive has no " + EXE ) 5833if not WIN : 5834for x in (EXE ,VEXE ): 5835if (eng / x ).exists (): 5836 (eng / x ).chmod (0o755 ) 5837ok (f"ready-made engine { meta . get ( 'version' , '' ) } for { ', ' . join ( 'sm_' + str ( a ) for a in archs ) } (CUDA " 5838f" { meta . get ( 'cuda' , '?' ) } )" ) 5839return eng 5840 5841 5842def update_engine_gpu (toolkit = 13 ): 5843"""#1485: the card an engine update is for. Not simply the one with the most VRAM: a Tesla V100 (32 GB) beside two 5844RTX 4090s was taken, and CUDA 13 cannot compile for it. The cards the installed models are set up for come 5845first (their "gpu"); for the CUDA 13 engine a card it cannot compile for is left out when another can. An 5846explicit --gpu (GPU_PICK) still wins. None when there is no NVIDIA GPU.""" 5847if GPU_PICK is not None : 5848return gpu_info () 5849found = gpus () 5850if not found : 5851return None 5852named = set () 5853for c in installed_configs (): 5854try : 5855g = json .loads (c .read_text (encoding = "utf-8-sig" )).get ("gpu" ) 5856except (OSError ,ValueError ): 5857continue 5858named .update (i for i in (g if isinstance (g ,list )else [g ])if isinstance (i ,int )and not isinstance (i ,bool )) 5859pool = [g for g in found if g ["index" ]in named ]or found 5860if int (toolkit )!= 12 : 5861pool = [g for g in pool if int (g ["arch" ])>= CUDA13_MIN_ARCH ]or pool 5862g = max (pool ,key = lambda x : (round (x ["vram_gb" ]),- x ["index" ])) 5863return {** g ,"count" :len (found )} 5864 5865 5866def engine_update_note ()-> None : 5867"""A start looks at the installed engine(s) and says when UPDATE would replace one; it changes nothing and reaches 5868no network (the engine that is installed starts as it is). update_installed_engine, below, is what UPDATE.bat / 5869update.sh and a setup run do.""" 5870for toolkit in (13 ,12 ): 5871eng = engine_dir (toolkit ) 5872info = eng / "BUILD.json" 5873if not info .exists ()or not (eng / EXE ).exists (): 5874continue 5875try : 5876meta = json .loads (info .read_text (encoding = "utf-8" )) 5877except (OSError ,ValueError ): 5878continue 5879ver = tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ()) 5880need = WIN_HIP_MIN_ENGINE if (meta .get ("backend" )== "hip" and WIN )else MIN_ENGINE 5881if meta .get ("source" )== "local" : 5882old = meta .get ("src" )!= source_hash (ENGINE_SOURCES )or stale_binary (eng / EXE ) 5883elif meta .get ("backend" )== "hip" and not WIN : 5884old = meta .get ("src" )!= source_hash (ENGINE_SOURCES )or stale_binary (eng / EXE ) 5885else : 5886old = ver < need 5887if old : 5888warn (f"the installed engine ( { meta . get ( 'version' ) or 'unknown version' } ) is older than this Strata expects: " 5889"starting it as it is. Starting never updates anything; run " 5890+ ("UPDATE.bat" if WIN else "./update.sh" )+ " (or `strata install --update`) to update it" ) 5891 5892 5893def update_installed_engine (url_base ,toolkit = None )-> None : 5894"""An installed ready-made engine older than MIN_ENGINE is replaced before the model starts, so a plain 5895START-HERE.bat on an existing install picks up a new release. If that cannot happen (no internet, the model 5896still running, no ready-made engine for this GPU) the installed engine is kept and starts as before. 5897toolkit None: engine/, then the experimental CUDA 12 engine in engine-cuda12/ when one is installed.""" 5898if toolkit is None : 5899update_installed_engine (url_base ,13 ) 5900if (engine_dir (12 )/ "BUILD.json" ).exists (): 5901update_installed_engine (url_base ,12 ) 5902return 5903eng = engine_dir (toolkit ) 5904info = eng / "BUILD.json" 5905if not info .exists ()or not (eng / EXE ).exists (): 5906return 5907meta_text = info .read_text (encoding = "utf-8" ) 5908meta = json .loads (meta_text ) 5909if meta .get ("backend" )== "hip" and WIN :# AMD on Windows: the ready-made HIP engine, when older 5910ver = tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ()) 5911if meta .get ("source" )== "prebuilt" and ver < WIN_HIP_MIN_ENGINE : 5912try : 5913g = next ((x for x in amd_gpus ()if amd_problem (x )is None ),None ) 5914if g is None : 5915raise RuntimeError ("no supported AMD GPU found" ) 5916say (f" Updating the ready-made AMD engine ( { meta . get ( 'version' ) } -> " 5917f" { '.' . join ( map ( str , WIN_HIP_MIN_ENGINE )) } or newer) ..." ) 5918if get_prebuilt_hip (url_base ,g ,updating = True )is None : 5919raise RuntimeError ("not published yet" ) 5920except (Exception ,SystemExit )as e : 5921warn (f"could not update the AMD engine { '' if isinstance ( e , SystemExit ) else f' ( { e } )' } : " 5922"starting the installed one" ) 5923return 5924if meta .get ("backend" )== "hip" :# AMD: compiled here, again when its source changed 5925if meta .get ("src" )!= source_hash (ENGINE_SOURCES )or stale_binary (eng / EXE ): 5926try : 5927usable = [x for x in amd_gpus ()if amd_problem (x )is None ] 5928g = next ((x for x in usable if x ["arch" ]in arch_names (meta .get ("archs" ))),usable [0 ]if usable else None ) 5929if g is None : 5930raise RuntimeError ("no supported AMD GPU found" ) 5931# every architecture it was built for (a layer split across two families keeps both) 5932build_engine_hip ({** g ,"archs" : [x for x in arch_names (meta .get ("archs" ))if x in AMD_ARCHS ]or [g ["arch" ]]}, 5933llama_override (),meta .get ("vision" )or "none" ) 5934except (Exception ,SystemExit )as e : 5935warn (f"could not compile the updated engine { '' if isinstance ( e , SystemExit ) else f' ( { e } )' } : " 5936"starting the installed one" ) 5937return 5938ver = tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ()) 5939local = meta .get ("source" )== "local" 5940vision = meta .get ("vision" )or "none" 5941if local :# compiled here: is it older than the source (a git pull)? 5942if meta .get ("src" )== source_hash (ENGINE_SOURCES )and not stale_binary (eng / EXE )and \ 5943 (vision == "none" or meta .get ("vision_src" )== source_hash (VISION_SOURCES )): 5944return 5945elif ver >= MIN_ENGINE : 5946return 5947try :# a running engine cannot be replaced (Windows keeps it locked) 5948for x in (EXE ,VEXE ): 5949if (eng / x ).exists (): 5950with open (eng / x ,"r+b" ): 5951pass 5952except OSError : 5953warn (f"engine { meta . get ( 'version' ) or '' } is in use: close the model window and run this again to update it" ) 5954return 5955gpu = update_engine_gpu (toolkit ) 5956if local : 5957try :# a failed compile must not stop the model from starting 5958if gpu is None : 5959raise RuntimeError ("no NVIDIA GPU found" ) 5960gpu = {** gpu ,"archs" :sorted ({int (gpu ["arch" ]),* arch_numbers (meta .get ("archs" ))})} 5961if int (toolkit )== 12 :# the cards it was compiled for (the main GPU may be newer) 5962gpu ["archs" ]= sorted (arch_numbers (meta .get ("archs" )))or gpu ["archs" ] 5963build_engine (gpu ,vision ,False ,llama_override (),toolkit = toolkit ) 5964except (Exception ,SystemExit )as e : 5965warn (f"could not compile the updated engine { '' if isinstance ( e , SystemExit ) else f' ( { e } )' } : starting the installed one" ) 5966return 5967new = None 5968if gpu is not None : 5969try : 5970if int (toolkit )== 12 :# the cards the CUDA 12 engine serves, not the newest one 5971gpu = {** gpu ,"archs" : [x for x in arch_numbers (meta .get ("archs" ))if x < CUDA13_MIN_ARCH ] 5972or [int (gpu ["arch" ])]} 5973new = get_prebuilt (url_base ,gpu ,"gpu" ,updating = True ,toolkit = toolkit ) 5974except Exception as e :# a failed download must not stop the model from starting 5975warn (f"updating the engine failed ( { e } )" ) 5976if new is None : 5977if not info .exists (): 5978info .write_text (meta_text )# get_prebuilt drops it before downloading: put it back 5979warn (f"could not update the engine: starting the installed { meta . get ( 'version' ) } " ) 5980return 5981pip_cuda_libs (toolkit ) 5982 5983 5984def pip_cuda_libs (toolkit = 13 )-> None : 5985"""NVIDIA's cuBLAS and CUDA runtime for a ready-made engine, from pip: CUDA 13's, or the CUDA 12 engine's.""" 5986acquisition .require ("NVIDIA's CUDA libraries (pip)" ) 5987if int (toolkit )== 12 : 5988pip_install (CUDA12_WHEELS ,"NVIDIA CUDA 12 libraries for the experimental engine (cuBLAS, CUDA runtime; ~0.7 GB)" ) 5989else : 5990pip_install (CUDA_WHEELS ,"NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)" ) 5991 5992 5993CUDA_SM120_SUSPECT = (13 ,2 )# #892 #968: nvcc 13.2.0 / 13.2.1 (build 13.2.51) for sm_120 made garbage answers (IQ1_S / IQ2_S / IQ3_S) and prompts 5994# (K-quant MMQ) that the same source compiled with 13.0.88 answers correctly (llama.cpp hit it too) 5995CUDA_SM120_FIXED_BUILD = 86 # CUDA 13.2.2 (nvcc build 13.2.86) fixes it (ggml-org/llama.cpp#28581, confirmed on a 5090 in #968) 5996 5997 5998def nvcc_build (nvcc ): 5999"""The build number of an nvcc ("Build cuda_13.2.r13.2/compiler...", "V13.2.86" -> 86); None when it cannot be read.""" 6000m = re .search (r"\bV\d+\.\d+\.(\d+)" ,out ([nvcc ,"--version" ])if nvcc else "" ) 6001return int (m .group (1 ))if m else None 6002 6003 6004def sm120_nvcc (nvcc ,cuda_v ,archs ): 6005"""#892 / #968: CUDA 13.2.0 / 13.2.1's nvcc for an RTX 50 card (sm_120). Returns (nvcc, cuda_v): an older 13.x toolkit 6006when one is installed and the user did not name a compiler (STRATA_NVCC), else the one found, with a warning that says 6007what to do. CUDA 13.2.2 (build 86 or newer) is fine. Recommends, never forces: a user who picked 13.2 keeps it.""" 6008if not nvcc or cuda_v != CUDA_SM120_SUSPECT or max (archs )< 120 : 6009return nvcc ,cuda_v 6010build = nvcc_build (nvcc ) 6011if build is not None and build >= CUDA_SM120_FIXED_BUILD : 6012return nvcc ,cuda_v 6013if not os .environ .get ("STRATA_NVCC" ): 6014alt ,alt_v = find_nvcc (below = CUDA_SM120_SUSPECT ) 6015if alt and alt_v and alt_v >= (13 ,0 ): 6016ok (f"CUDA { alt_v [ 0 ] } . { alt_v [ 1 ] } is used for the RTX 50 card (sm_120): CUDA 13.2.0 / 13.2.1's compiler made wrong " 6017"answers there (#892, #968); STRATA_NVCC=<nvcc> picks another" ) 6018return alt ,alt_v 6019warn ("CUDA 13.2.0 and 13.2.1's compiler (nvcc) made garbage prompts and answers for RTX 50 cards (sm_120) in two " 6020"reports (#892, #968): the same source compiled with CUDA 13.0, 13.1 or 13.2.2 is right. If the engine answers " 6021"with nonsense, update to CUDA 13.2.2 or install CUDA 13.0 next to it (https://developer.nvidia.com/cuda-toolkit-archive) " 6022"and set STRATA_NVCC to its nvcc; the ready-made engine is built with 13.0" ) 6023return nvcc ,cuda_v 6024 6025 6026def cuda_apt_repo (osr ): 6027"""The NVIDIA apt repo for this distribution ("ubuntu2404", "debian13") from /etc/os-release, or None when it is 6028not one setup adds the CUDA keyring for. Both families publish cuda-keyring and CUDA 13.x.""" 6029ver = osr .get ("VERSION_ID" ,"" ).strip ('"' ).replace ("." ,"" ) 6030repo = {"ubuntu" :"ubuntu" ,"debian" :"debian" }.get (osr .get ("ID" ,"" ),"" )+ ver 6031return repo if repo in ("ubuntu2204" ,"ubuntu2404" ,"debian12" ,"debian13" )else None 6032 6033 6034def install_build_tools (gpu ,yes ): 6035"""The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars).""" 6036acquisition .require ("the compiler and CUDA toolkit" ) 6037archs = [int (x )for x in gpu .get ("archs" , [gpu ["arch" ]])] 6038# #295: Pascal / Volta need a CUDA 12.x toolkit - CUDA 13 cannot build sm_60/sm_70; gpu["toolkit"] = 12: the 6039# experimental CUDA 12 engine for any cards (--cuda 12, docs/OLDER_GPUS.md) 6040old = int (gpu .get ("toolkit" )or (12 if min (archs )< CUDA13_MIN_ARCH else 13 ))== 12 6041need12 = (12 ,8 )if max (archs )>= 120 else (12 ,0 )# sm_120 needs CUDA 12.8 or newer 6042if old and max (archs )>= 120 : 6043warn ("an RTX 50 card (sm_120) in a CUDA 12 engine: engines built with CUDA 12.8 crashed on long prompts there " 6044"(#220, #224); the RTX 50 card alone (--gpu N) runs the ready-made CUDA 13 engine" ) 6045nvcc ,cuda_v = find_nvcc (below = (13 ,0 ))if old else find_nvcc () 6046if old and (nvcc is None or cuda_v < need12 ): 6047fail ("the experimental CUDA 12 engine (Pascal / Volta, or --cuda 12) is compiled here with the NVIDIA CUDA " 6048f"Toolkit { need12 [ 0 ] } . { need12 [ 1 ] } or a newer 12.x (CUDA 13 cannot compile for these cards)" + 6049 (f"; found CUDA { cuda_v [ 0 ] } . { cuda_v [ 1 ] } " if nvcc else "" ), 6050"install CUDA 12.9 (it can sit next to a newer one) from https://developer.nvidia.com/cuda-toolkit-archive " 6051"and run it again (STRATA_NVCC=<its nvcc> picks one toolkit)" ) 6052# RTX 50 (sm_120): CUDA 13.0 - an engine built with 12.8 crashed in the prompt path on Linux (#220) 6053need_cuda = need12 if old else (13 ,0 )if max (archs )>= 120 else (12 ,0 ) 6054vcvars = find_vcvars (cuda_v )if WIN else None 6055have_cc = vcvars is not None if WIN else shutil .which ("g++" )is not None 6056missing = [] 6057if not have_cc : 6058missing .append ("Visual Studio 2022 Build Tools (C++)" if WIN else "the C++ compiler (build-essential)" ) 6059if nvcc is None or cuda_v < need_cuda : 6060missing .append ("the NVIDIA CUDA Toolkit 13.0" ) 6061if not missing : 6062nvcc ,cuda_v = sm120_nvcc (nvcc ,cuda_v ,archs ) 6063ok (f"build tools present (CUDA { cuda_v [ 0 ] } . { cuda_v [ 1 ] } )" ) 6064return nvcc ,vcvars 6065say (" The engine has to be compiled for your PC, which needs: " + " and " .join (missing )+ "." ) 6066say (" They can be installed now (about 8-10 GB, 15-40 minutes" + (", Windows will ask for permission" if WIN else 6067", sudo will ask for your password" )+ ")." ) 6068if ask (" Install them now?" , ["y" ,"n" ],"y" ,yes )!= "y" : 6069fail ("the build tools are needed" ,"install them yourself (see README.md) and run it again" ) 6070if WIN : 6071if shutil .which ("winget" )is None : 6072fail ("winget (Windows package manager) is not available" , 6073"install 'App Installer' from the Microsoft Store, or install the tools by hand (README.md)" ) 6074wg = ["winget" ,"install" ,"-e" ,"--source" ,"winget" ,"--accept-package-agreements" , 6075"--accept-source-agreements" ,"--disable-interactivity" ] 6076if not have_cc : 6077run ([* wg ,"--id" ,"Microsoft.VisualStudio.2022.BuildTools" ,"--override" , 6078"--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended" ], 6079check = False ) 6080if nvcc is None or cuda_v < need_cuda : 6081run ([* wg ,"--id" ,"Nvidia.CUDA" ,"--version" ,"13.0" ],check = False ) 6082vcvars = find_vcvars (cuda_v ) 6083else : 6084apt = shutil .which ("apt-get" ) 6085if apt is None : 6086fail ("missing: " + " and " .join (missing )+ " (the automatic install is only done on Ubuntu/Debian)" , 6087"install them with your distribution's packages (Arch: pacman -S base-devel cuda; nvcc is found on " 6088"PATH, in /usr/local/cuda* and in /opt/cuda*), then run it again" ) 6089if not have_cc : 6090run (["sudo" ,"apt-get" ,"install" ,"-y" ,"build-essential" ]) 6091if nvcc is None or cuda_v < need_cuda : 6092osr = dict (line .split ("=" ,1 )for line in open ("/etc/os-release" ).read ().splitlines ()if "=" in line ) 6093repo = cuda_apt_repo (osr ) 6094if repo is None : 6095fail ("the CUDA Toolkit can be installed automatically on Ubuntu 22.04 / 24.04 and Debian 12 / 13 only" , 6096"install it from https://developer.nvidia.com/cuda-downloads and run it again" ) 6097deb = Path ("/tmp/cuda-keyring.deb" ) 6098# NVIDIA's arm64 server repository is "sbsa" (a DGX Spark; DGX OS normally has the toolkit already) 6099download (f"https://developer.download.nvidia.com/compute/cuda/repos/ { repo } /" 6100f" { 'sbsa' if is_arm64 () else 'x86_64' } /cuda-keyring_1.1-1_all.deb" ,deb ,"CUDA repository key" ) 6101run (["sudo" ,"dpkg" ,"-i" ,str (deb )]) 6102run (["sudo" ,"apt-get" ,"update" ]) 6103if repo .startswith ("ubuntu" ):# as before: 13.0, and a failed install stops setup here 6104run (["sudo" ,"apt-get" ,"install" ,"-y" ,"cuda-toolkit-13-0" ]) 6105else : 6106# Debian 13's CUDA repo carries no 13.0 package: take the oldest 13.x minor it has 6107for minor in range (10 ): 6108if run (["sudo" ,"apt-get" ,"install" ,"-y" ,f"cuda-toolkit-13- { minor } " ],check = False ).returncode == 0 : 6109break 6110else : 6111fail (f"no cuda-toolkit-13-x package could be installed from NVIDIA's { repo } repository" , 6112"install the CUDA Toolkit 13 from https://developer.nvidia.com/cuda-downloads and run it again" ) 6113nvcc ,cuda_v = find_nvcc (below = (13 ,0 ))if old else find_nvcc () 6114if (WIN and find_vcvars (cuda_v )is None )or (not WIN and shutil .which ("g++" )is None ): 6115fail ("the C++ build tools did not install" ,"install them by hand (README.md) and run it again" ) 6116if nvcc is None or cuda_v < need_cuda : 6117fail ("the CUDA Toolkit did not install" ,"install it from https://developer.nvidia.com/cuda-downloads, then run it again" ) 6118nvcc ,cuda_v = sm120_nvcc (nvcc ,cuda_v ,archs ) 6119ok (f"build tools installed (CUDA { cuda_v [ 0 ] } . { cuda_v [ 1 ] } )" ) 6120return nvcc ,find_vcvars (cuda_v )if WIN else None 6121 6122 6123def tool_usable (name ): 6124"""find_tool found one that runs and (cmake) is new enough: an older system cmake counts as missing, so pip puts the right one in the venv.""" 6125found = find_tool (name ) 6126if found is None : 6127return False 6128if name == "cmake" : 6129runs ,version = _tool_version (found ,name ) 6130return runs and (not version or version [:2 ]>= CMAKE_MIN ) 6131return True 6132 6133 6134def ensure_build_tools (): 6135"""cmake and ninja for a local compile, installed from requirements-build.txt when missing (#3403: the Mac setup 6136compiles without cmake_build(), so it calls this too). Returns (cmake, ninja).""" 6137# The ready-made engine path never calls this function. Keep build helpers out of 6138# the normal serving environment, and use already installed tools offline. 6139build_packages = requirement_lines (BUILD_REQUIREMENTS )if BUILD_REQUIREMENTS .exists ()else BUILD_PACKAGES 6140missing = [package for package in build_packages if not tool_usable (req_name (package ))] 6141if missing : 6142pip_install (missing ,"CMake and Ninja build tools" ) 6143cmake ,ninja = find_tool ("cmake" ),find_tool ("ninja" ) 6144if cmake is None or ninja is None : 6145fail ("cmake / ninja not found after installing them" ,"run: .venv python -m pip install -r requirements-build.txt" ) 6146return cmake ,ninja 6147 6148 6149def configured_generator (bdir :Path )-> str | None : 6150"""The generator a build folder was configured with (CMakeCache.txt), None when it was never configured.""" 6151try : 6152for line in (Path (bdir )/ "CMakeCache.txt" ).read_text (encoding = "utf-8" ,errors = "replace" ).splitlines (): 6153if line .startswith ("CMAKE_GENERATOR:" ): 6154return line .split ("=" ,1 )[1 ].strip () 6155except OSError : 6156pass 6157return None 6158 6159 6160def fresh_if_other_generator (bdir :Path ,generator :str = "Ninja" )-> bool : 6161"""CMake refuses to configure a folder with another generator than the one it was made with ("Does not match the generator used 6162previously"). The manual build in docs/INSTALL.md uses CMake's default, Unix Makefiles on Linux, in the same build/ folder (#4038). 6163Such a folder is configured afresh: its cache is removed (the compiled objects of the other generator are not reused anyway), with one 6164plain line. True when it did.""" 6165had = configured_generator (bdir ) 6166if had is None or had == generator : 6167return False 6168say (f" { Path ( bdir ). name } / was configured with { had } ; setup builds with { generator } , so it is configured again (the other build is not used)" ) 6169 (Path (bdir )/ "CMakeCache.txt" ).unlink (missing_ok = True ) 6170shutil .rmtree (Path (bdir )/ "CMakeFiles" ,ignore_errors = True ) 6171return True 6172 6173 6174def cmake_cache_entries (bdir :Path )-> dict : 6175"""The entries of a build folder's CMakeCache.txt as {name: value} (the type dropped); {} when it was never configured.""" 6176out = {} 6177try : 6178text = (Path (bdir )/ "CMakeCache.txt" ).read_text (encoding = "utf-8" ,errors = "replace" ) 6179except OSError : 6180return out 6181for line in text .splitlines (): 6182if line and not line .startswith (("#" ,"//" ))and "=" in line : 6183key ,value = line .split ("=" ,1 ) 6184out [key .split (":" ,1 )[0 ].strip ()]= value .strip () 6185return out 6186 6187 6188CUDA_CACHE_GLOBS = ("CUDA_*" ,"CUDAToolkit_*" )# FindCUDAToolkit's cached library paths and toolkit folders 6189 6190 6191def toolkit_change_undefs (bdir :Path ,defs )-> list : 6192"""#5717: FindCUDAToolkit keeps the library paths of the toolkit a folder was first configured with (CUDA_cudart_LIBRARY 6193and about 60 more); a new -DCUDAToolkit_ROOT does not search them again, so after a CUDA update that removed the old 6194toolkit, ninja stopped on the old libcudart.so. When the toolkit changed - another CUDAToolkit_ROOT than the cached one, 6195or a cached CUDA path that is gone - the configure drops those entries (-U, before the new -D) and CMake detects the CUDA 6196compiler again; the compiled objects stay, so only what changed is rebuilt. [] for an unchanged or a new folder.""" 6197cache = cmake_cache_entries (bdir ) 6198if not cache : 6199return [] 6200want = next ((str (d ).split ("=" ,1 )[1 ]for d in defs if str (d ).startswith ("-DCUDAToolkit_ROOT=" )),None ) 6201had = cache .get ("CUDAToolkit_ROOT" ) 6202moved = bool (want and had )and Path (had )!= Path (want ) 6203gone = any (not Path (part ).exists () 6204for name ,value in cache .items ()if name .startswith (("CUDA_" ,"CUDAToolkit_" )) 6205for part in value .split (";" ) 6206if part and not part .endswith ("-NOTFOUND" )and Path (part ).is_absolute ()) 6207if not (moved or gone ): 6208return [] 6209for f in (Path (bdir )/ "CMakeFiles" ).glob ("*/CMakeCUDACompiler.cmake" ): 6210f .unlink (missing_ok = True ) 6211return [f"-U { g } " for g in CUDA_CACHE_GLOBS ] 6212 6213 6214def cmake_build (src ,bdir ,target ,defs ,vcvars ,bat_name ): 6215acquisition .require ("a compile (cmake)" ) 6216cmake ,ninja = ensure_build_tools () 6217fresh_if_other_generator (bdir ) 6218conf = [cmake ,"-G" ,"Ninja" ,f"-DCMAKE_MAKE_PROGRAM= { ninja } " ,"-S" ,str (src ),"-B" ,str (bdir ), 6219* toolkit_change_undefs (bdir ,defs ),"-DCMAKE_BUILD_TYPE=Release" ,* defs ] 6220build = [cmake ,"--build" ,str (bdir ),"--target" ,target ,"-j" ,str (max (2 , (os .cpu_count ()or 4 )// 2 ))] 6221# A failed build is tried once more: CUDA 13.0's ptxas now and then fails to parse a PTX file it just wrote, and 6222# the same command then gets past it (issue #45); a second attempt only compiles what is still missing. 6223if WIN : 6224if vcvars is None :# #881: the build needs MSVC's environment 6225fail ("the Visual Studio 2022 C++ build tools were not found (Visual Studio 2019 is too old: the sources are C++20)" , 6226"install Visual Studio 2022 Build Tools (workload 'Desktop development with C++'), then run setup again; a ready-made engine " 6227"needs no compiler: `strata update` fetches it" ) 6228bat = ROOT / bat_name 6229q = lambda c :" " .join (f'" { x } "' if " " in str (x )else str (x )for x in c )# noqa: E731 6230bat .write_text (f'@echo off\r\ncall " { vcvars } " >nul\r\n { q ( conf ) } || exit /b 1\r\n { q ( build ) } && exit /b 0\r\n' 6231f'echo (the build stopped - trying it once more)\r\n { q ( build ) } || exit /b 1\r\n' , 6232encoding = "utf-8" ) 6233run (["cmd" ,"/c" ,str (bat )]) 6234else : 6235run (conf ) 6236if run (build ,check = False ).returncode != 0 : 6237say (" (the build stopped - trying it once more)" ) 6238run (build ) 6239 6240 6241ENGINE_SOURCES = ("CMakeLists.txt" ,"cmake" ,"src" ,"include" ,"third_party/ggml" ,"third_party/strata-ggml" ) 6242VISION_SOURCES = ("tools/vision" ,"third_party/strata-llama" ) 6243 6244 6245def source_hash (parts )-> str : 6246"""A fingerprint of the files a compiled engine is built from, kept in engine/BUILD.json: when a `git pull` 6247changes them, the engine is compiled again (issue #31).""" 6248h = hashlib .sha256 (LLAMA_CPP_COMMIT .encode ()) 6249for part in parts : 6250base = ROOT / part 6251for f in [base ]if base .is_file ()else sorted (x for x in base .rglob ("*" )if x .is_file ()): 6252h .update (f .relative_to (ROOT ).as_posix ().encode ()+ b"\0" + f .read_bytes ().replace (b"\r\n" ,b"\n" )) 6253return h .hexdigest ()[:16 ] 6254 6255 6256def isa_floor_defs (floor :str ,bdir :Path ,meta :dict )-> list : 6257"""The experimental older-CPU build's CMake definition (STRATA_ISA_FLOOR, CMakeLists.txt), none for the normal 6258build. A build folder configured for another floor is configured afresh: ggml's CPU options are cached there.""" 6259if (meta .get ("isa_floor" )or "" )!= floor and (bdir / "CMakeCache.txt" ).exists (): 6260 (bdir / "CMakeCache.txt" ).unlink () 6261return [f"-DSTRATA_ISA_FLOOR= { floor } " ]if floor else [] 6262 6263 6264def host_compiler_defs (cuda :bool )-> list : 6265"""CC / CXX / CUDAHOSTCXX pick the host compilers of a build - as -D definitions, so an existing build folder 6266takes them too (the environment reaches CMake only on a folder's first configure, which is why CXX=g++-14 alone 6267could die at the last step, #1645). CUDAHOSTCXX is nvcc's host compiler (-ccbin); it defaults to CXX, as 6268CMake's does. `cuda`: the project compiles CUDA (the host-compiler definition means nothing to a C++-only 6269one).""" 6270cc = os .environ .get ("CC" ,"" ).strip () 6271cxx = os .environ .get ("CXX" ,"" ).strip () 6272hostcxx = os .environ .get ("CUDAHOSTCXX" ,"" ).strip ()or cxx 6273return ([f"-DCMAKE_C_COMPILER= { cc } " ]if cc else [])+ \ 6274 ([f"-DCMAKE_CXX_COMPILER= { cxx } " ]if cxx else [])+ \ 6275 ([f"-DCMAKE_CUDA_HOST_COMPILER= { hostcxx } " ]if cuda and hostcxx else []) 6276 6277 6278def toolkit_root_defs (nvcc )-> list : 6279"""CUDAToolkit_ROOT for the toolkit whose nvcc builds the engine. Without it CMake can take cudart and cuBLAS from 6280another toolkit: with STRATA_NVCC=/opt/cuda-13.0/bin/nvcc on Ubuntu 24.04 that also has the distribution's CUDA 628112.0 (nvidia-cuda-toolkit), the engine was compiled with the 13.0 headers but linked libcudart.so.12 from 6282/usr/lib/x86_64-linux-gnu. The distribution's own nvcc (/usr/bin) keeps CMake's search as before.""" 6283root = Path (nvcc ).resolve ().parent .parent 6284return []if root == Path ("/usr" )else [f"-DCUDAToolkit_ROOT= { root } " ] 6285 6286 6287def engine_defs (archs ,toolkit = 13 )-> list : 6288"""Extra CMake definitions for the engine: the experimental Pascal/Volta build (#295) for cards below sm_75, and 6289for every CUDA 12 engine (the same build as the ready-made CUDA 12 one: it admits the older cards).""" 6290return ["-DSTRATA_EXPERIMENTAL_SM60=ON" ]if min (int (x )for x in archs )< 75 or int (toolkit )== 12 else [] 6291 6292 6293def prebuilt_vision (meta :dict ,gpu :dict ,vision :str )-> str : 6294"""The image encoder to use with a ready-made engine (`meta`: its BUILD.json). The encoder can cover fewer cards 6295than the engine (0.1.30/0.1.31: no RTX 20 code, #331): such a card gets the CPU encoder - the same program - instead 6296of compiling one, which fails on most Windows PCs (no Visual Studio / CUDA toolkit); --build compiles it.""" 6297if vision != "gpu" : 6298return vision 6299va = arch_numbers (meta .get ("vision_archs" ,meta .get ("archs" ))) 6300if va and int (gpu ["arch" ])not in va and not (meta .get ("ptx" )and int (gpu ["arch" ])> max (va )): 6301warn (f"the ready-made image encoder has no code for your GPU (sm_ { gpu [ 'arch' ] } ): it runs on the CPU instead " 6302"(images take longer; setup --build compiles one for your GPU)" ) 6303return "cpu" 6304return vision 6305 6306 6307def local_build_archs (archs ,found )-> list : 6308"""#4662: the architectures a compiled engine gets code for: the cards this install uses AND every other card Strata can run on in the PC. 6309A PC with a TITAN RTX (sm_75) and an RTX 3080 (sm_86) was updated with archs [75] (the pair was not picked as a split by setup), and the 6310layer-split run on both cards then launched kernels the sm_75 build holds only a trap for: "unspecified launch failure" on every long prompt. 6311One more architecture is a few more minutes of compile, once; a card Strata cannot use (older than sm_75) is left out.""" 6312try : 6313present = {int (g ["arch" ])for g in found or []if gpu_problem (g )is None } 6314except (KeyError ,TypeError ,ValueError ): 6315present = set () 6316return sorted ({int (x )for x in archs }| present ) 6317 6318 6319def build_engine (gpu ,vision ,yes ,llama ,toolkit = None )-> Path : 6320"""Compile the engine (and, for images, the encoder) for this GPU; the results go to engine/. A compiled 6321engine whose source files changed since (a `git pull`) is compiled again: only the changed files, a few minutes. 6322toolkit 12 (default: 12 for a card older than CUDA 13 supports): the experimental CUDA 12 engine, in 6323engine-cuda12/ with its own build folders.""" 6324acquisition .require ("an engine build" ) 6325if toolkit is None : 6326toolkit = 12 if min (int (x )for x in gpu .get ("archs" , [gpu ["arch" ]]))< CUDA13_MIN_ARCH else 13 6327t12 = int (toolkit )== 12 6328eng = engine_dir (toolkit ) 6329eng .mkdir (exist_ok = True ) 6330stamp = eng / "BUILD.json" 6331meta = json .loads (stamp .read_text (encoding = "utf-8" ))if stamp .exists ()else {} 6332want_vision = vision != "none" 6333local = meta .get ("source" )== "local" 6334src ,vsrc = source_hash (ENGINE_SOURCES ),source_hash (VISION_SOURCES ) 6335archs = sorted ({int (x )for x in gpu .get ("archs" , [gpu ["arch" ]])})# every card the model runs on 6336archs = local_build_archs (archs ,gpus ())# #4662: and every other card in the PC 6337built = set (arch_numbers (meta .get ("archs" ))) 6338# a card the engine has no code for (a GPU added with --gpus, #128) needs a compile even when the source is the 6339# same; the compile keeps the generations it was built for 6340new_arch = local and not set (archs )<= built 6341floor = cpu_floor (cpu_info ()[1 ])# "" on an AVX2 CPU: the normal engine 6342engine_ok = local and (eng / EXE ).exists ()and meta .get ("src" )== src and not new_arch and \ 6343 (meta .get ("isa_floor" )or "" )== floor and not stale_binary (eng / EXE ) 6344vision_ok = not want_vision or ((eng / VEXE ).exists ()and (not local or meta .get ("vision_src" )== vsrc )) 6345if engine_ok and vision_ok : 6346ok ("engine already built for this PC" ) 6347return eng 6348if local : 6349archs = sorted (built | set (archs )) 6350nvcc ,vcvars = install_build_tools ({** gpu ,"archs" :archs ,"toolkit" :toolkit },yes ) 6351cuda_archs = ";" .join (str (x )for x in archs ) 6352bdir ,vdir = (ROOT / "build-cuda12" ,ROOT / "build-vision-cuda12" )if t12 else (ROOT / "build" ,ROOT / "build-vision" ) 6353if not engine_ok : 6354say (" Compiling the engine for " + ", " .join (f"sm_ { x } " for x in archs )+ " (a card it had no code for; " 6355"10-20 minutes, once) ..." if new_arch else 6356" The engine's source changed: compiling it again (only what changed, a few minutes) ..." 6357if local and (eng / EXE ).exists ()else " Compiling the Strata engine for your GPU (10-20 minutes, once) ..." ) 6358cmake_build (ROOT ,bdir ,"strata" , 6359 ["-DSTRATA_ENABLE_CUDA=ON" ,"-DSTRATA_BUILD_TESTS=OFF" ,"-DSTRATA_Q6K_EXPERTS=ON" ,"-DSTRATA_MMQ_KQUANTS=ON" , 6360# without llama.cpp's MMQ, also in a build folder configured before (its cache says ON); ARM64 (DGX Spark): 6361# not measured without MMQ, kept as in 0.2.13 6362"-DSTRATA_MMQ=" + ("ON" if is_arm64 ()else "OFF" ), 6363f"-DCMAKE_CUDA_ARCHITECTURES= { cuda_archs } " , 6364f"-DCMAKE_CUDA_COMPILER= { nvcc } " ,* toolkit_root_defs (nvcc ),* ggml_defs (llama ), 6365* host_compiler_defs (True ),* engine_defs (archs ,toolkit ), 6366* isa_floor_defs (floor ,bdir ,meta )], 6367vcvars ,"build-strata-cuda12.bat" if t12 else "build-strata.bat" ) 6368if stale_binary (bdir / EXE ):# #2054: the stamp below is written only for a binary of this source 6369fail (f"the engine build finished without a new engine ( { EXE } is version { binary_engine_version ( bdir / EXE ) } , " 6370f"this source is { source_version () } ): the installed engine and its stamp are left as they were" , 6371"the build folder " + str (bdir )+ " may be configured for something else: delete it and run this again" ) 6372shutil .copy2 (bdir / EXE ,eng / EXE ) 6373if (bdir / KQ_LIB ).exists ():# built with it (Phase 1): it goes next to the engine 6374shutil .copy2 (bdir / KQ_LIB ,eng / KQ_LIB ) 6375elif (eng / KQ_LIB ).exists ():# an older one of another build would only be refused 6376 (eng / KQ_LIB ).unlink () 6377if not vision_ok : 6378say (" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ..." )) 6379defs = [f"-DLLAMA_DIR= { vision_llama ( llama ) } " ,f"-DSTRATA_VISION_CUDA= { 'ON' if vision == 'gpu' else 'OFF' } " , 6380"-DSTRATA_PORTABLE=OFF" ,* host_compiler_defs (vision == "gpu" )]# native, like the engine 6381if vision == "gpu" : 6382defs += [f"-DCMAKE_CUDA_ARCHITECTURES= { cuda_archs } " ,f"-DCMAKE_CUDA_COMPILER= { nvcc } " , 6383* toolkit_root_defs (nvcc )] 6384cmake_build (ROOT / "tools" / "vision" ,vdir ,"strata-vision" ,defs ,vcvars , 6385"build-vision-cuda12.bat" if t12 else "build-vision.bat" ) 6386shutil .copy2 (vdir / "bin" / VEXE ,eng / VEXE ) 6387bindir = Path (nvcc ).parent # the toolkit's own libraries (bin, bin/x64, lib64) 6388dirs = [str (d )for d in (bindir ,bindir / "x64" ,bindir .parent / "lib64" )if d .is_dir ()] 6389stamp .write_text (json .dumps ({"source" :"local" ,"version" :source_version (),"archs" :archs , 6390"vision" :vision ,** ({"toolkit" :12 }if t12 else {}), 6391"cuda_dirs" :dirs ,"src" :src ,"vision_src" :vsrc if want_vision else None , 6392** ({"isa_floor" :floor }if floor else {})},indent = 1 )) 6393ok (f"engine compiled: { eng / EXE } " ) 6394return eng 6395 6396 6397# ------------------------------------------------------------------------------------------------ the data folder 6398# The model files - the GGUFs, the prepared packs and the MTP layer, 70-120 GB - live in a data folder NEXT TO the 6399# Strata folder (`Strata-data`), not inside it: updating Strata by unzipping a new copy used to give a new, empty 6400# folder and a full download again. Where it is, and which Strata folders this user ran, is kept in a small 6401# per-user file, so every Strata folder on the PC finds the same files. 6402DATA_ITEMS = ("models" ,"packs" ,"mtp" ) 6403 6404 6405LOW_RAM_HEADROOM_GB = 10 # RAM beside the experts (GiB, as ram_gb() counts): the OS, the engine's other buffers, the server 6406RESIDENT_ENGINE = (0 ,1 ,30 )# the first engine with --resident-experts (the low-RAM mode's resident variant) 6407RESIDENT_SPLIT_ENGINE = (0 ,1 ,40 )# #642: the first engine that runs it on a layer split 6408 6409 6410def resident_split ()-> bool : 6411"""#642: the engine setup requires runs the low-RAM mode's resident variant on a layer split - each card's cache 6412holds the most-used experts of its own layers, and the RAM copy leaves out what any card holds. Before it, a 6413resident config on several GPUs read those experts through the OS file cache (#364 #384).""" 6414return MIN_ENGINE >= RESIDENT_SPLIT_ENGINE 6415 6416 6417def low_ram_needed (model ,ram )-> bool : 6418"""The model's experts do not fit this PC's RAM with room left for the rest: they are then mapped from the pack's 6419experts.bin instead of copied into RAM (the low-RAM mode).""" 6420return ram_short_of_arena (ram ,MODELS [model ]["arena_gb" ]) 6421 6422 6423def ram_short_of_arena (ram_gib ,arena_gb ,headroom_gib = LOW_RAM_HEADROOM_GB )-> bool : 6424"""True when `ram_gib` (GiB, as ram_gb() returns it) is less than an expert arena of `arena_gb` (GB of 10^9 6425bytes, as MODELS gives it) plus the headroom (GiB): both sides counted in GiB.""" 6426return ram_gib < arena_gb * 1e9 / 2 ** 30 + headroom_gib 6427 6428 6429#: The draft layer (MTP) takes about 1 GB of graphics memory: its 786 MiB of files plus the draft head's ~218 MiB 6430#: (phaseA-tests/notes-021-settings.md). It comes out of the expert cache, so every fit check counts it while MTP is on. 6431MTP_VRAM_GB = 1.0 6432 6433 6434def low_ram_gpu_gb (model ,vram_gb ,ctx = 32768 ,kv = "int8" ,mtp = True )-> float : 6435"""About how many GB of the model's experts the GPU's cache holds: its VRAM minus ~5 GB for the dense weights, 6436buffers and a 32K context's KV cache, minus the KV cache of a longer context (in VRAM in the low-RAM mode: its RAM 6437has no room for KV streaming), minus ~1 GB for the draft layer (MTP) when it is on.""" 6438kv_tok = 13 * KV_CELL_BYTES .get (kv ,1056 )# bytes per context token: 12 QSA layers + the draft layer 6439longer = max (0 ,ctx - 32768 )* kv_tok / 1e9 6440return max (0.0 ,min (MODELS [model ]["arena_gb" ],vram_gb - 5 - (MTP_VRAM_GB if mtp else 0.0 )- longer )) 6441 6442 6443def low_ram_gpu_share (model ,vram_gb ,ctx = 32768 ,kv = "int8" ,mtp = True )-> float : 6444"""About how much of the model's experts the GPU holds.""" 6445return low_ram_gpu_gb (model ,vram_gb ,ctx ,kv ,mtp )/ MODELS [model ]["arena_gb" ] 6446 6447 6448def low_ram_resident (model ,ram ,vram_gb ,ctx = 32768 ,kv = "int8" ,mtp = True )-> bool : 6449"""In the low-RAM mode: the experts the GPU does not hold fit the RAM with the usual room beside them, so they are 6450copied into RAM once (the resident variant, `--resident-experts`) instead of being read through the OS file cache 6451(plain `--mmap-experts`, which a PC this short of RAM keeps re-reading from the SSD).""" 6452rest = MODELS [model ]["arena_gb" ]- low_ram_gpu_gb (model ,vram_gb ,ctx ,kv ,mtp ) 6453return ram >= rest + LOW_RAM_HEADROOM_GB 6454 6455 6456def low_ram_fits (model ,ram ,vram_gb ,mtp = True )-> bool : 6457"""In the low-RAM mode: the experts the GPU does not hold fit the RAM left beside the rest (as file cache).""" 6458arena = MODELS [model ]["arena_gb" ] 6459return ram - 6 + max (0.0 ,vram_gb - 5 - (MTP_VRAM_GB if mtp else 0.0 ))>= arena 6460 6461 6462def model_files_gb (model )-> float : 6463"""The model's files without the n-gram / PLE lookup table's file, in GB: the download minus the table (strata_control/fit_label.py; the catalog's `fit_gb`, 6464the Terminal's "Needs (RAM + VRAM)" column).""" 6465from strata_control import fit_label 6466d = MODELS [model ] 6467return fit_label .files_gb ((d .get ("families" )or (None ,))[0 ],model ,d ) 6468 6469 6470def model_fit_label (model ,ram ,gpu )-> str : 6471""""fits" or "may run slower" (strata_control/fit_label.py, the owner's one rule): the files without the lookup table against the RAM and the card's memory 6472together. An integrated chip counts only its carve-out (`low_ram_vram`: its shared memory is the RAM).""" 6473from strata_control import fit_label 6474return fit_label .label (model_files_gb (model ),ram ,low_ram_vram (gpu )if gpu else 0.0 ) 6475 6476 6477def low_ram_wanted (model ,ram ,choice = "auto" )-> bool : 6478"""Does setup put this model in the low-RAM mode on this PC: its experts do not fit the RAM with the usual room 6479beside them (`low_ram_needed`), or the user asked for it. Unsloth's 4-bit file is not the low-RAM mode at all: 6480it always reads part of its experts from the files, through its RAM budget. Step 5 applies exactly this answer, 6481and the launcher's preset diff asks it too - so a preset that says "auto" is compared with what auto decides, 6482not with the word.""" 6483if MODELS [model ].get ("budget" ): 6484return False 6485return choice in ("on" ,"resident" ,"mmap" )or (choice == "auto" and low_ram_needed (model ,ram )) 6486 6487 6488def kv_streaming_ram_gb (ctx ,kv )-> float : 6489"""The RAM a streamed KV cache takes: ~13.7 KB per context token with 8-bit KV (1.7 GB at 128K), 10.6 KB with 6490K8V4, 7.5 KB with 4-bit - 12 QSA layers + the draft layer.""" 6491return ctx * (13 * KV_CELL_BYTES .get (kv ,1056 ))/ 1e9 6492 6493 6494def kv_streaming_need_gb (model ,ctx ,kv )-> float : 6495"""The RAM a PC needs before setup streams this model's KV cache on its own (`--kv-streaming on` skips the test): 6496the smaller of two numbers. (1) The model's all-in-RAM need (`ram_gb`) + the KV cache + 1 GB: the experts all fit 6497and the cache comes on top. (2) The experts (`arena_gb`) + LOW_RAM_HEADROOM_GB beside them (the line 6498`low_ram_needed` draws) + the KV cache: a small card holds so few experts that the engine's RAM copy is the 6499rest, and the KV's RAM then comes out of that copy (or out of the OS file cache when the arena does not fit), 6500not on top of it. KV-128 (phaseA-tests/gh-sweep-1031/KV-128.md), IQ3_S on a 12 GB card at 128K, 45 GiB of RAM 6501for the engine (Linux mimic): streaming gave 756 -> 1,267 expert slots and a 32K prompt in 12-17 s instead of 650221-34 s, with the RAM the engine used unchanged (RAM budget 31 -> 29 GiB); on the owner's RTX 5070 (R5070's 6503run) 924 -> 1,585 slots, a 32K prompt 130 -> 79 s, the RAM copy 30.8 -> 28.9 GiB, no paging. Rule (1) alone 6504asked 64.8 GB of a PC that reads 63.1 and left the KV in VRAM.""" 6505kv_gb = kv_streaming_ram_gb (ctx ,kv ) 6506m = MODELS [model ] 6507return min (m ["ram_gb" ]+ kv_gb + 1 ,m ["arena_gb" ]+ LOW_RAM_HEADROOM_GB + kv_gb ) 6508 6509 6510def kv_streaming_wanted (model ,ctx ,kv ,ram ,choice = "auto" )-> bool : 6511"""Will setup stream this model's KV cache on this PC: from 64K up, when the RAM holds the cache beside the 6512model's experts (`kv_streaming_need_gb`); `--kv-streaming on|off` overrides the RAM test (the owner's rule), and 6513WSL never streams. Step 7 writes `--kv-resident` on exactly this answer, and the launcher's preset diff asks it 6514too: a config's `--kv-resident` and a preset's "auto" are the same setting when this says yes.""" 6515if is_wsl ()or choice == "off" : 6516return False 6517return ctx >= 65536 and (ram >= kv_streaming_need_gb (model ,ctx ,kv )or choice == "on" ) 6518 6519 6520def low_ram_one_gpu_why (model ,ram ,choice ,sel = None )-> list [str ]: 6521"""#250: why the low-RAM mode recommends one GPU, with the RAM math that turned it on; #364 #384: and how to use 6522all of them (sel: the cards, for the --gpus example).""" 6523arena ,need = MODELS [model ]["arena_gb" ],MODELS [model ]["arena_gb" ]+ LOW_RAM_HEADROOM_GB 6524if choice == "auto" : 6525why = [f"Why: { model } 's experts are { arena :.0f } GB and must fit in RAM with ~ { LOW_RAM_HEADROOM_GB } GB beside " 6526f"them for the OS and the rest: { arena :.0f } + { LOW_RAM_HEADROOM_GB } = { need :.0f } GB, and this PC has " 6527f" { ram :.0f } GB." , 6528"So setup uses the low-RAM mode: the experts come from the model's file (copied into RAM as far as " 6529"it fits), the GPU holds the most-used ones." ] 6530else : 6531why = [f"Why: you chose the low-RAM mode (--low-ram { choice } ); without it { model } needs { arena :.0f } + " 6532f" { LOW_RAM_HEADROOM_GB } = { need :.0f } GB of RAM, this PC has { ram :.0f } GB." ] 6533return why + ["Its resident variant (the experts the GPU does not hold copied into RAM once: steady RAM use) runs " 6534"on one GPU: the engine has no layer split for it yet." , 6535f"To use all the GPUs: --gpus { ',' . join ( str ( i ) for i in sel ) if sel else '0,1' } - the experts the " 6536"GPUs do not hold are then read through the OS file cache: faster in two reports (1.3-1.6x, #364 " 6537f"#384), but RAM can fill up to 0 free during long prompts. Or { need :.0f } GB of RAM or more, or a " 6538"smaller size." ] 6539 6540 6541def low_ram_together (a ,model ,ram ,gpu ,chosen )-> bool : 6542"""#364 #384: the low-RAM mode with several GPUs chosen. One GPU is recommended: the resident variant keeps the 6543experts the GPU does not hold in RAM (steady RAM use) and has no layer split. All the GPUs together read those 6544experts through the OS file cache instead (--mmap-experts) - 1.3-1.6x faster in those reports, but RAM can fill 6545up to 0 free during long prompts. An explicit --gpus (or an earlier install's cards) is kept; otherwise asked, 6546one GPU by default (--yes: one GPU, as before). True: all of them.""" 6547sel = [g ["index" ]for g in chosen ] 6548names = " + " .join (gpu_name (g )for g in chosen ) 6549if a .gpus : 6550warn (f"the low-RAM mode on { names } , as you chose (--gpus): the experts the GPUs do not hold are read through " 6551"the OS file cache (the resident variant has no layer split yet), and RAM can fill up to 0 free during " 6552"long prompts" ) 6553say (f" One GPU keeps them in RAM (steady RAM use, recommended): --gpu { gpu [ 'index' ] } " ) 6554if a .low_ram == "resident" : 6555warn ("--low-ram resident has no layer split yet: the experts are read through the OS file cache instead" ) 6556return True 6557if a .low_ram != "resident" and not a .yes : 6558say () 6559for line in low_ram_one_gpu_why (model ,ram ,a .low_ram ,sel ): 6560say (" " + line ) 6561say (f" 1) { gpu_name ( gpu ) } only: the experts it does not hold kept in RAM where they fit (recommended: " 6562"steady RAM use)" ) 6563say (f" 2) { names } together: the experts the GPUs do not hold read through the OS file cache - faster" ) 6564say (" in two reports (1.3-1.6x, #364 #384), but RAM can fill up to 0 free during long prompts" ) 6565if ask ("Low-RAM mode: which GPUs?" , ["1" ,"2" ],"1" ,a .yes )== "2" : 6566ok (f"the low-RAM mode on { names } : the experts read through the OS file cache, as you chose" ) 6567return True 6568warn ("the low-RAM mode: using " + gpu_name (gpu )+ " only" ) 6569return False 6570warn ("the low-RAM mode: using " + gpu_name (gpu )+ " only (recommended)" ) 6571for line in low_ram_one_gpu_why (model ,ram ,a .low_ram ,sel ): 6572say (" " + line ) 6573return False 6574 6575 6576def unsloth_together (a ,model ,ram ,gpu ,chosen )-> bool : 6577"""#498: UD-Q4_K_XL with several GPUs chosen. Its RAM budget (--resident-budget-gib) has no layer split, so a 6578split runs without it: all its experts loaded into RAM from the GGUFs at start, as with the 2-3-bit models - only 6579where the RAM holds the GGUF files and 24 GB more (unsloth_split_need_gb; 165 GiB, 2x RTX 3090: 31 -> 64-78 6580tok/s). An explicit --gpus is honoured there; otherwise asked, one GPU by default (--yes: one GPU, as before); an 6581explicit --resident-budget-gib keeps one GPU. #642: the engines from RESIDENT_SPLIT_ENGINE keep the budget on a 6582split (the experts no card holds, the hottest by the whole profile), so there the cards go together with it, at 6583any RAM: --gpus, or "2" when asked; one GPU stays the recommendation (--yes alone: one GPU, as before). True: all 6584of them.""" 6585names = " + " .join (gpu_name (g )for g in chosen ) 6586if resident_split (): 6587note = "with its RAM budget (each card caches its own layers' experts, the RAM the hottest of the rest; #642)" 6588if a .gpus : 6589ok (f" { model } on { names } , as you chose (--gpus), { note } " ) 6590return True 6591if not a .yes : 6592say () 6593say (f" { model } runs with a RAM budget of its experts, on one GPU or on { names } together:" ) 6594say (f" 1) { gpu_name ( gpu ) } only (recommended: the tested setup)" ) 6595say (f" 2) { names } together: each card caches the experts of its own layers (#642)" ) 6596if ask (f" { model } : which GPUs?" , ["1" ,"2" ],"1" ,a .yes )== "2" : 6597ok (f" { model } on { names } , { note } " ) 6598return True 6599warn (f" { model } runs on one GPU: using { gpu_name ( gpu ) } only (--gpus " + "," .join (str (g ["index" ])for g in chosen ) 6600+ f" shares it across { names } , with its RAM budget)" ) 6601return False 6602need = unsloth_split_need_gb (model ) 6603if ram < need : 6604note = (f" { model } on several GPUs has no RAM budget and needs ~ { need :.0f } GB of RAM (its GGUF files and " 6605f" { UNSLOTH_RAM_LEFT_GB } GB more), this PC has { ram :.0f } ; the estimate is a worst case (#737: a 128 GB PC " 6606"ran it)" ) 6607if a .gpus and a .resident_budget_gib is None :# #737: asked for by name: a question, not a refusal 6608confirm_risk (note + ", but it may page or stall here" ,True ,a .yes , 6609f" { model } on several GPUs needs ~ { need :.0f } GB of RAM; this PC has { ram :.0f } GB" , 6610f"start it on one GPU: --gpus { gpu [ 'index' ] } " ," Use them together anyway?" ) 6611ok (f" { model } on { names } , as you chose (--gpus), with { ram :.0f } GB of RAM" ) 6612return True 6613warn (f" { note } - using { gpu_name ( gpu ) } only (--gpus " + "," .join (str (g ["index" ])for g in chosen )+ 6614" uses them together anyway)" ) 6615return False 6616if a .resident_budget_gib is not None : 6617warn (f"--resident-budget-gib has no layer split: { model } runs on one GPU with it - using { gpu_name ( gpu ) } only " 6618f"(leave the budget out to use { names } together)" ) 6619return False 6620note = (f"no RAM budget - all of its experts (~ { MODELS [ model ][ 'arena_gb' ]:.0f } GB) are loaded into RAM from the " 6621f"model files at start, and the files pass through the OS file cache (needs ~ { need :.0f } GB of RAM, this " 6622f"PC has { ram :.0f } )" ) 6623if a .gpus : 6624ok (f" { model } on { names } , as you chose (--gpus): { note } " ) 6625return True 6626if not a .yes : 6627say () 6628say (f" { model } can run on one GPU with a RAM budget of its experts, or on { names } together without one:" ) 6629say (f" 1) { gpu_name ( gpu ) } only: the most-used experts kept in RAM, the rest read from the SSD (recommended: " 6630"the tested setup)" ) 6631say (f" 2) { names } together: { note } ;" ) 6632say (" about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s)" ) 6633if ask (f" { model } : which GPUs?" , ["1" ,"2" ],"1" ,a .yes )== "2" : 6634ok (f" { model } on { names } : { note } " ) 6635return True 6636warn (f" { model } runs on one GPU: using { gpu_name ( gpu ) } only (--gpus " + "," .join (str (g ["index" ])for g in chosen )+ 6637f" shares it across { names } without the RAM budget: this PC's RAM holds it)" ) 6638return False 6639 6640 6641def confirm_risk (msg ,explicit ,yes ,stop ,hint = None ,question = " Go on anyway?" ,default = "n" )-> None : 6642"""The owner's rule: setup recommends, it never forces. A choice setup expects to fail or run badly is said 6643plainly (msg), then asked (default n; `default` keeps an older question's own default), or with --yes taken as 6644consent when it was asked for explicitly (a flag such as --model or --gpus): --yes alone keeps the stop 6645(stop, hint). Returns when it goes on; the caller says what it does.""" 6646warn (msg ) 6647if yes and explicit : 6648return 6649if ask (question , ["y" ,"n" ],default ,yes )!= "y" : 6650fail (stop ,hint ) 6651 6652 6653def confirm_paging (model ,ram ,choice ,yes ,explicit_model = False ): 6654"""The model's experts do not fit this PC's RAM and the low-RAM mode is off. #125: a warning and a question, not 6655a stop - the user may accept paging. Asked "no" by default, so an unattended --yes install stops here, unless 6656the low-RAM mode was turned off explicitly (--low-ram off, #250) or the size was (--model): that is the choice 6657already made.""" 6658need_gb ,arena = MODELS [model ]["ram_gb" ],MODELS [model ]["arena_gb" ] 6659off = choice == "off" 6660confirm_risk (f" { model } needs about { need_gb } GB of RAM and this PC has { ram :.0f } GB: its experts alone are " 6661f" { arena :.0f } GB and must stay in RAM, so Windows/Linux will page part of them from disk. Expect it " 6662"to be much slower, and it may not start at all.\n A smaller size (Q2_0 or IQ2_XS) fits; more " 6663"RAM fixes it." ,off or explicit_model ,yes , 6664f" { model } needs about { need_gb } GB of RAM; this PC has { ram :.0f } GB" , 6665"choose Q2_0 or IQ2_XS, or add RAM" + ("" if off else f"; or --model { model } --yes (or --low-ram off " 6666"--yes) to install it anyway" ), 6667" Install it anyway?" ,"y" if off else "n" ) 6668warn (f"installing { model } with { ram :.0f } GB of RAM, as you chose" + (" (--low-ram off)" if off else 6669" (--model)" if explicit_model else "" )) 6670 6671 6672def ctx_ram_need (model ,ctx ,low_ram = False ): 6673"""#406: the RAM (GB) setup estimates for a long context with IQ3_XXS / IQ3_S: their experts + the context's 66748-bit KV cache + 24 GB of room for everything else (the 0.1.29 arithmetic, counted). None where the context does 6675not count against RAM by this rule: the other sizes, and the low-RAM mode (its KV cache stays in VRAM).""" 6676if model not in ("IQ3_XXS" ,"IQ3_S" )or low_ram : 6677return None 6678return MODELS [model ]["arena_gb" ]+ ctx * 13 * 1056 / 1e9 + 24 6679 6680 6681def ram_ctx (model ,ram ,low_ram = False )-> int : 6682"""#406: the longest context the RAM rule recommends: 128K, or longer where the estimate fits this PC's RAM. It 6683is part of the recommended default (the smaller of it and the GPU's rule); a longer choice is kept, with a note. 6684The 200K menu step is never the recommendation (#608).""" 6685# 204800 (#608) is a menu step between 128K and 256K, never the recommendation: where 256K does not fit, 128K stays 6686return max (c for c in CONTEXTS if c <= 131072 or (c != 204800 and (ctx_ram_need (model ,c ,low_ram )or 0 )<= ram )) 6687 6688 6689def app_settings_file ()-> Path | None : 6690"""The desktop app keeps its own settings file (STRATA_SETTINGS_FILE, in the app's data folder) and never reads or writes the 6691one an older command-line Strata uses, so an old install is never adopted or moved.""" 6692raw = os .environ .get ("STRATA_SETTINGS_FILE" ) 6693return Path (raw )if raw else None 6694 6695 6696def settings_path ()-> Path : 6697own = app_settings_file () 6698if own is not None : 6699return own 6700if WIN : 6701return Path (os .environ .get ("APPDATA" )or Path .home ()/ "AppData" / "Roaming" )/ "Strata" / "settings.json" 6702return Path (os .environ .get ("XDG_CONFIG_HOME" )or Path .home ()/ ".config" )/ "strata" / "settings.json" 6703 6704 6705def load_settings ()-> dict : 6706try : 6707return json .loads (settings_path ().read_text (encoding = "utf-8" )) 6708except (OSError ,ValueError ): 6709return {} 6710 6711 6712def save_settings (s :dict )-> None : 6713if s .get ("data_dir" )and s .get ("data_dir" )!= load_settings ().get ("data_dir" ): 6714s = {** s ,"data_dir_at" :time .time ()}# when the models folder was chosen: the app and the Terminal keep the newer choice 6715try : 6716settings_path ().parent .mkdir (parents = True ,exist_ok = True ) 6717settings_path ().write_text (json .dumps (s ,indent = 1 ),encoding = "utf-8" ) 6718except OSError as e : 6719warn (f"could not save { settings_path () } ( { e } )" ) 6720 6721 6722def has_data (folder :Path )-> bool : 6723for d in DATA_ITEMS : 6724try : 6725if (folder / d ).is_dir ()and any ((folder / d ).iterdir ()): 6726return True 6727except OSError : 6728pass 6729return False 6730 6731 6732def other_installs (settings :dict )-> list : 6733"""Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders 6734next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`).""" 6735cands = [Path (p )for p in settings .get ("installs" , [])if not in_trash (p )] 6736for base in dict .fromkeys (()if app_settings_file ()else (home ().parent ,home ().parent .parent )): 6737try : 6738for d in base .iterdir (): 6739if d .is_dir ()and d .name .lower ().startswith ("strata" ): 6740cands .append (d ) 6741cands += [c for c in d .iterdir ()if c .is_dir ()and c .name .lower ().startswith ("strata" )] 6742except OSError : 6743pass 6744found = [] 6745for d in cands : 6746try : 6747d = d .resolve () 6748if d != home ()and d not in found and (d / "setup.py" ).is_file (): 6749found .append (d ) 6750except OSError : 6751pass 6752return found 6753 6754 6755def same_drive (a :Path ,b :Path )-> bool : 6756try : 6757return os .stat (a ).st_dev == os .stat (b ).st_dev 6758except OSError : 6759return False 6760 6761 6762def move_into (src :Path ,dst :Path )-> None : 6763"""A rename into the data folder (same drive: instant); a folder merges into one already there, keeping what the 6764destination has. Whatever cannot be moved (a file in use) stays where it is.""" 6765if not dst .exists (): 6766try : 6767dst .parent .mkdir (parents = True ,exist_ok = True ) 6768atomic .replace (src ,dst ) 6769return 6770except OSError : 6771if not src .is_dir (): 6772return 6773dst .mkdir (parents = True ,exist_ok = True ) 6774if src .is_dir ()and dst .is_dir (): 6775for c in list (src .iterdir ()): 6776move_into (c ,dst / c .name ) 6777try : 6778src .rmdir () 6779except OSError : 6780pass 6781 6782 6783def repoint_config (cfg_file :Path ,old :Path ,new :Path )-> None : 6784"""A config whose model files moved from `old` to `new` points at them there (each path only if its file is 6785now there and no longer at the old place).""" 6786try : 6787cfg = json .loads (cfg_file .read_text (encoding = "utf-8-sig" )) 6788except (OSError ,ValueError ): 6789return 6790 6791def fix (v ): 6792if isinstance (v ,list ): 6793return [fix (x )for x in v ] 6794if isinstance (v ,dict ): 6795return {k :fix (x )for k ,x in v .items ()} 6796if isinstance (v ,str ): 6797for d in DATA_ITEMS : 6798o = str (old / d ) 6799nv ,no = os .path .normcase (v ),os .path .normcase (o )# Windows: C:\ and c:\ are the same place 6800if nv == no or nv .startswith (no + os .sep ): 6801n = str (new / d )+ v [len (o ):] 6802if Path (n ).exists ()and not Path (v ).exists (): 6803return n 6804return v 6805 6806new_cfg = fix (cfg ) 6807if new_cfg != cfg : 6808write_config (cfg_file ,new_cfg ) 6809 6810 6811def library_size_gb (folder :Path )-> float : 6812"""The GB of model files (models, packs, mtp) in a data folder.""" 6813total = 0 6814for d in DATA_ITEMS : 6815for root ,_dirs ,files in os .walk (folder / d ): 6816for f in files : 6817try : 6818total += os .path .getsize (os .path .join (root ,f )) 6819except OSError : 6820pass 6821return total / 1e9 6822 6823 6824def same_folder (a :Path ,b :Path )-> bool : 6825"""The same folder, however it is spelled (a different case, a short 8.3 name, a link).""" 6826try : 6827return os .path .samefile (a ,b ) 6828except OSError : 6829return os .path .normcase (os .path .abspath (a ))== os .path .normcase (os .path .abspath (b )) 6830 6831 6832def data_folder (requested :str | None ,move :bool = False ,yes :bool = True ,set_default :bool = False )-> tuple : 6833"""(the data folder, folders that still hold model files and are used where they are). 6834 6835A --data-dir that names a NEW folder never moves anything by itself. When model files already exist elsewhere, 6836the person is asked: keep them where they are and use the new folder for new downloads (the answer with --yes 6837or when nobody can answer), or move them in (`move`, --move-data, or the answer "move"). Only a move, or 6838--set-default-data-dir, or a PC with no model files anywhere, changes the remembered data folder. Without 6839--data-dir the model files of this folder and of earlier Strata folders on the same drive are gathered into the 6840remembered data folder and their configs point there (that is the data folder's own job).""" 6841settings = load_settings () 6842remembered = Path (settings ["data_dir" ])if settings .get ("data_dir" )else home ().parent / "Strata-data" 6843dest = Path (requested ).expanduser ().resolve ()if requested else remembered 6844from strata_control import folders 6845bad = folders .problem (dest ) 6846if bad and requested : 6847fail (folders .without_nothing_changed (bad )[:400 ],"Nothing was downloaded or changed, and the folder was not saved as your data folder." ) 6848if bad and settings .get ("data_dir" ):# an unusable folder saved earlier: go back to the default and say so; never keep it 6849warn (f"The data folder saved before cannot be used ( { bad [ 0 ] } ) Using { home (). parent / 'Strata-data' } instead." ) 6850remembered = dest = home ().parent / "Strata-data" 6851settings = {k :v for k ,v in settings .items ()if k != "data_dir" } 6852try : 6853dest .mkdir (parents = True ,exist_ok = True ) 6854except OSError as e :# e.g. no write access next to the Strata folder 6855warn (f"cannot use { dest } for the model files ( { e } ): keeping them in { home () } " ) 6856dest = home () 6857elsewhere = [] 6858# #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data 6859# folder nested in any of them (an install that kept its models one level down) 6860sources = [home (),* other_installs (settings )] 6861if settings .get ("data_dir" )and not same_folder (Path (settings ["data_dir" ]),dest ): 6862sources .append (Path (settings ["data_dir" ])) 6863sources += [f / "Strata-data" for f in list (sources )if not same_folder (f / "Strata-data" ,dest )] 6864if requested and not same_folder (dest ,remembered ): 6865sources .append (remembered ) 6866# a different folder than the one in use: nothing is moved unless the person says so 6867held = [] 6868for folder in dict .fromkeys (sources ): 6869if not same_folder (folder ,dest )and has_data (folder )and not any (same_folder (folder ,h )for h in held ): 6870held .append (folder ) 6871movable = [f for f in held if same_drive (f ,dest )] 6872if movable and not move and not yes : 6873gb = sum (library_size_gb (f )for f in movable ) 6874say () 6875size = f" { gb :.0f } GB" if gb >= 10 else f" { gb :.1f } GB" 6876say (f" Your models are in { ', ' . join ( str ( f ) for f in movable ) } ( { size } )." ) 6877say (f" keep) leave them there and use { dest } only for new downloads" ) 6878say (f" move) move your { size } of models to { dest } " ) 6879move = ask (f"Move your { size } of models to the new folder, or use the new folder only for new downloads?" , 6880 ["keep" ,"move" ],"keep" ,False )== "move" 6881if held and not move : 6882for folder in held : 6883say (f" Models you already have in { folder } stay there; new downloads go to { dest } ." ) 6884if set_default : 6885save_settings ({** settings ,"data_dir" :str (dest )}) 6886return dest ,held 6887if not held : 6888move = True # nothing to lose track of: the new folder becomes the default 6889seen = set () 6890for folder in sources : 6891key = os .path .normcase (str (folder )) 6892if key in seen : 6893continue 6894seen .add (key ) 6895if same_folder (folder ,dest )or not has_data (folder ): 6896continue 6897if not same_drive (folder ,dest ): 6898elsewhere .append (folder )# another drive: used where it is (no 70 GB copy) 6899continue 6900# the downloads merge file by file (the same file wherever it came from); a prepared pack or MTP layer moves 6901# whole or not at all, so two copies are never mixed 6902if (folder / "models" ).is_dir (): 6903move_into (folder / "models" ,dest / "models" ) 6904for item in [* ((folder / "packs" ).glob ("*" )if (folder / "packs" ).is_dir ()else []),folder / "mtp" ]: 6905rel = item .relative_to (folder ) 6906if item .exists ()and not (dest / rel ).exists (): 6907move_into (item ,dest / rel ) 6908for d in ("packs" ,): 6909try : 6910 (folder / d ).rmdir ()# empty now 6911except OSError : 6912pass 6913for c in model_config_files (folder ): 6914repoint_config (c ,folder ,dest ) 6915if has_data (folder ): 6916elsewhere .append (folder )# in use, or a copy the data folder already has 6917warn (f"some model files are still in { folder } (in use, or already in { dest } )" ) 6918else : 6919ok (f"model files from { folder } moved to { dest } (a new copy of Strata finds them there)" ) 6920installs = [str (home ())]+ [p for p in settings .get ("installs" , []) 6921if p != str (home ())and Path (p ).is_dir ()and not in_trash (p )] 6922save_settings ({** settings ,"data_dir" :str (dest ),"installs" :installs [:20 ]}) 6923return dest ,elsewhere 6924 6925 6926def data_folder_for (a )-> tuple : 6927"""data_folder() with the answers on the command line (--data-dir, --move-data, --yes, --set-default-data-dir).""" 6928return data_folder (getattr (a ,"data_dir" ,None ),getattr (a ,"move_data" ,False ),bool (getattr (a ,"yes" ,True )), 6929getattr (a ,"set_default_data_dir" ,False )) 6930 6931 6932def data_folder_in_place ()-> tuple : 6933"""(the data folder, []) for a start: where settings.json says the model files are, or the default place. Reads 6934the settings and nothing else: no folder is created, nothing is moved or copied, no setting is saved. The run 6935configs name their model files, so an install made by an earlier Strata starts from where it is.""" 6936settings = load_settings () 6937dest = Path (settings ["data_dir" ])if settings .get ("data_dir" )else home ().parent / "Strata-data" 6938from strata_control import folders 6939if settings .get ("data_dir" )and folders .problem (dest ):# a folder saved earlier that cannot be used: the default, and it is not kept 6940dest = home ().parent / "Strata-data" 6941return dest , [] 6942 6943 6944def write_config (path :Path ,cfg :dict ): 6945"""A run config, written whole or not at all (#459): to a temporary file first, then moved over the old one, so 6946a setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind.""" 6947tmp = path .with_name (path .name + ".tmp" ) 6948tmp .write_text (json .dumps (cfg ,indent = 1 ),encoding = "utf-8" ) 6949atomic .replace (tmp ,path ) 6950 6951 6952# #629: the run config's keys setup writes itself (and rewrites on every setup run); any other key is the user's - a 6953# "sampling" or "mcp_servers" block, "allowed_hosts", "cors_origins", "open_browser" - and is kept when setup runs again 6954# "args_written" (strata_control/user_args.py) is setup's own; "user_args" is not in SETUP_KEYS on purpose: carry_over keeps it, 6955# then applies the person's options over the generated ones 6956SETUP_KEYS = frozenset ({"exe" ,"args" ,"cwd" ,"tokenizer" ,"model_name" ,"log" ,"lib_dirs" ,"port" ,"backend" ,"env" , 6957"gpu" ,"gpus_asked" ,"gpus_by" ,"layer_split" ,"host" ,"api_key" ,"draft_vocab" ,"vision" ,"args_written" }) 6958SETUP_ENV = frozenset ({"STRATA_HIPBLASLT_TUNING" ,"STRATA_ROCBLAS_TUNING" ,"STRATA_RESIDENT_PIN" ,"STRATA_NO_ARENA_THP" ,"STRATA_MMQ_KQ" ,"STRATA_HC_Q8" , 6959"STRATA_ROUTE_TAIL_SKIP" })| frozenset (GFX1103_SWITCHES )| frozenset (GFX1150_SWITCHES )# the "env" entries setup writes (the gfx1103 switches are setup's too: a re-run refreshes them, they do not linger) 6960# 0.1.44 added these three, written for Unsloth's files only (unsloth_default_env). In any other model's config they are the 6961# user's own (STRATA_ROUTE_TAIL_SKIP=0 to turn the tail skip off, STRATA_MMQ_KQ=1 ...): a setup run again keeps them there 6962# (0.1.44 dropped them with the rest of SETUP_ENV). 6963SETUP_ENV_UNSLOTH = frozenset ({"STRATA_MMQ_KQ" ,"STRATA_HC_Q8" ,"STRATA_ROUTE_TAIL_SKIP" }) 6964SETUP_VISION = frozenset ({"exe" ,"cpu_exe" ,"mmproj" ,"model" ,"gpu" ,"max_tokens" ,"threads" }) 6965 6966 6967def carry_over (old :dict ,cfg :dict ,explicit :list [str ]| None = None )-> list [str ]: 6968"""#629: setup run again for an installed model keeps what the user added to its run config: every key setup does 6969not write (`SETUP_KEYS`), the "env" entries setup does not write, and in "vision" the keys setup does not write 6970plus an mmproj of their own (a Q8_0 one, #625) that still exists. `cfg` (the new config) is updated in place; 6971the names of what was kept are returned. Engine options added by hand to "args" are not merged (setup chooses 6972those): `args_dropped` names them. `explicit`: engine options given on this run's command line (they win and are 6973kept from now on, see carry_user_args).""" 6974kept = [] 6975for k ,v in old .items (): 6976if k not in SETUP_KEYS and k not in cfg : 6977cfg [k ]= v 6978kept .append (k ) 6979mine = SETUP_ENV if "-unsloth-" in str (cfg .get ("model_name" )or "" )else SETUP_ENV - SETUP_ENV_UNSLOTH 6980env = {k :v for k ,v in (old .get ("env" )or {}).items ()if k not in mine and k not in (cfg .get ("env" )or {})} \ 6981if isinstance (old .get ("env" ),dict )else {} 6982if env : 6983cfg ["env" ]= {** (cfg .get ("env" )or {}),** env } 6984kept += [f"env { k } " for k in env ] 6985ov ,nv = old .get ("vision" ),cfg .get ("vision" ) 6986if isinstance (ov ,dict )and isinstance (nv ,dict ): 6987for k ,v in ov .items (): 6988if k not in SETUP_VISION and k not in nv : 6989nv [k ]= v 6990kept .append (f"vision { k } " ) 6991mm = ov .get ("mmproj" )# a file of the user's own: not the one setup downloads 6992if isinstance (mm ,str )and Path (mm ).name != Path (str (nv .get ("mmproj" ))).name and Path (mm ).is_file (): 6993nv ["mmproj" ]= mm 6994kept .append ("vision mmproj" ) 6995kept += carry_profile_args (old ,cfg ) 6996kept += carry_user_args (old ,cfg ,explicit ) 6997off = draft_layer .apply (cfg )# "mtp": false was the user's (a key setup does not write): the new args honour it 6998if off : 6999kept .append ("mtp off (" + " " .join (off )+ " left out of args)" ) 7000return kept 7001 7002 7003# the options setup chooses itself on every run from its answers (context, KV type, pictures, the draft layer, the layer split): 7004# a hand edit of one of these is carried by the answers (choices_from_config) or by its own key ("mtp", "vision"), not by user_args 7005SETUP_CHOICE_FLAGS = frozenset ({"--max-context" ,"--kv" ,"--vision" ,"--mtp" ,"--spec-min-p" ,"--batch-mtp" ,"--layer-split" }) 7006 7007 7008def setup_flags ()-> frozenset : 7009"""Every engine option this file names (setup.py's own source): the options setup can write. Used for a run config 7010that has no `args_written` (written by an earlier Strata): an option in its args that is not in this set was added by hand.""" 7011global _SETUP_FLAGS 7012if _SETUP_FLAGS is None : 7013try : 7014text = Path (__file__ ).read_text (encoding = "utf-8" ) 7015_SETUP_FLAGS = frozenset (re .findall (r'"(--[a-z][a-z0-9-]+)"' ,text )) 7016except OSError : 7017_SETUP_FLAGS = frozenset () 7018return _SETUP_FLAGS 7019 7020 7021_SETUP_FLAGS = None 7022 7023 7024def explicit_args (a )-> list [str ]: 7025"""The engine options this run's command line sets that the person keeps from now on (user_args): --vram-reserve-mib.""" 7026n = getattr (a ,"vram_reserve_mib" ,None ) 7027return ["--vram-reserve-mib" ,str (n )]if n is not None else [] 7028 7029 7030def carry_user_args (old :dict ,cfg :dict ,explicit :list [str ]| None = None )-> list [str ]: 7031"""#3216 #3215 #3270: the engine options the person set by hand in the earlier run config are put back over the 7032generated ones, and recorded in the new one's "user_args" (strata_control/user_args.py). They are the earlier 7033"user_args", the options of "args" that differ from "args_written" (hand edits), for a config with no "args_written" 7034the options its args had and the new ones do not (control vectors, --spec, ...) and an explicit --vram-reserve-mib of 7035the earlier file. `explicit`: options given on this run's command line, which win. The names kept are returned.""" 7036nargs = cfg .get ("args" ) 7037if not isinstance (nargs ,list ): 7038return [] 7039mine = user_args .capture (old ,SETUP_CHOICE_FLAGS ) 7040oargs = old .get ("args" ) 7041if user_args .WRITTEN_KEY not in old and isinstance (oargs ,list ): 7042have = {user_args .flag_of (g )for g in user_args .groups (mine )} 7043mine += user_args .flat ([g for g in user_args .groups (user_args .dropped_by_setup (oargs ,nargs ,setup_flags (),SETUP_CHOICE_FLAGS )) 7044if user_args .flag_of (g )not in have ]) 7045reserve = flag_value (oargs ,"--vram-reserve-mib" )# an old file: the reserve it names, unless it is the vision default or the app's own 7046vis = isinstance (old .get ("vision" ),dict ) 7047if reserve is not None and reserve .isdigit ()and not (vis and int (reserve )== VISION ["gpu" ]["reserve_mib" ])and "ui_resource_baseline" not in old and "--vram-reserve-mib" not in mine : 7048mine += ["--vram-reserve-mib" ,reserve ] 7049for g in user_args .groups (explicit or []): 7050mine = user_args .merge (mine ,g ) 7051if not mine : 7052user_args .stamp (cfg , []) 7053return [] 7054cfg ["args" ]= user_args .merge (nargs ,mine ) 7055user_args .stamp (cfg ,mine ) 7056return ["args " + f for f in dict .fromkeys (g [0 ]for g in user_args .groups (mine )if g [0 ].startswith ("--" ))] 7057 7058 7059def flag_value (args :list ,flag :str ): 7060"""The value after `flag` in an argument list, or None.""" 7061for i ,a in enumerate (args [:- 1 ]): 7062if a == flag : 7063return str (args [i + 1 ]) 7064return None 7065 7066 7067def carry_profile_args (old :dict ,cfg :dict )-> list [str ]: 7068"""#775: a learned expert profile the user wired in by hand (--expert-profile <their file>, --expert-profile-save 7069<file>) survives a setup run: setup writes the shipped profile, which a measured one of their own beats (2.5-3.1x at 7070256K on a 16 GB card in the report). Their --expert-profile replaces the shipped one only when it is another file 7071that still exists; --expert-profile-save is kept when the new config has none. The names kept are returned.""" 7072oargs ,nargs = old .get ("args" ),cfg .get ("args" ) 7073if not isinstance (oargs ,list )or not isinstance (nargs ,list ): 7074return [] 7075kept = [] 7076mine ,shipped = flag_value (oargs ,"--expert-profile" ),flag_value (nargs ,"--expert-profile" ) 7077if mine and shipped and Path (mine ).name != Path (shipped ).name and Path (mine ).is_file (): 7078nargs [nargs .index ("--expert-profile" )+ 1 ]= mine 7079kept .append ("args --expert-profile" ) 7080save = flag_value (oargs ,"--expert-profile-save" ) 7081if save and flag_value (nargs ,"--expert-profile-save" )is None : 7082nargs += ["--expert-profile-save" ,save ] 7083kept .append ("args --expert-profile-save" ) 7084return kept 7085 7086 7087def args_dropped (old :dict ,cfg :dict )-> list [str ]: 7088"""#629: the engine options of the earlier run config that the new one has no more (by flag name): options added 7089by hand, which a setup run does not carry over - the start of the line that names them.""" 7090def flags (c ): 7091a = c .get ("args" )if isinstance (c .get ("args" ),list )else [] 7092return [str (x )for x in a if str (x ).startswith ("--" )] 7093new = set (flags (cfg )) 7094return list (dict .fromkeys (f for f in flags (old )if f not in new )) 7095 7096 7097SHAPE_ENGINE :dict = {}# the model-shape engine the chosen model runs on: {"shape": "q4_lite"} (strata_control/shape_engine.py); empty: the Strata engine 7098 7099 7100def engine_exe (eng :Path )-> str : 7101"""The `exe` of a run config: the engine component in the app, else the engine binary's path. A model of its own shape names that shape's engine.""" 7102if SHAPE_ENGINE .get ("shape" ): 7103from strata_control import shape_engine 7104return shape_engine .reference (SHAPE_ENGINE ["shape" ]) 7105return "component:strata-engine" if CONTROL else str (eng / EXE ) 7106 7107 7108def write_setup_config (cfg_path :Path ,cfg :dict ,source :Path | None = None ,explicit :list [str ]| None = None ,after_carry = None )-> None : 7109"""#629: setup's run config, written over an earlier one for the same model without losing what the user added 7110to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as 7111strata-<model>.json.bak when it changes. `source`: an earlier install's config to carry the keys over from when 7112this folder has none yet (a copy set up like the last one). A line says what was kept, one what was not.""" 7113if SHAPE_ENGINE .get ("title" )and SHAPE_ENGINE .get ("shape" )and cfg .get ("exe" )== engine_component .REFERENCE_PREFIX + "strata-" + SHAPE_ENGINE ["shape" ].replace ("_" ,"-" ): 7114cfg ["shape_title" ]= SHAPE_ENGINE ["title" ]# the engine's refusal at a start names the model, not the geometry (strata_control/shape_engine.py) 7115old_path = cfg_path if cfg_path .is_file ()else source 7116old = None 7117if old_path is not None and old_path .is_file (): 7118try : 7119old = json .loads (old_path .read_text (encoding = "utf-8-sig" )) 7120except (OSError ,ValueError ): 7121pass 7122if not isinstance (old ,dict ): 7123old = None 7124kept = carry_over (old ,cfg ,explicit )if old is not None else [] 7125if old is None : 7126carry_user_args ({},cfg ,explicit )# a first install: only what this run's command line sets (nothing to report as kept) 7127if after_carry is not None :# a check of the finished argument list (the person's own options are in it now) 7128after_carry (cfg ) 7129user_args .stamp (cfg )# args_written: what setup wrote, for the next hand-edit check 7130if "images" in cfg and cfg ["images" ]is None :# --images no (or not downloaded): no image section 7131cfg .pop ("images" ) 7132bak = None 7133if cfg_path .is_file ()and old != cfg : 7134bak = cfg_path .with_name (cfg_path .name + ".bak" ) 7135try : 7136shutil .copyfile (cfg_path ,bak ) 7137except OSError as e : 7138warn (f"could not keep a copy of the earlier { cfg_path . name } ( { e . strerror or e } )" ) 7139bak = None 7140write_config (cfg_path ,cfg ) 7141if kept : 7142ok (f"kept from your earlier { old_path . name } : " + ", " .join (kept )) 7143if bak is not None : 7144dropped = args_dropped (old ,cfg )if old is not None else [] 7145say (f" the earlier run config is kept as { bak . name } " + ( 7146f"; engine options it had that this one has not (setup chooses those): { ' ' . join ( dropped ) } " 7147if dropped else "" )) 7148 7149 7150def readable_config (path :Path )-> bool : 7151"""#459: a config that parses as a JSON object; any other gets a one-line warning naming it.""" 7152text = None 7153try : 7154text = path .read_text (encoding = "utf-8-sig" ) 7155if isinstance (json .loads (text ),dict ): 7156return True 7157why = "not a JSON object" 7158except OSError as e : 7159why = e .strerror or str (e ) 7160except ValueError :# JSONDecodeError, or bytes that are not UTF-8 7161why = "the file is empty" if text is not None and not text .strip ()else "not valid JSON" 7162warn (f"skipped the earlier config { path } ( { why } ): setting this copy up without it" ) 7163return False 7164 7165 7166def model_config_files (folder :Path )-> list : 7167"""#346: the strata-*.json files of a folder that can be model configs. The server keeps a config's Chat settings 7168next to it as strata-<model>.shared-settings.json: it matches the pattern but is no config (no exe, no args).""" 7169return [p for p in folder .glob ("strata-*.json" )if not p .name .endswith (".shared-settings.json" )] 7170 7171 7172def previous_config (elsewhere_first :list ,settings :dict ): 7173"""The most recently used model config of another Strata folder on this PC, for a folder that has none yet. One 7174that does not parse (an empty or cut-off file, #459) is skipped with a warning: the newest readable one is used, 7175and with none this copy is set up as a fresh install.""" 7176cands = [] 7177for folder in [* elsewhere_first ,* other_installs (settings )]: 7178cands += model_config_files (folder ) 7179from strata_control import retired 7180cands = [c for c in dict .fromkeys (cands )if c .is_file ()and not retired .config_file_reason (c )]# never set up like a DeepSeek model 7181return next ((c for c in sorted (cands ,key = lambda p :p .stat ().st_mtime ,reverse = True )if readable_config (c )),None ) 7182 7183 7184def own_path_config (cfg :dict )-> bool : 7185"""A config for a family with its own engine path (Qwen3.6): its --mtp is a draft count, not a draft layer.""" 7186return cfg .get ("arch" )in {d ["arch" ]for d in OWN_PATH_FAMILIES .values ()} 7187 7188 7189def choices_from_config (cfg_path :Path )-> dict : 7190"""The setup answers a config was written with (family, size, context, KV, images, projection, network).""" 7191cfg = json .loads (cfg_path .read_text (encoding = "utf-8-sig" )) 7192tag = cfg_path .stem [len ("strata-" ):] 7193own = next ((f for f ,d in OWN_PATH_FAMILIES .items ()if tag .startswith (d ["tag" ])),None ) 7194if own is not None :# Qwen3.6: its own sizes; no KV / images / projection settings 7195d = OWN_PATH_FAMILIES [own ] 7196size = next ((m for m in d ["models" ]if m .lower ()== tag [len (d ["tag" ]):].lower ()),None ) 7197a = cfg .get ("args" , []) 7198ctx = a [a .index ("--max-context" )+ 1 ]if "--max-context" in a and a .index ("--max-context" )+ 1 < len (a )else None 7199vis = cfg .get ("vision" ) 7200return {"family" :own ,"model" :size ,"context" :int (ctx )if ctx and ctx .isdigit ()else None ,"kv" :None , 7201"vision" : ("gpu" if vis .get ("gpu" )else "cpu" )if isinstance (vis ,dict )else "none" ,"esp" :"off" ,"host" :cfg .get ("host" ),"api_key" :cfg .get ("api_key" ), 7202"port" :cfg .get ("port" ),"gpu" :cfg .get ("gpu" ),"layer_split" :None , 7203"cuda" :12 if config_toolkit (cfg )== 12 else None ,"vram_reserve_mib" :None } 7204family = next ((f for f ,d in FAMILIES .items ()if d ["tag" ]and tag .startswith (d ["tag" ])),"qwen" ) 7205model = (tag [len (FAMILIES [family ]["tag" ]):]if tag .startswith (FAMILIES [family ]["tag" ])else tag ).upper () 7206model = next ((m for m in MODELS if m .upper ()== model ),model )# (the catalog's spelling: UD-IQ4_XS-v31 has a lower-case v) 7207if model not in MODELS :# (sizes have no dash except UD-Q4_K_XL: the old rule) 7208model = tag .split ("-" )[- 1 ].upper () 7209a = cfg .get ("args" , []) 7210val = lambda k :a [a .index (k )+ 1 ]if k in a and a .index (k )+ 1 < len (a )else None # noqa: E731 7211vis = cfg .get ("vision" ) 7212esp = val ("--control-vector-scaled" ) 7213esp_path = esp .rsplit (":" ,1 )[0 ]if esp else None 7214return {"family" :family ,"model" :model if model in MODELS else None , 7215"context" :int (val ("--max-context" ))if val ("--max-context" )else None , 7216"kv" :val ("--kv" )if val ("--kv" )in ("int8" ,"q4_0" )else None , 7217"vision" : ("gpu" if vis .get ("gpu" )else "cpu" )if isinstance (vis ,dict )else "none" , 7218"esp" : ("on" if Path (esp_path ).name == ESP_VECTOR .name else esp_path )if esp_path else "off" , 7219"host" :cfg .get ("host" ),"api_key" :cfg .get ("api_key" ),"port" :cfg .get ("port" ),"gpu" :cfg .get ("gpu" ), 7220"layer_split" :cfg .get ("layer_split" ),"cuda" :12 if config_toolkit (cfg )== 12 else None , 7221# #493: --vram-reserve-mib given at setup (images write the default 700 themselves) 7222"vram_reserve_mib" :int (val ("--vram-reserve-mib" ))if (val ("--vram-reserve-mib" )or "" ).isdigit ()and ( 7223vis is None or int (val ("--vram-reserve-mib" ))!= VISION ["gpu" ]["reserve_mib" ])else None } 7224 7225 7226def calibration_targets (have :list ,model :str | None ,family :str | None )-> list : 7227"""#2036: the installed configs `--calibrate --model X` (and/or --family) means; every config with neither.""" 7228if not (model or family ): 7229return [c for c in have if choices_from_config (c )["family" ]not in OWN_PATH_FAMILIES ] 7230out = [] 7231for c in have : 7232ch = choices_from_config (c ) 7233if ch ["family" ]in OWN_PATH_FAMILIES :# the tuning measures Flash-Next's engine settings 7234continue 7235if (not model or ch ["model" ]== model )and (not family or ch ["family" ]== family ): 7236out .append (c ) 7237return out 7238 7239 7240def find_in (roots :list ,rel :str ): 7241"""The first of roots/rel that exists.""" 7242for r in roots : 7243if (r / rel ).exists (): 7244return r / rel 7245return None 7246 7247 7248def mmproj_beside (gguf_dir ,name :str ,size :int | None = None ): 7249"""The picture file a person's own GGUF folder (--gguf-dir, "Use a local GGUF") already has: in the folder itself, or in the folder above it and that 7250folder's models/ (a Strata data folder's layout: models/<size>/ shards, models/<picture file>; pictures.places() looks there too). The two outer places are 7251taken only at the pinned size (`size`), so a half-copied file is fetched again and not used. None when there is none.""" 7252if not gguf_dir : 7253return None 7254base = Path (gguf_dir ) 7255own = base / name 7256if own .is_file (): 7257return own 7258for r in (base .parent ,base .parent / "models" ): 7259f = r / name 7260try : 7261if f .is_file ()and (size is None or f .stat ().st_size == size ): 7262return f 7263except OSError : 7264continue 7265return None 7266 7267 7268# A picture reader the person may already have instead of the pinned one: Unsloth's mmproj-F16.gguf for Flash-Next (the same vision tower in F16; 7269# lane 14: 58 of 72 answers word for word with the pinned BF16 file on the same card, none of the differences wrong about the picture; embeddings 0.9998 7270# mean / 0.998 worst). Accepted ONLY when it is already there, with this size and this SHA-256 (Unsloth rev 38bb39ee97821de2c9009abb7e93950eec396e66), 7271# and only when no pinned file is found: pinned name -> (file name, bytes, sha256). It is never downloaded. 7272ALT_READERS = {MMPROJ : ("mmproj-F16.gguf" ,904004000 ,"1f7b7f0b984cf065c604360c29c8098362ed61b290db0ff12c6f360bb1a8a980" )} 7273_ALT_MARK = re .compile (r"alt-reader sha256 ([0-9a-f]{64})" ) 7274 7275 7276def alt_reader_places (pinned :str ,models_dir ,roots ,gguf_dir )-> list : 7277"""Where the alternative reader of `pinned` is looked for: the same places as the pinned one (the data folder's models/, an earlier install's 7278models/, and a person's own GGUF folder: beside the shards, the folder above and that folder's models/).""" 7279alt = ALT_READERS .get (pinned ) 7280if alt is None : 7281return [] 7282places = [Path (models_dir )/ alt [0 ]]+ [Path (r )/ "models" / alt [0 ]for r in roots or []] 7283if gguf_dir : 7284base = Path (gguf_dir ) 7285places += [base / alt [0 ],base .parent / alt [0 ],base .parent / "models" / alt [0 ]] 7286return places 7287 7288 7289def accepted_alt_reader (pinned :str ,places ,* ,start :bool = True ): 7290"""The first file in `places` that is the alternative reader of `pinned` (name, size and SHA-256 all as pinned in ALT_READERS), else None. Anything 7291else with that name is ignored (never deleted, never renamed). The SHA-256 (0.9 GB, a few seconds) is remembered in a mark in Strata's own 7292marks/ folder, never beside the person's file; the mark is keyed by the real path, size, modification time and change time 7293(_alt_reader_mark), so a file that was replaced, also in place with its size and modification time kept, is hashed again. start=True is 7294the setup run (says what it does, writes the mark); start=False is the plan (the same answer, says nothing, writes nothing).""" 7295alt = ALT_READERS .get (pinned ) 7296if alt is None : 7297return None 7298name ,size ,sha = alt 7299for p in places : 7300p = Path (p ) 7301try : 7302if p .name != name or not p .is_file ()or p .stat ().st_size != size : 7303continue # absent, another name or another size: ignored exactly as before 7304except OSError : 7305continue 7306digest = None 7307kept = _alt_reader_mark (p ) 7308try : 7309found = _ALT_MARK .match (kept .read_text (encoding = "utf-8" ,errors = "replace" ))if kept is not None and kept .exists ()else None 7310digest = found .group (1 )if found else None 7311except OSError : 7312digest = None 7313if digest is None : 7314if start : 7315say (f" checking { p . name } (SHA-256, { size / 1e9 :.1f } GB) ..." ) 7316digest = _hash_file (p ,size ) 7317if start and kept is not None : 7318try : 7319kept .parent .mkdir (parents = True ,exist_ok = True ) 7320kept .write_text (f"alt-reader sha256 { digest } \n" ,encoding = "utf-8" ) 7321except OSError : 7322pass # (not remembered: the next run hashes again; nothing else changes) 7323if digest == sha : 7324return p 7325if start : 7326say (f" note: { p } has the name of Unsloth's picture reader but is a different file, so it is not used. " 7327"The picture reader is downloaded (0.9 GB)." ) 7328return None 7329 7330 7331def resolve_reader (pinned :str ,mmproj :Path ,models_dir ,roots ,gguf_dir ,size ): 7332"""Which picture reader this run uses: (kind, path). `mmproj` is where the pinned file would be (the data folder's models/, or an earlier 7333install's copy when there is one). kind "fetch": the pinned file at `mmproj` (it exists, or it is downloaded); "near": the pinned file in the 7334person's own folder (mmproj_beside); "alt": a verified Unsloth mmproj-F16.gguf the person already has (only when no pinned file is anywhere).""" 7335if mmproj .exists (): 7336return "fetch" ,mmproj 7337near = mmproj_beside (gguf_dir ,pinned ,size ) 7338if near is not None : 7339return "near" ,near 7340alt = accepted_alt_reader (pinned ,alt_reader_places (pinned ,models_dir ,roots ,gguf_dir ),start = True ) 7341if alt is not None : 7342return "alt" ,alt 7343return "fetch" ,mmproj 7344 7345 7346def share_sibling_file (dst :Path ,parent :Path ,name :str ,size :int )-> bool : 7347"""A shared file that sits in another model's folder under `parent` (parent/<model folder>/<name>; Qwen3.6 keeps its picture file beside each size) is made 7348available at `dst` without the network: a hard link, else a copy. Only a file of the pinned `size`; its SHA-256 is checked by the caller's download(), as for 7349any file put there by hand. True when `dst` is there.""" 7350if dst .exists (): 7351return True 7352try : 7353sibs = sorted (p for p in parent .glob ("*/" + name )if p .is_file ()and p != dst and p .stat ().st_size == size ) 7354except OSError : 7355return False 7356for src in sibs : 7357try : 7358dst .parent .mkdir (parents = True ,exist_ok = True ) 7359try : 7360os .link (src ,dst ) 7361except OSError : 7362tmp = dst .with_name (dst .name + ".copying" ) 7363shutil .copyfile (src ,tmp ) 7364os .replace (tmp ,dst ) 7365return True 7366except OSError : 7367continue 7368return False 7369 7370 7371# ------------------------------------------------------------------------------------------------ start 7372def model_config (path :Path )-> bool : 7373"""#549: a model's run config (a JSON object with "exe" and "args"). Any other strata-*.json in the folder (a 7374file of the user's own, a cut-off one) is skipped with a warning naming it instead of stopping setup.""" 7375try : 7376cfg = json .loads (path .read_text (encoding = "utf-8-sig" )) 7377if isinstance (cfg ,dict )and cfg .get ("exe" )and isinstance (cfg .get ("args" ),list ): 7378return True 7379why = 'no "exe" or "args"' 7380except OSError as e : 7381why = e .strerror or str (e ) 7382except ValueError : 7383why = "not valid JSON" 7384warn (f"skipped { path . name } ( { why } ): it is not a Strata model config" ) 7385return False 7386 7387 7388def installed_configs (): 7389"""The model configs of this install, newest first; a DeepSeek one is not among them (this Strata does not run, check, tune or rewrite it: 7390retired_configs, strata_control/retired.py).""" 7391from strata_control import retired 7392return [p for p in sorted (model_config_files (home ()),key = lambda p :p .stat ().st_mtime ,reverse = True ) 7393if model_config (p )and not retired .config_file_reason (p )] 7394 7395 7396def retired_configs ()-> list : 7397"""The DeepSeek model configs of this install: left exactly as they are.""" 7398from strata_control import retired 7399return [p for p in sorted (model_config_files (home ()))if model_config (p )and retired .config_file_reason (p )] 7400 7401 7402def source_version ()-> str : 7403"""The engine version the source tree builds (CMakeLists.txt's project version). "0" when there is none to read: the packaged 7404Terminal carries no CMakeLists.txt (it ships VERSION and BUNDLE.json), and a missing file was a FileNotFoundError out of 7405prebuilt_bases() that ended the whole setup (#4188).""" 7406try : 7407m = re .search (r"project\(strata VERSION ([\d.]+)" , (ROOT / "CMakeLists.txt" ).read_text (encoding = "utf-8" )) 7408except (OSError ,UnicodeDecodeError ): 7409return "0" 7410return m .group (1 )if m else "0" 7411 7412 7413def binary_engine_version (exe )-> str | None : 7414"""The version compiled into an engine binary (the `engine=X.Y.Z` line it prints at start; 0.1.13 and newer carry 7415it), read from the file without running it. None: unreadable, or a binary without it.""" 7416try : 7417m = re .search (rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n" ,Path (exe ).read_bytes ()) 7418except OSError : 7419return None 7420return m .group (1 ).decode ()if m else None 7421 7422 7423def stale_binary (exe )-> bool : 7424"""#2054: the engine binary is of another version than this source tree builds. A BUILD.json that carries the 7425source's hash and version cannot be trusted alone: a build that stopped (a host compiler the toolkit rejects) can 7426leave the old binary beside a stamp of the new source, and nothing would ever compile it again.""" 7427v ,source = binary_engine_version (exe ),source_version () 7428return v is not None and source != "0" and v != source # "0": no source tree to compare with (the packaged Terminal) 7429 7430 7431def engine_version (exe :Path )-> tuple : 7432"""The version in the engine folder's BUILD.json, or else the one compiled into the binary. A locally compiled 7433engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept 7434(issue #49).""" 7435try : 7436meta = json .loads ((Path (exe ).parent / "BUILD.json" ).read_text (encoding = "utf-8" )) 7437except (OSError ,ValueError ): 7438meta = {} 7439v = str (meta .get ("version" )or "" ) 7440if not v :# the version compiled into the binary: 0.1.13 and newer 7441try :# carry it, so a binary without it is older 7442m = re .search (rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n" ,Path (exe ).read_bytes ()) 7443v = m .group (1 ).decode ()if m else "0.1.12" 7444except OSError : 7445v = "0" 7446return tuple (int (x )for x in v .split ("." )[:4 ]if x .isdigit ()) 7447 7448 7449def is_wsl ()-> bool : 7450return sys .platform .startswith ("linux" )and "microsoft" in platform .uname ().release .lower () 7451 7452 7453def ple_ram_platform_ok ()-> bool : 7454"""147-verify: --ple-io ram for a PC with RAM to spare was measured on Linux only (Windows locks pages differently and 7455WSL pins little), so only there.""" 7456return not WIN and not is_wsl () 7457 7458 7459def rotational_disk (path )-> str | None : 7460"""#605 (Linux): the disk's name when `path` is on a rotational disk (sysfs queue/rotational), else None.""" 7461if WIN : 7462return None 7463try : 7464st = os .stat (path ) 7465p = Path (f"/sys/dev/block/ { os . major ( st . st_dev ) } : { os . minor ( st . st_dev ) } " ).resolve () 7466for q in (p ,p .parent ):# a partition has its disk's queue 7467f = q / "queue" / "rotational" 7468if f .exists (): 7469return q .name if f .read_text ().strip ()== "1" else None 7470except (OSError ,ValueError ,AttributeError ): 7471pass 7472return None 7473 7474 7475def hip_config_cards (sel )-> list [dict ]: 7476"""#566: the AMD cards a HIP config runs on - its "gpu" (one index or a list) in HIP's numbering, as amd_gpus 7477lists them; no "gpu": the supported card with the most VRAM, as setup picks it. Each card's name carries its 7478architecture (an RX 7900 XTX and an RX 7900 XT are both gfx1100; a card without a product name in sysfs is known 7479by its arch only). A card that is not found is {} (the key then says "?").""" 7480amd = amd_gpus () 7481if sel is None : 7482usable = [g for g in amd if amd_problem (g )is None ] 7483sel = min (usable ,key = amd_rank )["index" ]if usable else None 7484byid = {g ["index" ]:g for g in amd } 7485cards = [] 7486for i in (sel if isinstance (sel ,list )else [sel ]): 7487g = byid .get (i ) 7488if g is None : 7489cards .append ({}) 7490continue 7491arch = g .get ("arch" )or "" 7492name = g .get ("name" )or "?" 7493cards .append ({** g ,"name" :name if not arch or arch in name else f" { name } ( { arch } )" }) 7494return cards 7495 7496 7497def gpu_sel (value )-> list : 7498"""A config's "gpu" as a list of card numbers: 0, [0, 2] or the string form "0,2" (which serve splits 7499the same way). [] when it names none. Without this, a string "0,1" reached gpu_info() whole and 7500calibrate died with "there is no GPU 0,1" on a dual-GPU config.""" 7501if value is None or value == "" : 7502return [] 7503items = value if isinstance (value , (list ,tuple ))else str (value ).split ("," ) 7504sel = [] 7505for x in items : 7506x = str (x ).strip () 7507if x == "" : 7508continue 7509sel .append (int (x )if x .isdigit ()else x ) 7510return sel 7511 7512 7513def hardware_key (cfg :dict )-> str : 7514"""What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting 7515(the context's KV cache and the image encoder take VRAM from the expert cache). #566: a HIP config's cards are 7516AMD's (hip_config_cards) - nvidia-smi's list named them "?" (or another card with that number) before.""" 7517sel = cfg .get ("gpu" ) 7518if isinstance (sel ,str ): 7519sel = gpu_sel (sel ) 7520if cfg .get ("backend" )== "hip" : 7521gl = hip_config_cards (sel ) 7522else : 7523gl = [gpu_info (i )or {}for i in sel ]if isinstance (sel ,list )else [gpu_info (sel )or {}] 7524g = {"name" :" + " .join (x .get ("name" ,"?" )for x in gl ),"vram_gb" :sum (x .get ("vram_gb" ,0 )for x in gl )} 7525a = cfg .get ("args" , []) 7526ctx = a [a .index ("--max-context" )+ 1 ]if "--max-context" in a else "?" 7527return "|" .join ([g .get ("name" ,"?" ),f" { g . get ( 'vram_gb' , 0 ):.0f } GB" ,cpu_info ()[0 ],f" { ram_gb ():.0f } GB" , 7528cfg .get ("model_name" ,"?" ),ctx ,"images" if "--vision" in a else "text" ]) 7529 7530 7531def calibrate_config (cfg_path :Path )-> bool : 7532"""Measure the engine's hardware-dependent settings on this PC (tools/calibrate.py), write them into the run 7533config and remember them per PC and model in the settings file, so an update or a reinstall keeps them.""" 7534sys .path .insert (0 ,str (ROOT / "tools" )) 7535import calibrate as CAL 7536cfg = json .loads (cfg_path .read_text (encoding = "utf-8-sig" )) 7537say () 7538say (" Tuning Strata for this PC: the output speed is measured with a few engine settings (the PCIe share, the" ) 7539say (" draft depth, the CPU threads, the expert cache; on two or more cards also the prompt chunks). It takes" ) 7540say (" roughly 15-30 minutes (3 rounds of each value); the PC is busy meanwhile." ) 7541try : 7542since = os .path .getsize (cfg ["log" ])if cfg .get ("log" )and os .path .isfile (cfg ["log" ])else 0 7543except OSError : 7544since = 0 7545try : 7546res = CAL .run (cfg ,say = say ) 7547except Exception as e :# never stops an install: the defaults stay 7548warn (f"the tuning did not finish ( { e } ): the default settings stay" ) 7549why = CAL .engine_error (cfg .get ("log" ),since )# #447: the engine's own reason, not only "see the log" 7550if why : 7551say (f" the engine said: { why } " ) 7552return False 7553cfg ["args" ]= CAL .apply (cfg ["args" ],res ["settings" ]) 7554if "env" in res :# HIP: the engine variables it measured (STRATA_SH_STREAM) 7555cfg ["env" ]= CAL .apply_env (cfg .get ("env" ),res ["env" ]) 7556write_config (cfg_path ,cfg ) 7557st = load_settings () 7558st .setdefault ("calibration" , {})[hardware_key (cfg )]= {"settings" :res ["settings" ],"env" :res .get ("env" )or {}, 7559"tok_s" :res ["report" ].get ("tok_s" ), 7560"date" :time .strftime ("%Y-%m-%d" )} 7561save_settings (st ) 7562chosen = {** res ["settings" ],** (res .get ("env" )or {})} 7563if chosen : 7564ok ("tuned for this PC: " + ", " .join (f" { k } { v } " if k .startswith ("--" )else f" { k } = { v } " for k ,v in chosen .items ()) 7565+ (f" ( { res [ 'report' ][ 'tok_s' ] } tok/s)" if res ["report" ].get ("tok_s" )else "" )) 7566else : 7567ok ("tuned for this PC: the default settings are already the fastest here" 7568+ (f" ( { res [ 'report' ][ 'tok_s' ] } tok/s)" if res ["report" ].get ("tok_s" )else "" )) 7569return True 7570 7571 7572def saved_calibration (cfg :dict )-> dict | None : 7573"""The settings an earlier calibration found for this PC and model, if any.""" 7574return (load_settings ().get ("calibration" )or {}).get (hardware_key (cfg )) 7575 7576 7577def setup_calibration (cfg :dict ,hip :bool )-> dict | None : 7578"""The calibration a (re-)install applies to its new config: the one saved for this PC and model. #566: on Linux 7579HIP too - hardware_key now names the AMD cards, so a `./setup.sh --calibrate` run is matched to its card and 7580model. Windows HIP keeps the defaults for now (not tried there). Setup still offers the tuning itself on NVIDIA 7581only: each control is verified on HIP first.""" 7582if hip and WIN : 7583return None 7584return saved_calibration (cfg ) 7585 7586 7587def upgrade_config (cfg_path :Path ,cfg :dict )-> dict : 7588"""Configs written before v0.1.13 read prompts in fixed 2048-token chunks; the engine now picks the chunk 7589itself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts). Under WSL, 7590KV streaming is dropped: its RAM copy must be pinned, and the driver pins only about 1 GB there.""" 7591a = cfg .get ("args" , []) 7592changed = False 7593ver = engine_version (cfg ["exe" ])if "--prefill" in a else (0 ,0 ,0 ) 7594if "--prefill" in a and a [a .index ("--prefill" )+ 1 ]== "2048" and ver >= (0 ,1 ,13 ): 7595a [a .index ("--prefill" )+ 1 ]= "auto" 7596changed = True 7597ok ("prompt reading: the engine now picks its chunk size (--prefill auto)" ) 7598elif "--prefill" in a and a [a .index ("--prefill" )+ 1 ]== "auto" and (0 ,0 ,0 )< ver < (0 ,1 ,13 ): 7599a [a .index ("--prefill" )+ 1 ]= "2048" # an older engine kept after a failed update (issue #49) 7600changed = True 7601warn (f"the installed engine is { '.' . join ( map ( str , ver )) } : prompts are read in 2048-token chunks until it is updated" ) 7602if is_wsl ()and "--kv-resident" in a : 7603i = a .index ("--kv-resident" ) 7604del a [i :i + 2 ] 7605changed = True 7606ok ("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM" ) 7607if changed : 7608write_config (cfg_path ,cfg ) 7609return cfg 7610 7611 7612def update_install (have :list ,a )-> int : 7613"""#475: `setup.py --update` (UPDATE.bat / update.sh, after their git pull): what a plain START-HERE.bat does to 7614an install before it starts the model, without starting it - the Python packages, the ready-made engine when this 7615setup needs a newer one (MIN_ENGINE; a compiled engine when its source changed), each installed model's config 7616upgrades and its draft subset. No question is asked and the model files are not touched; a model still running 7617keeps its engine (update_installed_engine says to close it and run this again).""" 7618have = [p for p in have if model_config (p )]# #549: a strata-*.json that is no model config is skipped 7619if not have : 7620say (" No model is installed in this Strata folder yet: run START-HERE.bat (Linux: ./setup.sh) to set it up -" ) 7621say (" it finds an earlier install's model files next to it and reuses them." ) 7622return 0 7623pip_install (runtime_packages (), 7624"numpy, jinja2, regex, pyyaml, tqdm, requests, pillow, psutil, textual (the screens)" ) 7625if not a .build : 7626update_installed_engine (a .prebuilt ) 7627mtp_done :set = set () 7628for cfg_path in have : 7629cfg = upgrade_config (cfg_path ,json .loads (cfg_path .read_text (encoding = "utf-8-sig" ))) 7630if not own_path_config (cfg ): 7631refresh_shared_draft_vocab (cfg ,mtp_done ) 7632if cfg .get ("backend" )== "hip" and WIN : 7633hip_runtime_beside_exe (Path (cfg ["exe" ]).parent )# #468 #461 7634ok (f" { cfg . get ( 'model_name' , cfg_path . stem ) } : up to date" ) 7635ver = engine_version (Path (json .loads (have [0 ].read_text (encoding = "utf-8-sig" ))["exe" ])) 7636say () 7637start = "START-HERE.bat" if WIN else "./setup.sh" 7638if any (ver )and tuple (ver )< MIN_ENGINE :# #3653: the engine step failed above; "updated" would be untrue 7639warn (f"Strata's files are updated, but the engine was NOT: it is still { '.' . join ( map ( str , ver )) } and this Strata wants " 7640f" { '.' . join ( map ( str , MIN_ENGINE )) } or newer. The model still starts with the old engine." ) 7641say (f" Next step: check the internet connection (and that the model window is closed), then run { 'UPDATE.bat' if WIN else './update.sh' } again; " 7642"the line above this one says why the engine was not fetched." ) 7643return 0 7644ok ("Strata is updated" + (f" (engine { '.' . join ( map ( str , ver )) } )" if any (ver )else "" )+ 7645f". Start the model with { start } when you want it." ) 7646return 0 7647 7648 7649def settings_summary (cfg :dict ,port = None )-> str : 7650"""#564: the settings a start uses, in one line: the config's engine options (the model's file paths left out) 7651and the server's own fields, so a change made by hand to strata-<model>.json can be checked without the log.""" 7652a ,out ,i = [str (x )for x in cfg .get ("args" )or []], [],0 7653while i < len (a ): 7654flag = a [i ] 7655val = a [i + 1 ]if i + 1 < len (a )and not a [i + 1 ].startswith ("--" )else None 7656i += 1 if val is None else 2 7657if not flag .startswith ("--" ): 7658continue # a positional: the model file 7659if val is not None and ("/" in val or "\\" in val or val .lower ().endswith ((".gguf" ,".bin" ))): 7660continue # a path: --native, --mtp, --profile ... 7661out .append (flag if val is None else f" { flag } { val } " ) 7662srv = [f" { cfg . get ( 'host' , '127.0.0.1' ) } : { port or cfg . get ( 'port' , 8080 ) } " ] 7663if cfg .get ("api_key" ): 7664srv .append ("api key set" ) 7665if cfg .get ("open_browser" )is False :# #609 7666srv .append ("no browser" ) 7667for k in ("gpu" ,"layer_split" ,"draft_vocab" ,"fit_max_tokens" ,"reasoning_budget_tokens" ,"anthropic_thinking" ): 7668if cfg .get (k )is not None : 7669v = cfg [k ] 7670srv .append (f" { k } { ',' . join ( map ( str , v )) if isinstance ( v , list ) else str ( v ). lower () if isinstance ( v , bool ) else v } " ) 7671return " " .join (out )+ ("; " if out else "" )+ "server " + ", " .join (srv ) 7672 7673 7674def start (cfg_path :Path ,port :int | None ,gpu :int | list | None = None ,open_browser = True ,yes = False , 7675layer_split = None ,keep = None )-> int : 7676"""Start the model. Nothing is installed, downloaded or compiled while it starts (strata_control/acquisition.py): 7677what is missing is named with the command that installs it (SETUP / UPDATE / strata install).""" 7678with acquisition .forbidden (): 7679return _start (cfg_path ,port ,gpu ,open_browser ,yes ,layer_split ,keep ) 7680 7681 7682def _start (cfg_path :Path ,port :int | None ,gpu :int | list | None = None ,open_browser = True ,yes = False , 7683layer_split = None ,keep = None )-> int : 7684"""keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab, 7685--vram-reserve-mib).""" 7686cfg = upgrade_config (cfg_path ,json .loads (cfg_path .read_text (encoding = "utf-8-sig" ))) 7687component = engine_component .is_reference (cfg ["exe" ]) 7688# The server resolves and verifies component engines; the reference itself is not a file. 7689files = ([]if component else [cfg ["exe" ]])+ [a for a in cfg ["args" ]if a .endswith (".gguf" )] 7690missing = [p for p in files if not Path (p ).exists ()] 7691if missing : 7692fail (f" { cfg_path . name } refers to missing files: { missing [ 0 ] } " ,"run it again with --setup to repair" ) 7693keep = {k :v for k ,v in (keep or {}).items ()if v is not None } 7694reserve = keep .pop ("vram_reserve_mib" ,None )# #493: an engine argument, kept in the config's args 7695if reserve is not None : 7696args = cfg ["args" ] 7697if "--vram-reserve-mib" in args [:- 1 ]: 7698args [args .index ("--vram-reserve-mib" )+ 1 ]= str (reserve ) 7699else : 7700args += ["--vram-reserve-mib" ,str (reserve )] 7701cfg [user_args .USER_KEY ]= user_args .set_flag (user_args .capture (cfg ),"--vram-reserve-mib" ,reserve )# the person's own value: kept by every later setup run and start 7702if user_args .WRITTEN_KEY in cfg : 7703cfg [user_args .WRITTEN_KEY ]= list (cfg ["args" ]) 7704write_config (cfg_path ,cfg ) 7705ok (f"saved for this model: { reserve } MiB of VRAM kept free for other programs (--vram-reserve-mib)" ) 7706if keep and any (cfg .get (k )!= v for k ,v in keep .items ()):# #179: a --host/--api-key on a start was ignored 7707cfg .update (keep ) 7708write_config (cfg_path ,cfg ) 7709ok ("saved for this model: " + ", " .join ( 7710"api key" if k == "api_key" else ("the browser opens" if v else "no browser" )if k == "open_browser" 7711else f" { k . replace ( '_' , ' ' ) } { v } " for k ,v in keep .items ())) 7712cfg_path .touch ()# the most recently used model 7713if "--mtp" in cfg ["args" ][:- 1 ]and not own_path_config (cfg ): 7714refresh_draft_vocab (Path (cfg ["args" ][cfg ["args" ].index ("--mtp" )+ 1 ]),cfg .get ("draft_vocab" ,"cjk" )) 7715from strata_control import drafting 7716refresh_dflash2_vocab (drafting .data_dir_of (cfg ["args" ]),cfg .get ("draft_vocab" ,"cjk" )) 7717cmd = [sys .executable ,str (ROOT / "serve" / "server.py" ),"--engine" ,"strata" ,"--config" ,str (cfg_path ), 7718"--port" ,str (port or cfg .get ("port" ,8080 ))] 7719if cfg .get ("backend" )== "hip" :# AMD, numbered as HIP numbers them (setup's KFD order) 7720if WIN and not component : 7721hip_runtime_beside_exe (Path (cfg ["exe" ]).parent )# #468 #461: also fixes a 0.1.34 install 7722amd = amd_gpus () 7723if isinstance (gpu ,list ):# --gpus: saved, this model runs on these cards from now on 7724cards = amd_parse_gpus ("," .join (str (i )for i in gpu ),amd ) 7725built = []if component else (engine_archs_hip ()or []) 7726miss = [x for x in cards if built and x ["arch" ]not in built ] 7727if miss : 7728fail ("the installed engine has no code for " + ", " .join (f" { x [ 'name' ] } ( { x [ 'arch' ] } )" for x in miss ), 7729"set it up for these cards: ./setup.sh --setup --backend hip --gpus " + "," .join (map (str ,gpu ))) 7730cfg ["gpu" ],cfg ["gpus_asked" ],cfg ["gpus_by" ]= gpu ,True ,"person" 7731cfg ["layer_split" ]= layer_split or cfg .get ("layer_split" )or "auto" 7732split_budget (cfg ,yes ,True )# #498: before it is saved (asks when the RAM is short, #737) 7733write_config (cfg_path ,cfg ) 7734gpu = None 7735elif gpu is not None : 7736cmd += ["--gpu" ,str (gpu )] 7737found = [] 7738use = gpu if gpu is not None else cfg .get ("gpu" ) 7739if isinstance (use ,list ): 7740byid = {x ["index" ]:x for x in amd } 7741ok ("GPUs: " + " + " .join (gpu_name (byid [i ])if i in byid else f"GPU { i } (not found)" for i in use ) 7742+ f" together, AMD (layers split { cfg . get ( 'layer_split' ) or 'auto' } )" ) 7743else : 7744g = next ((x for x in amd if x ["index" ]== (use if use is not None else x ["index" ]) 7745and amd_problem (x )is None ),None ) 7746if g is not None : 7747ok (f"GPU: { g [ 'name' ] } ( { g [ 'vram_gb' ]:.0f } GB, AMD)" ) 7748else : 7749found = gpus () 7750global OLD_GPUS # Pascal / Volta: named on this start, or this model's CUDA 12 engine 7751OLD_GPUS = OLD_GPUS or old_gpus_opt_in (found ,gpu if isinstance (gpu ,list )else [gpu ]if gpu is not None else 7752cfg .get ("gpu" )if isinstance (cfg .get ("gpu" ),list )else [cfg .get ("gpu" )], 775312 if config_toolkit (cfg )== 12 else None ) 7754if cfg .get ("backend" )== "hip" : 7755pass 7756elif isinstance (gpu ,list ):# --gpus: saved, this model runs on these cards from now on 7757check_gpus (gpu ,found ,yes = yes ,named = True ) 7758cfg ["gpu" ],cfg ["gpus_asked" ]= gpu ,True 7759cfg ["layer_split" ]= layer_split or cfg .get ("layer_split" )or "auto" 7760split_budget (cfg ,yes ,True )# #498: before it is saved (asks when the RAM is short, #737) 7761recommend_remote_expert_opt (cfg ) 7762write_config (cfg_path ,cfg ) 7763gpu = None 7764elif gpu is not None :# --gpu N: this start only, on that card 7765check_gpus ([gpu ],found ) 7766cmd += ["--gpu" ,str (gpu )] 7767else : 7768cfg = offer_together (cfg_path ,cfg ,yes ) 7769use = gpu if gpu is not None else cfg .get ("gpu" ) 7770# #364 #384: a resident low-RAM config on several GPUs; #498: a UD-Q4_K_XL config with its RAM budget (by hand) 7771if isinstance (use ,list )and (split_mmap (cfg )| split_budget (cfg )): 7772write_config (cfg_path ,cfg ) 7773if cfg .get ("backend" )== "hip" : 7774pass 7775elif isinstance (use ,list ): 7776check_gpus (use ,found ,"(chosen for this model) " ,yes = True ,named = True ) 7777byid = {g ["index" ]:g for g in found } 7778cfg = ensure_engine_for ([byid [i ]for i in use ],cfg_path ,cfg ,yes ) 7779ok ("GPUs: " + " + " .join (gpu_name (byid [i ])for i in use )+ f" together (layers split { cfg . get ( 'layer_split' ) or 'auto' } )" ) 7780elif found : 7781g = next ((x for x in found if x ["index" ]== use ),None )if use is not None else max ( 7782found ,key = lambda x : (round (x ["vram_gb" ]),- x ["index" ])) 7783if g is not None : 7784cfg = ensure_engine_for ([g ],cfg_path ,cfg ,yes ) 7785ok ("GPU: " + gpu_name (g )) 7786browser = open_browser and cfg .get ("open_browser" )is not False # #609: "open_browser": false, --no-browser 7787if browser : 7788cmd .append ("--open" ) 7789gb = 0.0 7790if "--native" in cfg ["args" ]: 7791try : 7792gb = Path (cfg ["args" ][cfg ["args" ].index ("--native" )+ 1 ]).stat ().st_size / 1e9 7793except (OSError ,IndexError ): 7794pass 7795say () 7796say (" " + "-" * 100 ) 7797size = f'about { gb :.0f } GB' if gb >= 1 else '34-55 GB' 7798a_ = cfg ["args" ] 7799if "--mmap-experts" in a_ and "--resident-budget-gib" not in a_ and "--resident-experts" not in a_ : 7800# #505: the mapped low-RAM mode loads nothing into RAM up front (the server's narrator says the same) 7801say (f" Starting { cfg . get ( 'model_name' , 'the model' ) } : it maps { size } of experts from the model files (the OS " 7802"file cache reads them)." ) 7803else : 7804say (f" Starting { cfg . get ( 'model_name' , 'the model' ) } : it loads { size } into RAM and locks part of it for the " 7805"GPU." ) 7806say (" While it does, YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES (longer the first time after a" ) 7807say (" restart). That is normal: please wait and don't close this window - " + ( 7808"the browser opens when it is ready." if browser else "the server says when it is ready." )) 7809say (" Later, closing this window stops the model." ) 7810say (" " + "-" * 100 ) 7811for n ,line in enumerate (textwrap .wrap (f"Settings ( { cfg_path . name } ): { settings_summary ( cfg , port ) } " ,100 , 7812break_on_hyphens = False )):# #564: what this start uses 7813say ((" " if n == 0 else " " )+ line ) 7814if not WIN and os .environ .get ("STRATA_EXECV" ): 7815# Replace this process instead of spawning a child. The Docker image sets STRATA_EXECV=1, 7816# so there the server is PID 1 and docker stop's SIGTERM reaches the process that can 7817# answer the engine with QUIT. Normal Linux starts keep spawning the server as a child. 7818os .execve (cmd [0 ],cmd , {** os .environ ,acquisition .ENV :"1" }) 7819# the server and everything it starts are told, too: nothing in a running model installs or downloads 7820return subprocess .call (cmd ,env = {** os .environ ,acquisition .ENV :"1" }) 7821 7822 7823# the draft subsets setup copied before (sha256): replaced by the current one, a subset made by hand is kept 7824OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25" }# to 0.1.26: 27 Han tokens 7825 7826 7827DRAFT_VOCABS = {"cjk" :"draft_vocab.bin" ,"en" :"draft_vocab_en.bin" ,"cyrillic" :"draft_vocab_cyrillic.bin" , 7828"fr" :"draft_vocab_fr.bin" ,"latin" :"draft_vocab_latin.bin" } 7829 7830 7831def saved_draft_vocab (cfg_path :Path )-> str | None : 7832"""The draft subset a model's config chose earlier (--draft-vocab), or None: a setup run again without the flag 7833rewrites the config, and would otherwise put the default subset back.""" 7834try : 7835v = json .loads (cfg_path .read_text (encoding = "utf-8-sig" )).get ("draft_vocab" ) 7836except (OSError ,ValueError ,AttributeError ): 7837return None 7838return v if v in DRAFT_VOCABS else None 7839 7840 7841def vision_tokens (asked :int | None ,vision :str ,earlier :Path | None )-> int : 7842"""#625: the most image tokens a picture becomes (the config's vision.max_tokens): --vision-tokens N, else what an 7843earlier config of this model chose for the same encoder device (a setup run again keeps it), else the device's 7844default (VISION). More is allowed with a note on the time it takes: setup recommends, it does not cap.""" 7845default = VISION [vision ]["max_tokens" ] 7846if asked is None and earlier is not None : 7847try : 7848v = json .loads (earlier .read_text (encoding = "utf-8-sig" )).get ("vision" ) 7849except (OSError ,ValueError ,AttributeError ): 7850v = None 7851mt = v .get ("max_tokens" )if isinstance (v ,dict )and bool (v .get ("gpu" ))== (vision == "gpu" )else None 7852if isinstance (mt ,int )and mt > 0 and mt != default : 7853asked = mt 7854if asked is None : 7855return default 7856note = "" 7857if vision == "cpu" and asked > default : 7858note = (" - on the CPU a picture takes longer to encode the more tokens it gets (several seconds more at " 7859"1,024 than at 300)" ) 7860elif asked > VISION ["gpu" ]["max_tokens" ]: 7861note = " - more than the encoder's default needs more VRAM and context per picture" 7862ok (f"images: up to { asked } image tokens per picture (--vision-tokens; default { default } ) { note } " ) 7863return asked 7864 7865 7866DRAFT_VOCAB_MIB = {"cjk" :348 ,"cyrillic" :193 ,"fr" :151 ,"en" :133 ,"latin" :203 }# the draft head's VRAM per subset (IQ3_S: the largest) 7867SMALL_DRAFT_VRAM_GB = 14 # #474: below this the default subset's head can be what does not fit 7868 7869 7870def draft_vocab_note (vram_gb :float ,chosen :str | None )-> list [str ]: 7871"""#474: on a card under 14 GB, the default draft subset (cjk, ~348 MiB of VRAM) can be what does not fit at the 7872start ("the draft head does not fit"), and the engine's expert cache gets what a smaller one leaves. Setup 7873RECOMMENDS a smaller one here and changes nothing (the owner's rule, #403 #406): a subset chosen with 7874--draft-vocab, or kept from an earlier install, gets no note. [] for every other case.""" 7875if chosen or not 0 < vram_gb < SMALL_DRAFT_VRAM_GB : 7876return [] 7877start = "START-HERE.bat" if WIN else "./setup.sh" 7878return [f"Tip for a { vram_gb :.0f } GB card: the draft layer's default token subset (with Chinese, Japanese and " 7879f"Korean) needs up to ~ { DRAFT_VOCAB_MIB [ 'cjk' ] } MiB of VRAM." , 7880f" For English and code answers, { start } --draft-vocab en needs up to ~ { DRAFT_VOCAB_MIB [ 'en' ] } MiB " 7881f"(cyrillic: ~ { DRAFT_VOCAB_MIB [ 'cyrillic' ] } ) and leaves the rest to the expert cache - and it is the" , 7882" fix when the start stops with \"the draft head does not fit\". The model keeps the choice." ] 7883 7884 7885SMALL_CARD_GB = 7.5 # #496: a card under 8 GB gets a tip (an 8 GB card lists 7.99) 7886 7887 7888def small_card_note (ctx :int ,draft_vocab :str | None )-> list [str ]: 7889"""#496: what frees VRAM on a card under 8 GB when the start stops with "no VRAM is left for the expert cache" 7890(the engine already lowers its own reserve on such a card) - a recommendation, setup changes none of it. (The 7891draft layer stays: the server needs it.)""" 7892start = "START-HERE.bat --setup" if WIN else "./setup.sh" 7893tips = [] 7894if ctx > 8192 : 7895tips .append ("an 8K context (a smaller KV cache)" ) 7896if draft_vocab != "en" : 7897tips .append (f"--draft-vocab en (a draft head of ~ { DRAFT_VOCAB_MIB [ 'en' ] } MiB instead of " 7898f"~ { DRAFT_VOCAB_MIB [ draft_vocab or 'cjk' ] } )" ) 7899lines = ["If the start stops with \"no VRAM is left for the expert cache\" (the engine's log says how much is " 7900"short):" ] 7901if tips : 7902lines .append (f" run { start } again with " + " and " .join (tips )+ ", or close other programs that use the GPU." ) 7903else : 7904lines .append (" close other programs that use the GPU." ) 7905return lines 7906 7907 7908# Unsloth's files on a card of about 8 GB. The dense side is Q8_0 (~3 GB) and the draft layer binds ~0.8 GB, so little is 7909# left for the expert cache. Measured on an 8 GB Arc A750 (the Intel worker, 2026-10-13): setup's 8192 / int8 / reserve 400 7910# start stopped with "no VRAM is left for the expert cache, short 473 MiB"; --max-context 4608 --kv q4_0 --vram-reserve-mib 0 7911# started with 3 cache slots (4.4 tok/s). UD_FIT_FIXED_MIB is that measurement turned into a constant (everything but the 7912# session's KV, the reserve and the draft layer); an ESTIMATE for CUDA and HIP cards of the same size, whose engine says what 7913# is short if it is off. The engine itself lowers its default reserve to 300 MiB on such a card. 7914UD_FIT_FIXED_MIB = 7356 7915UD_FIT_MTP_MIB = 802 7916UD_FIT_MIN_SLACK_MIB = 64 # at least a few cache slots beside the estimate's error 7917UD_FIT_CARD_GB = 9.5 # the check is for cards up to here 7918UD_FIT_RUNTIME_MIB = 250 # CUDA / HIP: the runtime's own context (the SYCL measurement above has none of it) 7919UD_FIT_ENGINE_RESERVE_MIB = 300 # the reserve the engine settles on when none is given and the card is tight 7920KV_WORDS = {"int8" :"8-bit" ,"q4_0" :"4-bit (Hadamard-rotated)" ,"k8v4" :"8-bit keys, 4-bit values" ,"fp16" :"16-bit" } 7921UD_FIT_KV_BYTES = {"fp16" :2112 ,"int8" :1056 ,"q4_0" :576 ,"k8v4" :816 }# per token per attention layer (13) 7922UD_FIT_CTX_STEPS = (8192 ,6144 ,4608 ) 7923 7924 7925def unsloth_runtime_mib (gpu :dict )-> int : 7926return 0 if (gpu or {}).get ("driver" )in ("xe" ,"i915" )else UD_FIT_RUNTIME_MIB 7927 7928 7929def unsloth_vram_slack_mib (vram_gb :float ,ctx :int ,kv :str ,reserve_mib :int ,mtp :bool = True , 7930runtime_mib :int = 0 )-> float : 7931"""MiB left for the expert cache by setup's estimate (negative: the engine would refuse to start).""" 7932session = ctx * 13 * UD_FIT_KV_BYTES .get (kv ,1056 )/ 2 ** 20 7933return vram_gb * 1024 - UD_FIT_FIXED_MIB - (UD_FIT_MTP_MIB if mtp else 0 )- session - max (reserve_mib ,0 )- runtime_mib 7934 7935 7936def unsloth_small_card_plan (vram_gb :float ,ctx :int ,kv :str ,reserve_mib :int | None ,ctx_fixed = False ,kv_fixed = False , 7937runtime_mib :int = 0 ): 7938"""(ctx, kv, mtp, slack_mib) of the least harmful start that the estimate says fits, or None when none does. 7939Order of harm: the KV in 4 bits, then a smaller context (down to 4608), then no draft layer on the GPU (decode 7940up to 2x slower, but 0.8 GB for the cache); a value the user chose (--context, --kv) is not changed.""" 7941reserve = UD_FIT_ENGINE_RESERVE_MIB if reserve_mib is None else reserve_mib 7942ctxs = [ctx ]if ctx_fixed else [ctx ]+ [c for c in UD_FIT_CTX_STEPS if c < ctx ] 7943kvs = [kv ]if kv_fixed or kv == "q4_0" else [kv ,"q4_0" ] 7944for mtp in (True ,False ): 7945for c in ctxs : 7946for k in kvs : 7947slack = unsloth_vram_slack_mib (vram_gb ,c ,k ,reserve ,mtp ,runtime_mib ) 7948if slack >= UD_FIT_MIN_SLACK_MIB : 7949return c ,k ,mtp ,slack 7950return None 7951 7952 7953def unsloth_small_card_lines (model :str ,vram_gb :float ,plan ,start_ok :bool )-> list [str ]: 7954"""The words for a ~8 GB card: that UD-* is very slow here and what to pick instead (always), and when the start 7955would have stopped, that and what setup changed instead. Recommend, never force.""" 7956lines = [f" { model } on a { vram_gb :.0f } GB card is very slow: the dense side and the draft layer fill the card, the expert " 7957"cache gets a few slots, and nearly every expert comes from RAM or the SSD (3-5 tok/s measured on an 8 GB " 7958"Arc A750). IQ3_XXS or IQ3_S of the Qwen3.8-Flash-Next family fit such a card far better; run setup again " 7959"and pick one of them." ] 7960if not start_ok and plan is None : 7961lines .append ("By setup's estimate even a 4608 context with a 4-bit KV cache and no draft layer leaves no room " 7962"for the expert cache on this card: the start will probably stop with \"no VRAM is left for the " 7963"expert cache\"." ) 7964return lines 7965 7966 7967PARALLEL_MAX = 8 # #465: the engine's batch window holds at most 8 requests 7968PARALLEL_SHARE = 0.2 # #465: the slots' sessions may take this share of the VRAM the expert cache would hold 7969PARALLEL_HELD = 0.5 # #465: ... and only where the cache still holds this share of the experts beside them 7970PARALLEL_COST_NOTE = ("parallel N reduces waiting for several users but costs about 10-25% speed per request on this " 7971"card" ) 7972 7973 7974def parallel_slot_gb (ctx :int ,kv :str ,streaming :bool )-> float : 7975"""#465: the VRAM one batch slot's session takes: its KV cache (12 QSA layers; with KV streaming only the 32K 7976positions the attention reads stay in VRAM) and the DeltaNet state (~0.17 GB). Measured: 0.56 GiB at 32K int8.""" 7977kv_tok = 12 * (576 if kv == "q4_0" else 1056 ) 7978return (min (ctx ,32768 )if streaming else ctx )* kv_tok / 1e9 + 0.17 7979 7980 7981def parallel_recommend (vram_gbs ,arena_gb :float ,ctx :int ,kv :str ,streaming :bool )-> int : 7982"""#465: how many requests at once ("parallel") to recommend: 0 = none (one at a time). Only where the experts 7983mostly fit in VRAM - the expert cache (each card's VRAM less ~5 GB, every card of a layer split) still holds 7984PARALLEL_HELD of the model's experts beside the slots' sessions, which take at most PARALLEL_SHARE of it, up to 4. 7985Where the experts mostly run on the CPU a batch reads about as many experts as the requests one by one and every 7986slot's VRAM is expert cache lost: measured on a 12 GB RTX 5070 (Q2_0, 32K), a request alone 11-24% slower with 2-4 7987slots, 4 requests together 63 tok/s against 71 one after the other (docs/BATCHING.md).""" 7988if isinstance (vram_gbs , (int ,float )): 7989vram_gbs = [vram_gbs ] 7990cache_gb = sum (max (0.0 ,v - 5 )for v in vram_gbs ) 7991slot = parallel_slot_gb (ctx ,kv ,streaming ) 7992best = 0 7993for n in (2 ,3 ,4 ): 7994if n * slot <= PARALLEL_SHARE * cache_gb and (cache_gb - n * slot )>= PARALLEL_HELD * arena_gb : 7995best = n 7996return best 7997 7998 7999def parallel_note (asked :int | None ,vram_gbs ,arena_gb :float ,ctx :int ,kv :str ,streaming :bool )-> list [str ]: 8000"""#465: what setup says about "parallel": the recommendation (or, where it would cost speed, why it is left at 8001one), or how the asked count compares with it (kept as asked: recommend, never force).""" 8002rec = parallel_recommend (vram_gbs ,arena_gb ,ctx ,kv ,streaming ) 8003slot = parallel_slot_gb (ctx ,kv ,streaming ) 8004if asked is None or asked <= 1 : 8005if not rec : 8006return [f"Several requests at once: left at one at a time - { PARALLEL_COST_NOTE } (docs/BATCHING.md)." ] 8007return [f"Several requests at once (opt-in): --parallel { rec } decodes up to { rec } together instead of one " 8008f"after the other (each takes ~ { slot :.1f } GB of VRAM from the expert cache; docs/BATCHING.md)." ] 8009lines = [f"parallel requests: { asked } at once (each takes ~ { slot :.1f } GB of VRAM from the expert cache, " 8010f" { asked * slot :.1f } GB in all)" ] 8011if asked > PARALLEL_MAX : 8012lines .append (f"the engine runs at most { PARALLEL_MAX } at once; it will use { PARALLEL_MAX } " ) 8013if not rec : 8014lines .append (f"recommended for this card: one at a time - { PARALLEL_COST_NOTE } ; kept as you chose" ) 8015elif asked > rec : 8016lines .append (f"recommended for this card: { rec } - more slots leave fewer experts in VRAM, which can make every " 8017"request slower; kept as you chose" ) 8018return lines 8019 8020 8021PREFILL_BIG_RAM_GB = 96 # bench #433 #440 #834 #669: --prefill auto:32768 +21-35% at 96 GB, ~3x slower at 32 GB 8022PREFILL_RISK_RAM_GB = 64 # below this an explicit auto:32768 is warned about 8023HEADROOM_RAM_GB = 48 # bench #834: STRATA_RESIDENT_HEADROOM_GIB=6 on a PC with this much RAM or less 8024AGENT_CACHE_FREE_GB = 24 # bench #882 #440: RAM left beside the model for the conversation cache 8025AGENT_CACHE_MIB = 8192 8026SMALL_VISION_VRAM_GB = 12.5 # bench #469: the GPU image encoder shrinks the prompt chunks on cards up to 12 GB 8027 8028 8029def arg_after (args ,flag ): 8030"""The value after `flag` in an argument list, or None.""" 8031return args [args .index (flag )+ 1 ]if flag in args [:- 1 ]else None 8032 8033 8034def bare_auto_is_32768 (gpu ,args ,env )-> bool : 8035"""Round 0212 (owner 11-03): the engine gives a bare `--prefill auto` a 32768-token ceiling on one NVIDIA card of compute capability 8.0 or up, and on 80367.0 (Volta; include/strata/core/nv_chunk.hpp `nv_chunk_card_ok`, called from generate.cpp); Turing (7.5) and Pascal (6.x) keep 8192. STRATA_NV_CHUNK=0 8037or STRATA_DEFAULTS=026 (the config's env or this process's) keep 8192, and a layer split reads 8192-token chunks. `gpu` is the one card the config 8038runs on (the engine sees only the cards CUDA_VISIBLE_DEVICES names, so for a mixed PC the lowest of those decides, which is this card).""" 8039arch = str ((gpu or {}).get ("arch" ,"" )) 8040if not arch .isdigit ()or len (arch )< 2 : 8041return False 8042major ,minor = int (arch [:- 1 ]),int (arch [- 1 ])# "70" -> 7.0, "86" -> 8.6, "120" -> 12.0 8043if not (major >= 8 or (major == 7 and minor == 0 )): 8044return False 8045if any (a in (args or [])for a in ("--gpus" ,"--layer-split" )): 8046return False 8047e = dict (env or {}) 8048nv_chunk = e .get ("STRATA_NV_CHUNK" ,os .environ .get ("STRATA_NV_CHUNK" )) 8049defaults = e .get ("STRATA_DEFAULTS" ,os .environ .get ("STRATA_DEFAULTS" )) 8050if (nv_chunk is not None and str (nv_chunk ).startswith (("0" ,"16" )))or str (defaults )in ("026" ,"0.2.6" ,"v0.2.6" ): 8051return False 8052return True 8053 8054 8055def bench_tips (args ,env ,ram :float ,model_ram_gb :float ,vram_gb :float ,vision :str ,win :bool ,gpu = None )-> list [str ]: 8056"""Recommendations from the community bench data (plan 0.1.40 item 14). Text only: nothing here changes a 8057default, the config or the engine's arguments (recommend, never force). `ram` is this PC's RAM, `model_ram_gb` 8058what the chosen model keeps in it.""" 8059tips = [] 8060cache = arg_after (args ,"--expert-cache" ) 8061if win and cache is not None and cache != "auto" : 8062tips .append (f"warning: --expert-cache { cache } is a fixed size. On Windows, a size that leaves almost no VRAM free " 8063"has run up to 7x slower (#780 #781); a smaller number, or auto, leaves the driver room" ) 8064prefill = arg_after (args ,"--prefill" ) 8065if prefill == "auto:32768" and ram < PREFILL_RISK_RAM_GB : 8066tips .append (f"warning: --prefill auto:32768 on { ram :.0f } GB of RAM: it ran ~3x slower than --prefill auto with " 8067"32 GB (#834 #669); it paid off (+21-35%) with 96 GB" ) 8068elif prefill == "auto" and ram >= PREFILL_BIG_RAM_GB and not bare_auto_is_32768 (gpu ,args ,env ):# already the default there (round 0212) 8069tips .append (f"tip: with { ram :.0f } GB of RAM, --prefill auto:32768 in the config's args read prompts 21-35% " 8070"faster in community benchmarks (#433 #440 #834); not set, nothing changes" ) 8071resident = any (a in args for a in ("--resident-experts" ,"--resident-budget-gib" )) 8072if resident and ram <= HEADROOM_RAM_GB and "STRATA_RESIDENT_HEADROOM_GIB" not in (env or {}): 8073tips .append (f"tip: on a PC with { ram :.0f } GB of RAM, \"env\": {{\"STRATA_RESIDENT_HEADROOM_GIB\": \"6\"}} in the " 8074"config kept decode speed in a community benchmark and left the system 2 GiB more (#834); the " 8075"default is 4" ) 8076if vision == "gpu" and 0 < vram_gb <= SMALL_VISION_VRAM_GB : 8077tips .append ("tip: the image encoder on the GPU makes a prompt's chunks smaller on a card this size (243 vs 750 " 8078"tok/s measured, #469); run setup again with --vision cpu to read prompts ~3x faster, at about " 8079"2-3 s per picture" ) 8080return tips 8081 8082 8083DISPLAY_RESERVE_MIB = 1500 # #779: the tip for an NVIDIA card that also drives a display 8084DESKTOP_RESERVE_MIB = 3072 # #560 #516: what kept a KDE/Wayland desktop alive beside a full expert cache 8085 8086 8087def linux_desktop (env = None )-> bool : 8088"""A graphical session on Linux (Wayland or X).""" 8089env = os .environ if env is None else env 8090return sys .platform .startswith ("linux" )and bool (env .get ("WAYLAND_DISPLAY" )or env .get ("DISPLAY" )) 8091 8092 8093def desktop_reserve_note ()-> list [str ]: 8094"""#560 #516: an AMD card that also drives a Linux desktop - with the default 700 MiB reserve the expert cache 8095fills it, and when the desktop needs more VRAM amdgpu moves the cache to system RAM, where the OOM killer then ends 8096the compositor. A recommendation, setup changes nothing.""" 8097return [f"If this AMD card also drives your desktop and the desktop or apps crash once the model is loaded, keep " 8098f"more VRAM free: ./setup.sh --vram-reserve-mib { DESKTOP_RESERVE_MIB } " , 8099" (remembered for this model; the expert cache gets ~2.3 GB less, a few % of speed)" ] 8100 8101 8102def mtp_corrupt (mtp :Path ,env = None )-> bool : 8103"""#327: True when the MTP tensors an install fetched are not the pinned checkpoint's (tools/mtp_fetch.py verify, 8104which hashes only files that changed since they last checked out). A mirror that ignored range requests left the 8105shards' starts there instead, and the draft layer built from them accepted nothing - with no error anywhere.""" 8106if not (mtp / "tensors" ).is_dir (): 8107return False 8108r = subprocess .run ([sys .executable ,str (ROOT / "tools" / "mtp_fetch.py" ),"verify" ,"--out" ,str (mtp )],env = env , 8109stdout = subprocess .PIPE ,stderr = subprocess .STDOUT ,text = True ,errors = "replace" ) 8110return r .returncode == 3 8111 8112 8113def provide_dflash2_vocab (data :Path ,choice :str = "cjk" )-> None : 8114"""A DFlash2-only install has no MTP folder to hold the draft vocabulary: it is kept beside the DFlash2 pack (strata_control/drafting.py provide_vocab), as the subset the person chose 8115in setup (--draft-vocab, saved in the model's config; the default file when none).""" 8116from strata_control import drafting 8117if drafting .provide_vocab (data ,choice or "cjk" )is None : 8118warn ("the draft vocabulary file (data/draft_vocab.bin) is missing from this Strata folder, so DFlash2 cannot start; update Strata" ) 8119 8120 8121def refresh_dflash2_vocab (data :Path | None ,choice :str = "cjk" )-> None : 8122"""The DFlash2 copy of the draft subset (beside its pack) follows the person's choice too, when that copy exists: an update, a start and setup run again keep or apply the 8123choice for a DFlash2-only install, which has no MTP folder for refresh_draft_vocab to work on.""" 8124if data is None : 8125return 8126from strata_control import drafting 8127if drafting .vocab_target (data ).is_file (): 8128drafting .refresh_vocab (data ,choice or "cjk" ) 8129 8130 8131def refresh_draft_vocab (rt :Path ,choice :str = "cjk" )-> None : 8132"""The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137), `en` 8133(data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster) or 8134`cyrillic` (data/draft_vocab_cyrillic.bin: English/code and the whole Cyrillic script, for Ukrainian, Russian, 8135Bulgarian, Serbian... answers) or `fr` (data/draft_vocab_fr.bin: English/code and the tokens of French text, #597) or `latin` (data/draft_vocab_latin.bin: English/code and 8136the tokens of German, Spanish, French and Polish text). 8137Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept.""" 8138new ,dst = ROOT / "data" / DRAFT_VOCABS .get (choice ,"draft_vocab.bin" ),rt / "draft_vocab.bin" 8139if not new .exists ()or not rt .is_dir (): 8140return 8141if dst .exists (): 8142old = hashlib .sha256 (dst .read_bytes ()).hexdigest () 8143shipped = OLD_DRAFT_VOCABS | {hashlib .sha256 ((ROOT / "data" / f ).read_bytes ()).hexdigest () 8144for f in DRAFT_VOCABS .values ()if (ROOT / "data" / f ).exists ()} 8145if old not in shipped or old == hashlib .sha256 (new .read_bytes ()).hexdigest (): 8146return 8147ok ("draft layer: the token subset " + {"cjk" :"with Chinese, Japanese and Korean" , 8148"cyrillic" :"with the Cyrillic script" , 8149"fr" :"for French" , 8150"latin" :"with the Latin-script languages" }.get (choice , 8151"for English and code (less VRAM)" )) 8152shutil .copyfile (new ,dst ) 8153 8154 8155def refresh_shared_draft_vocab (cfg :dict ,done :set )-> None : 8156"""update_install's draft subset of one config, for configs taken most recently used first (installed_configs' 8157order): an MTP folder already in `done` is left alone. Several configs can name one MTP folder (a second config of 8158the same model: another GPU mode, another context), each with its own "draft_vocab". Refreshed once per config, 8159the folder ended with the subset of the config used LONGEST ago: a config without the key (cjk) put the default 8160subset over the cyrillic one of the config in use, and its Russian answers were drafted without Cyrillic tokens. 8161The folder takes the subset of the most recently used config that names it; a start still installs its own 8162config's.""" 8163args = cfg .get ("args" )or [] 8164if "--mtp" not in args [:- 1 ]: 8165return 8166from strata_control import drafting 8167data = drafting .data_dir_of (args ) 8168if data is not None :# the DFlash2 copy, once per data folder, the config used last first like the MTP folder below 8169dkey = ("dflash2" ,os .path .normcase (os .path .abspath (data ))) 8170if dkey not in done : 8171done .add (dkey ) 8172refresh_dflash2_vocab (data ,cfg .get ("draft_vocab" ,"cjk" )) 8173rt = Path (args [args .index ("--mtp" )+ 1 ]) 8174key = os .path .normcase (os .path .abspath (rt )) 8175if key in done : 8176return 8177done .add (key ) 8178refresh_draft_vocab (rt ,cfg .get ("draft_vocab" ,"cjk" )) 8179 8180 8181def ensure_engine_for (cards ,cfg_path :Path ,cfg :dict ,yes :bool )-> dict : 8182"""The installed engine must have code for every card the model starts on: a card added later (--gpus with an 8183older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a 8184card gets the engine compiled for all of them, before the start. A Pascal / Volta card added to a model on the 8185CUDA 13 engine moves the model to the experimental CUDA 12 engine (CUDA 13 has no code for it).""" 8186if engine_component .is_reference (cfg .get ("exe" )): 8187return cfg # the server checks the installed component, not ROOT/engine 8188tk = config_toolkit (cfg ) 8189if tk == 13 and any (int (g ["arch" ])< CUDA13_MIN_ARCH for g in cards ): 8190return use_cuda12 (cards ,cfg_path ,cfg ,yes ) 8191missing = [g for g in cards if not (engine_runs_on (g )if tk == 13 else engine_runs_on (g ,tk ))] 8192if not missing : 8193return cfg 8194acquisition .require ("an engine with code for " + ", " .join (f" { g [ 'name' ] } (sm_ { g [ 'arch' ] } )" for g in missing ), 8195 ("START-HERE.bat --setup" if WIN else "./setup.sh --setup" )+ " (it compiles the engine for these cards)" ) 8196eng = engine_dir (tk ) 8197info = eng / "BUILD.json" 8198meta = json .loads (info .read_text (encoding = "utf-8" )) 8199say () 8200say (" The installed engine has no code for " + ", " .join (f" { g [ 'name' ] } (sm_ { g [ 'arch' ] } )" for g in missing )+ 8201": it is compiled for " + ("these cards" if len (cards )> 1 else "it" )+ " now." ) 8202main = gpu_info (cards [0 ]["index" ]) 8203archs = sorted (set (arch_numbers (meta .get ("archs" )))| {int (g ["arch" ])for g in cards }) 8204vision = meta .get ("vision" )or ("gpu" if (eng / VEXE ).exists ()else "none" ) 8205build_engine ({** main ,"archs" :archs },vision ,yes ,llama_override (),toolkit = tk ) 8206dirs = json .loads (info .read_text (encoding = "utf-8" )).get ("cuda_dirs" )or [] 8207cfg ["lib_dirs" ]= dirs + [d for d in cfg .get ("lib_dirs" )or []if d not in dirs ] 8208write_config (cfg_path ,cfg ) 8209return cfg 8210 8211 8212def get_cuda12_engine (url_base ,gpu ,vision ,yes ,build = False )-> Path : 8213"""The experimental CUDA 12 engine for these cards (gpu["archs"]): the ready-made one (Windows) with NVIDIA's 8214CUDA 12 libraries, or compiled here with a CUDA 12.x toolkit (Linux, --build, or no ready-made one).""" 8215eng = None if build else get_prebuilt (url_base ,gpu ,vision ,toolkit = 12 ) 8216if eng is not None and json .loads ((eng / "BUILD.json" ).read_text (encoding = "utf-8" )).get ("source" )!= "local" : 8217pip_cuda_libs (12 ) 8218if vision != "none" and not (eng / VEXE ).exists (): 8219eng = None 8220return eng if eng is not None else build_engine (gpu ,vision ,yes ,llama_override (),toolkit = 12 ) 8221 8222 8223def engine_lib_dirs (eng :Path ,toolkit = 13 )-> list : 8224"""The library folders a CUDA engine loads from: its own (a compiled one: the toolkit's), else pip's wheels.""" 8225meta = json .loads ((eng / "BUILD.json" ).read_text (encoding = "utf-8" )) 8226return meta .get ("lib_dirs" )or meta .get ("cuda_dirs" )or cuda_lib_dirs (toolkit ) 8227 8228 8229def use_cuda12 (cards ,cfg_path :Path ,cfg :dict ,yes :bool )-> dict : 8230"""A model on the CUDA 13 engine now has a Pascal / Volta card (a --gpus at start): the model's config moves to 8231the experimental CUDA 12 engine (one engine per model; its other models keep theirs).""" 8232acquisition .require ("the experimental CUDA 12 engine" ) 8233old = min (int (g ["arch" ])for g in cards ) 8234acquisition .require ("the experimental CUDA 12 engine for sm_%d" % old , 8235 ("START-HERE.bat --setup --cuda 12" if WIN else "./setup.sh --setup --cuda 12" )) 8236say () 8237warn (f"sm_ { old } is older than CUDA 13 supports (it dropped Pascal and Volta): this model moves to the experimental " 8238"CUDA 12 engine (docs/OLDER_GPUS.md; START-HERE.bat --setup --cuda 13 and newer cards only moves it back)" ) 8239main = gpu_info (cards [0 ]["index" ])or cards [0 ] 8240vision = "gpu" if cfg .get ("vision" )else "none" 8241eng = get_cuda12_engine (os .environ .get ("STRATA_PREBUILT_URL" ,PREBUILT_URL ), 8242 {** main ,"archs" :sorted ({int (g ["arch" ])for g in cards })},vision ,yes ) 8243cfg ["exe" ]= str (eng / EXE ) 8244cfg ["cuda" ]= 12 8245cfg ["lib_dirs" ]= engine_lib_dirs (eng ,12 ) 8246if cfg .get ("vision" )and (eng / VEXE ).exists (): 8247cfg ["vision" ]["exe" ]= str (eng / VEXE ) 8248write_config (cfg_path ,cfg ) 8249ok (f"engine: { eng / EXE } (CUDA 12, experimental)" ) 8250return cfg 8251 8252 8253def write_run_script (model ,cfg_path ,port ,open_browser = True ): 8254"""run-<model>.bat / .sh: the server with this config; `open_browser` False (#609: --no-browser) leaves --open out.""" 8255serve = [sys .executable ,str (ROOT / "serve" / "server.py" ),"--engine" ,"strata" ,"--config" ,str (cfg_path ), 8256"--port" ,str (port )]+ (["--open" ]if open_browser else []) 8257if WIN : 8258script = home ()/ f"run- { model . lower () } .bat" 8259script .write_text ("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str (ROOT )+ "\"\r\n" + 8260" " .join (f'" { x } "' for x in serve )+ "\r\nif errorlevel 1 pause\r\n" ,encoding = "utf-8" ) 8261else : 8262script = home ()/ f"run- { model . lower () } .sh" 8263script .write_text ("#!/bin/sh\ncd \"" + str (ROOT )+ "\"\nexec " + " " .join (f'" { x } "' for x in serve )+ "\n" , 8264encoding = "utf-8" ) 8265script .chmod (0o755 ) 8266return script 8267 8268 8269# ------------------------------------------------------------------------------------------------ the rope config 8270def derived_factor (ctx :int ,trained :int = 262144 )-> float : 8271"""The automatic extension factor: the FINAL context over the trained one, at least 1. 8272 8273Factor 1 removes the automatic expansion - the trained angles stand as they are - but it is not a 8274switch for rope as a whole: an explicitly chosen method's settings keep their defined behavior. 8275""" 8276return max (1.0 ,float (ctx )/ float (trained )) 8277 8278 8279def resolve_rope (ctx :int ,scaling ,scale ,trained :int = 262144 ): 8280"""The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. 8281 8282An explicit --rope-scaling/--rope-scale always wins - a valid user-supplied factor is kept verbatim even 8283when a reduction changed the context. Past the trained range an omitted method defaults to yarn - 8284llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the 8285magnitude correction keeps the attention temperature - and an omitted factor is derived from the 8286final context (final / trained, at least 1), as is an explicitly chosen method's missing factor 8287inside the trained range: factor 1, the trained angles, no expansion. An explicit none is refused 8288past the trained range (the setup will not configure a run it knows is out of spec) rather than 8289silently overridden. 8290""" 8291if scale is not None and (not math .isfinite (scale )or scale < 1.0 ): 8292raise ValueError ("--rope-scale must be a finite value >= 1, e.g. --rope-scale 4" ) 8293if ctx <= trained : 8294if scale is not None and scaling in (None ,"none" ): 8295raise ValueError ("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the " 8296"trained 262144, so there is nothing to scale)" ) 8297if scaling in (None ,"none" ): 8298return None ,None # the stock model, by choice or by default 8299return scaling ,scale if scale is not None else derived_factor (ctx ,trained ) 8300if scaling == "none" : 8301raise ValueError (f"a { ctx // 1024 } K context is past the model's trained 262144, and --rope-scaling none " 8302"keeps the stock angles there - the model has never seen those positions, so the setup " 8303"refuses the combination instead of quietly overriding it. Pick --rope-scaling yarn or " 8304"linear, or rerun with --context 262144 or lower" ) 8305return scaling or "yarn" ,scale if scale is not None else derived_factor (ctx ,trained ) 8306 8307 8308# ------------------------------------------------------------------------------------------------ main 8309def mac_setup (argv )-> int : 8310"""A Mac (Apple Silicon): the Metal engine, built from source on the Mac by metal/setup_mac.py (its own steps: 8311the Mac check, the pack by unified memory, the engine build, the Metal defaults). Nothing of the CUDA / HIP paths 8312is used or changed.""" 8313return subprocess .call ([sys .executable ,str (ROOT / "metal" / "setup_mac.py" ),* argv ]) 8314 8315 8316def sycl_setup (argv )-> int : 8317"""--backend sycl: the Intel Arc engine (the SYCL port in sycl/, PR #423), experimental. There is no ready-made 8318Intel engine: it is compiled from source on the PC (docs/INTEL_ARC.md), then sycl/setup_intel.py runs this setup 8319with the Intel steps swapped in. Nothing of the CUDA / HIP paths is used or changed.""" 8320say () 8321say (" Intel Arc (--backend sycl): supported since 0.1.40.2 on Linux, tested on an Arc Pro B70 (xe) and an Arc A750 " 8322"(i915); other Arc cards and driver versions are untested, and reports help (docs/INTEL.md)." ) 8323if WIN : 8324fail ("the Intel Arc engine has no Windows setup yet (no ready-made Intel engine either)" , 8325"run it on Linux (Ubuntu 24.04 with Intel's GPU driver and oneAPI): docs/INTEL_ARC.md" ) 8326say (" There is no ready-made Intel engine: it is built from source with Intel oneAPI (icpx + oneMKL)," ) 8327say (" docs/INTEL_ARC.md. Setup continues with sycl/setup_intel.py." ) 8328rest ,skip = [],False 8329for x in argv :# setup_intel.py drives this setup through its AMD path 8330if skip : 8331skip = False 8332elif x == "--backend" : 8333skip = True 8334elif not x .startswith ("--backend=" ): 8335rest .append (x ) 8336script = ROOT / "sycl" / "setup_intel.py" 8337if not script .exists (): 8338fail (f" { script } is missing" ,"use a full Strata checkout (git clone) - docs/INTEL_ARC.md" ) 8339return subprocess .call ([sys .executable ,str (script ),* rest ]) 8340 8341 8342def intel_control_setup (a )-> int : 8343"""`--backend sycl` in the app's CONTROL mode (tools/strata_mcp.py passes it for an Intel Arc PC): what the Terminal does for an Arc 8344(strata_cli/launch/runner.py adopt_prepared_files): the pack from the model's GGUF files (`--prepare-pack`'s step), then the run config 8345(strata_cli/launch/adopt.py), the engine named as the component. Nothing is downloaded, nothing is compiled; Intel 8346cards do not download models, so the files must be on the computer (--gguf-dir, or <data folder>/models/<tag>). The older `--backend sycl` 8347(a source build with oneAPI, sycl/setup_intel.py) is sycl_setup(), for a checkout; the app's bundle has no sycl/ folder.""" 8348from strata_cli .launch import adopt 8349from strata_control import intel_app 8350say ("Strata on an Intel Arc card (the SYCL engine)" ) 8351step (1 ,"checking this computer" ) 8352if not intel_app .supported_here (): 8353fail ("the Intel Arc engine runs on Linux only" ,"there is no Windows or Mac Intel engine yet" ) 8354family = a .family or "qwen" 8355if family not in FAMILIES or not intel_app .can_set_up (family ,FAMILIES [family ]): 8356fail (f"cannot set up { family } for an Intel Arc card" ,"choose a Qwen3.8-Flash-Next, Swift, Coder, Gyro or Unsloth size" ) 8357fam ,model = FAMILIES [family ],a .model 8358if not model : 8359fail ("an Intel Arc setup needs --model, e.g. --model Q2_0" ) 8360data ,_elsewhere = data_folder_for (a ) 8361tag = fam ["tag" ]+ model 8362if a .gguf_dir : 8363model_dir = Path (a .gguf_dir ) 8364else : 8365model_dir = (Path (a .models_dir )if a .models_dir else data / "models" )/ tag 8366if model_dir .is_file (): 8367model_dir = model_dir .parent 8368shards = intel_app .model_files_in (model_dir ,family ,fam ) 8369if not shards : 8370fail (intel_app .NO_DOWNLOAD ) 8371ok (f"model files: { model_dir } ( { len ( shards ) } file { 's' if len ( shards ) != 1 else '' } )" ) 8372cards = intel_app .arc_cards () 8373vram = max ((float (c .get ("vram_gb" )or 0 )for c in cards ),default = 0.0 ) 8374ok ("graphics card: " + (", " .join (f" { c [ 'name' ] } ( { c [ 'vram_gb' ]:g } GB)" for c in cards )or "an Intel Arc" )) 8375if a .check : 8376return 0 8377SHAPE_ENGINE .clear () 8378if fam .get ("shape" ):# a feed model of its own shape: its own engine component, fetched from the signed feed (strata_control/shape_engine.py) 8379SHAPE_ENGINE ["shape" ],SHAPE_ENGINE ["title" ]= fam ["shape" ],fam .get ("title" ) 8380shape_engine_fetch (a ) 8381step (2 ,"preparing the model for this graphics card" ) 8382pack = data / "packs" / tag .lower () 8383if not ((pack / "experts.bin" ).exists ()or ((pack / "index.txt" ).exists ()and (pack / "tokenizer" / "vocab.json" ).exists ())): 8384a .gguf_dir ,a .prepare_pack = str (model_dir ),str (pack ) 8385rc = prepare_pack_only (a ) 8386if rc : 8387return rc 8388else : 8389ok (f"model already prepared: { pack } " ) 8390step (3 ,"writing the run settings" ) 8391notes :list = [] 8392cfg ,problems = adopt .plan (family = family ,model = model ,model_dir = model_dir ,data_dir = data ,src = ROOT ,context = a .context or 32768 ,kv = a .kv , 8393model_name = f" { fam . get ( 'name' , family ) } - { model . lower () } " ,family_def = fam ,log = home ()/ f"strata- { tag . lower () } .log" , 8394backend = "sycl" ,vram_gb = vram ,notes = notes ,pack_name = tag .lower ()) 8395if cfg is None : 8396fail ("Strata cannot start this model on the Intel Arc card yet: " + "; " .join (problems )) 8397if a .port : 8398cfg ["port" ]= a .port 8399if a .host : 8400cfg ["host" ]= a .host 8401if a .api_key : 8402cfg ["api_key" ]= a .api_key 8403if a .browser is not None : 8404cfg ["open_browser" ]= a .browser 8405cfg_path = home ()/ f"strata- { tag . lower () } .json" 8406write_setup_config (cfg_path ,cfg ) 8407for n in notes : 8408say (" " + n ) 8409ok (f"run settings: { cfg_path . name } " ) 8410say () 8411say ("All set." ) 8412return 0 8413 8414 8415def control_engine_step (gpu ,vision ): 8416"""Step 4 in the app: the engine is the component folder's package (strata_control/engine_component.py), found if it is 8417there and never fetched or built. A model can be downloaded and prepared before the engine is installed; the run config 8418names "component:strata-engine" and the engine is looked up when the model is loaded. llama.cpp's source zip is fetched 8419for gguf-py only (the preparation tools), as setup always did: no git, no compiler.""" 8420from strata_control import engine_component as EC 8421llama = llama_cpp_if_here () 8422try : 8423found = EC .resolve (full = False ) 8424eng ,meta = Path (found .root ), {"version" :found .version ,"backend" :found .backend ,"source" :"local" } 8425ok (f"engine component: { found . version } ( { found . platform } - { found . backend } ) in { eng } " ) 8426if found .backend == "hip" and is_rdna2 (gpu )and any (a in RDNA2_ARCHS for a in found .hip_archs ): 8427for line in rdna2_notes (gpu ):# the RX 6000 package: built, not tested on a real card 8428say (line ) 8429except EC .EngineMissing as e : 8430plain = getattr (e ,"plain_notice" ,None )or getattr (e ,"driver_notice" ,None ) 8431if os .environ .get ("STRATA_NEED_ENGINE" )== "1" and os .environ .get ("STRATA_ALLOW_NO_ENGINE" )!= "1" : 8432# strata launch needs an engine now: stop before step 5 instead of after the download, unless launch itself asked to go on 8433# (STRATA_ALLOW_NO_ENGINE: the person said yes to "download the model anyway"). The app does not stop (owner decision 8434# 2026-10-18): it says so in its download card and still downloads the model. 8435fail (plain or "no engine is installed for this PC" , 8436"get the engine that matches this graphics card (`strata update`, or the app's Settings), then run this again; " 8437"nothing was downloaded and files already downloaded are kept" ) 8438eng = home ()/ "engine" 8439meta = {"version" :"99.0.0" ,"source" :"local" ,"component" :"missing" }# its version is checked when it loads 8440warn (f" { plain + ' ' if plain else '' } no engine is installed for this PC yet ( { e } ). The model is downloaded and prepared now; " 8441"install the engine component for your GPU (the app's Settings, or the Terminal) before loading it" ) 8442if vision != "none" : 8443if (eng / VEXE ).is_file (): 8444ok (f"image encoder: { eng / VEXE } (carried by the engine component)" ) 8445return llama ,eng ,meta , [],gpu ,vision 8446warn ("this engine component has no image encoder (strata-vision): images off for this model" ) 8447return llama ,eng ,meta , [],gpu ,"none" 8448 8449 8450def shape_engine_fetch (a ): 8451"""The engine of the chosen model's shape (SHAPE_ENGINE), fetched through the signed feed (--feed, STRATA_UPDATE_FEED, the remembered feed, or the release's), checked, started 8452once and kept (strata_control/shape_engine.py); the Strata engine is not touched. Returns its component (shape_engine.find), or None when there is none and the person said to 8453go on without it (STRATA_ALLOW_NO_ENGINE: the model is downloaded and prepared, and set up again later); otherwise it stops with the owner's lines.""" 8454from strata_control import engine_component as EC ,shape_engine 8455shape ,title = SHAPE_ENGINE ["shape" ],SHAPE_ENGINE .get ("title" ) 8456name = shape_engine .shown (shape ,title )# what a person reads: the model's title (shape_engine.USE_TITLE) 8457from strata_cli import update_cmd 8458source = update_cmd ._feed_source (argparse .Namespace (feed = getattr (a ,"feed" ,None )),EC .components_dir ()) 8459exe = shape_engine .ensure (shape ,source ,emit = lambda m :say (" " + m ),title = title ) 8460if exe is None : 8461if os .environ .get ("STRATA_ALLOW_NO_ENGINE" )== "1" : 8462warn (shape_engine .WORDS ["setup_skip" ].format (model = name )) 8463return None 8464fail (shape_engine .WORDS ["setup_failed" ].format (model = name ),shape_engine .WORDS ["setup_failed_hint" ]) 8465found = shape_engine .find (shape ,full = False ,title = title ) 8466ok (shape_engine .WORDS ["setup_ok" ].format (model = name ,version = found .version ,folder = found .root )) 8467return found 8468 8469 8470def shape_engine_step (a ,gpu ,vision ): 8471"""Step 4 for a model that runs on the engine of its own shape (a Qwen4 model whose geometry is not Flash-Next's: strata_control/shape_engine.py). That engine is a 8472separate component next to the Strata engine (shape_engine_fetch); the run config names it ("component:strata-q4-lite") and every start looks it up. 8473Returns what engine_step returns.""" 8474shape = SHAPE_ENGINE ["shape" ] 8475llama = llama_cpp_if_here () 8476found = shape_engine_fetch (a ) 8477if found is None : 8478return llama ,home ()/ "engine" , {"version" :"99.0.0" ,"source" :"local" ,"component" :"missing" }, [],gpu ,"none" 8479eng ,meta = Path (found .root ), {"version" :found .version ,"backend" :found .backend ,"source" :"local" ,"shape" :shape } 8480if vision != "none" : 8481if (eng / VEXE ).is_file (): 8482ok (f"image encoder: { eng / VEXE } (carried by the engine component)" ) 8483return llama ,eng ,meta , [],gpu ,vision 8484warn ("this engine component has no image encoder (strata-vision): images off for this model" ) 8485return llama ,eng ,meta , [],gpu ,"none" 8486 8487 8488def engine_step (a ,gpu ,hip ,amd ,cuda_tk ,vision ): 8489"""Step 4: llama.cpp's sources and the engine (ready-made, or compiled here). Returns (llama, engine folder, its 8490BUILD.json, its library folders, the GPU (AMD on Windows: as the engine sees it), the image-encoder choice).""" 8491if SHAPE_ENGINE .get ("shape" ): 8492return shape_engine_step (a ,gpu ,vision ) 8493if CONTROL : 8494return control_engine_step (gpu ,vision ) 8495llama = llama_override () 8496ok (f"llama.cpp { LLAMA_CPP_COMMIT [: 7 ] } (gguf-py, ggml, mtmd)" ) 8497if hip and WIN :# AMD on Windows: the ready-made HIP engine (no compiler) 8498eng = None if a .build else get_prebuilt_hip (a .prebuilt ,gpu ) 8499if eng is None : 8500fail ("no ready-made AMD engine for this Strata version" + (" (--build)" if a .build else "" ), 8501"compiling it on Windows: tools\\hip\\build_windows.bat makes strata-windows-x64-hip.zip, then run " 8502"START-HERE.bat --backend hip --prebuilt <its dist folder> (docs/AMD_HIP.md)" ) 8503gpu = hip_card (eng ,gpu ,amd ) 8504a .gpu = gpu ["index" ]if gpu ["count" ]> 1 else a .gpu 8505else : 8506eng = None if a .build or hip else get_prebuilt (a .prebuilt ,gpu ,vision ,** ({"toolkit" :12 }if cuda_tk == 12 8507else {})) 8508if eng is not None and not hip and json .loads ((eng / "BUILD.json" ).read_text (encoding = "utf-8" )).get ("source" )!= "local" : 8509pip_cuda_libs (cuda_tk ) 8510if vision != "none" and not (eng / VEXE ).exists (): 8511warn ("the ready-made engine has no image encoder: compiling it" ) 8512eng = None 8513else : 8514vision = prebuilt_vision (json .loads ((eng / "BUILD.json" ).read_text (encoding = "utf-8" )),gpu ,vision ) 8515if eng is None : 8516eng = build_engine_hip (gpu ,llama ,vision )if hip else build_engine (gpu ,vision ,a .yes ,llama ,toolkit = cuda_tk ) 8517meta = json .loads ((eng / "BUILD.json" ).read_text (encoding = "utf-8" )) 8518if hip and WIN :# the ready-made engine's rocm/bin, first on the engine's PATH 8519lib_dirs = [str (d )for d in hip_lib_dirs (eng )] 8520else : 8521lib_dirs = meta .get ("lib_dirs" )or meta .get ("cuda_dirs" )or cuda_lib_dirs (cuda_tk ) 8522return llama ,eng ,meta ,lib_dirs ,gpu ,vision 8523 8524 8525def engine_families (eng :Path )-> set : 8526"""The model families an engine runs (`strata --families`; an engine from before it: Flash-Next's only).""" 8527try : 8528text = subprocess .run ([str (eng / EXE ),"--families" ],capture_output = True ,text = True ,errors = "replace" ,timeout = 60 , 8529env = engine_env (eng )).stdout # #2372: with the engine's rocm/bin on PATH 8530except (OSError ,subprocess .SubprocessError ): 8531return {"qwen4exp" } 8532names = set (text .split ()) 8533return names if "qwen4exp" in names else {"qwen4exp" } 8534 8535 8536_FEED_FAMILIES :dict = {} 8537FEED_MODELS = None # the feed's models added to the tables below (id -> FeedModel); None until a feed with a models member was read 8538FEED_UNAVAILABLE :dict = {}# id -> {"title", "by", "family", "reason"}: feed models the installed engine does not run, listed and never offered 8539 8540 8541def feed_engine_families ()-> set | None : 8542"""The model families the installed engine runs (`strata --families`), or None when there is no engine to ask. Asked once for each engine program.""" 8543try : 8544from strata_control import engine_component as EC 8545eng = Path (EC .resolve (full = False ).root ) 8546except Exception :# noqa: BLE001 - no engine installed (yet): setup checks again when it installs 8547return None 8548if not (eng / EXE ).is_file (): 8549return None 8550key = str (eng / EXE ) 8551if key not in _FEED_FAMILIES : 8552_FEED_FAMILIES [key ]= engine_families (eng ) 8553return _FEED_FAMILIES [key ] 8554 8555 8556class _SetupTables : 8557"""This module's tables for strata_control/feed_models.py, which takes `setup` as an argument (this file is also loaded under other names, so no sys.modules lookup).""" 8558def __getattr__ (self ,name ): 8559try : 8560return globals ()[name ] 8561except KeyError : 8562raise AttributeError (name )from None 8563 8564def __setattr__ (self ,name ,value ): 8565globals ()[name ]= value 8566 8567 8568def feed_models_setup (feed :str | None = None ,fetch :bool = True )-> None : 8569"""Add the models of the signed update feed (member `models`; the last verified list when the feed cannot be read) to the tables the menus read. Does 8570nothing, and prints nothing, when the feed has no models. See strata_control/feed_models.py.""" 8571from strata_control import feed_models 8572source = None 8573if fetch and not acquisition .is_forbidden (): 8574try : 8575from strata_cli import update_cmd 8576source = update_cmd ._feed_source (argparse .Namespace (feed = feed ),home ()) 8577except Exception :# noqa: BLE001 - no feed address: the cached list only 8578source = None 8579# the read is optional (the last verified list stays): no failure sentence, but a server that does not answer is named after 5 s (W1) 8580loaded = feed_models .load (source ,fetch = source is not None ,say = lambda line :say (f" { line } ..." )) 8581if loaded .models : 8582feed_models .apply (_SetupTables (),loaded .models ,feed_engine_families ()) 8583 8584 8585def own_path_contexts ()-> list : 8586"""The context sizes the own-path menu offers: up to the model's trained 262,144 (no rope scaling on this path yet).""" 8587return [c for c in CONTEXTS if c <= 262144 ] 8588 8589 8590def own_path_context (fam :dict ,vram_gb :float ,model :str | None = None )-> int : 8591"""The recommended context for an own-path family: 128K (owner, 2026-11-01), or on a card where 128K does not fit the largest 8592size that does (#5715, strata_control/own_path_fit.py; the smallest when none fits). A recommendation only: any size can be chosen.""" 8593from strata_control import own_path_fit 8594return own_path_fit .recommended (own_path_fit .inputs (fam .get ("name" ),model ),vram_gb ,own_path_contexts ()) 8595 8596 8597def own_path_context_warning (fam :dict ,model :str ,vram_gb :float ,ctx :int )-> str | None : 8598"""The sentence said when the chosen context does not fit the card (#5715); None when it fits or cannot be said.""" 8599from strata_control import own_path_fit 8600return own_path_fit .warning (own_path_fit .inputs (fam .get ("name" ),model ),vram_gb ,ctx ,own_path_contexts ()) 8601 8602 8603def own_path_size (fam :dict ,ram :float )-> str : 8604"""The recommended size: the largest file whose RAM need this PC has (the smallest when none fits).""" 8605fits = [m for m ,d in fam ["models" ].items ()if ram >= d ["ram_gb" ]] 8606return max (fits ,key = lambda m :fam ["sha256" ][fam ["file" ].format (q = m )][0 ])if fits else next (iter (fam ["models" ])) 8607 8608 8609def own_path_vision (a ,fam :dict ,gpu :dict ,hip :bool )-> str : 8610"""The image encoder for an own-path family (Qwen3.6-35B-A3B): "gpu", "cpu" or "none". Pictures are on by default (owner rule 86112026-10-18) and the reader follows strata_control/vision_reader.py's one rule on every make of card: the CPU encoder under 24 GB of 8612VRAM (the GPU one takes ~1.4 GB the experts would use), the GPU encoder from 24 GB. --vision yes|no|gpu|cpu, else a question whose 8613default answer is yes; what is asked for with --vision gpu / cpu is kept, with a note (recommend, never force).""" 8614asked = a .vision 8615vram = float (gpu .get ("vram_gb" ,0.0 )) 8616if asked in ("no" ,"none" ): 8617return "none" 8618if asked is None : 8619from strata_control import vision_reader as VR 8620mode = VR .default_mode (vram ) 8621say () 8622say (f" Images: { fam [ 'title' ] } can also read pictures (screenshots, photos, scanned pages). This adds a " 8623f" { fam [ 'sha256' ][ fam [ 'mmproj' ]][ 0 ] / 1e9 :.1f } GB download" + ( 8624" and the image encoder runs on the GPU (about 1-1.4 GB of VRAM kept free, a fraction of a second per picture)." 8625if mode == "gpu" else 8626"; the encoder runs on the CPU (a few seconds per picture), because the GPU encoder would take ~1.4 GB " 8627"of VRAM from the experts on this card (--vision gpu to use it anyway)." )) 8628if ask ("Do you want images?" , ["y" ,"n" ],"y" ,a .yes )!= "y" : 8629return "none" 8630asked = "yes" 8631if hip : 8632return hip_vision (asked ,vram )# settled against the engine's readers in hip_reader() (GPU reader, else CPU) 8633if asked == "yes" : 8634asked = "gpu" if (vram <= 0 or vram >= IMAGES_GPU_ENCODER_MIN_VRAM_GB )else "cpu" 8635if asked == "gpu" and 0 < vram < IMAGES_GPU_ENCODER_MIN_VRAM_GB : 8636warn (f"the GPU image encoder takes ~1.4 GB of VRAM, which on a { vram :.0f } GB card is room the experts would use: " 8637"--vision cpu reads pictures on the CPU instead (a few seconds each); kept as you chose" ) 8638return asked 8639 8640 8641def own_path_parallel_slot_gb (fam :dict ,ctx :int )-> float : 8642"""The VRAM one batch slot's session takes: its KV cache (fp32 K and V of the attention layers and the MTP block) and 8643the recurrent state of the GDN layers.""" 8644return ctx * fam ["kv_bytes_per_token" ]/ 1e9 + fam ["state_gb" ] 8645 8646 8647PARALLEL_SMALL_SHARE = 0.35 # a card that does not hold every expert: the slots' sessions may take this share of the room the 8648# experts would have (VRAM less ~4.5 GB for the dense weights and buffers). Measured (Q4_K_XL): 8649# RTX 3060 12 GB, 8K context, 4 slots (23% of that room): a request alone -4%; A4000 / P100 8650# 16 GB, 32K, 2 slots (27%): -11% / -9%, 4 slots (54%): -27% and no gain together. 8651 8652 8653def own_path_parallel_fits_all (fam :dict ,model :str ,vram_gb :float ,ctx :int ,n :int )-> bool : 8654"""True where every routed expert still sits in VRAM beside n slots' sessions (one more session than the slots: the 8655solo path's own).""" 8656size = fam ["sha256" ][fam ["file" ].format (q = model )][0 ]/ 1e9 8657base = size * 0.93 + 4.5 # the routed experts + the dense weights and buffers (the file's 7% beyond them) 8658return base + (n + 1 )* own_path_parallel_slot_gb (fam ,ctx )<= vram_gb 8659 8660 8661def own_path_parallel_recommend (fam :dict ,model :str ,vram_gb :float ,ctx :int )-> int : 8662"""How many requests at once to recommend: 0 = none (the card cannot hold even two slots). Where every routed expert 8663still fits in VRAM with the slots' sessions, up to 4 (a batch reads each expert once for all its rows). On a card 8664that does not hold every expert even for one session (the hybrid mode already) it is recommended too, as an offer with 8665its price said: measured on 8666an RTX 3060 12 GB, 4 requests together run ~1.5x as fast as one, a request alone ~5% slower, because the slots take 8667VRAM from the expert cache; up to the count whose sessions leave PARALLEL_SMALL_ROOM_GB of the card.""" 8668slot = own_path_parallel_slot_gb (fam ,ctx ) 8669best = max ([n for n in (2 ,3 ,4 )if own_path_parallel_fits_all (fam ,model ,vram_gb ,ctx ,n )],default = 0 ) 8670if best : 8671return best 8672if own_path_parallel_fits_all (fam ,model ,vram_gb ,ctx ,0 ): 8673return 0 # a card that holds every expert for one session only: more sessions would push experts to the CPU 8674# (measured on a 32 GB R9700 at 128K: 4 slots left 15 of 256 experts per layer, decode 81 tok/s 8675# against ~180): not offered there, a number asked for is kept 8676room = max (vram_gb - 4.5 ,0.0 ) 8677return max ([n for n in (2 ,3 ,4 )if n * slot <= PARALLEL_SMALL_SHARE * room ],default = 0 ) 8678 8679 8680def own_path_parallel_note (a_parallel ,fam :dict ,model :str ,vram_gb :float ,ctx :int )-> list : 8681"""What setup says about "parallel" for an own-path family: the recommendation, or how the asked count compares with 8682it (kept as asked: recommend, never force).""" 8683rec = own_path_parallel_recommend (fam ,model ,vram_gb ,ctx ) 8684slot = own_path_parallel_slot_gb (fam ,ctx ) 8685if a_parallel is None or a_parallel <= 1 : 8686if not rec : 8687return ["Several requests at once (opt-in, --parallel N): left at one at a time, because this card cannot spare " 8688f"the room: each session takes ~ { slot :.1f } GB of VRAM at this context, and where the card holds every " 8689"expert only for one session, more would move experts to the CPU and slow every request a lot (a " 8690"smaller context leaves room for more; docs/QWEN36.md)." ] 8691if own_path_parallel_fits_all (fam ,model ,vram_gb ,ctx ,rec ): 8692return [f"Several requests at once (opt-in): --parallel { rec } decodes up to { rec } together instead of one after " 8693f"the other (each takes ~ { slot :.1f } GB of VRAM at this context; docs/BATCHING.md)." ] 8694return [f"Several requests at once (opt-in): --parallel { rec } decodes up to { rec } together, so a second user or agent " 8695"starts at once instead of waiting for the first. The price on this card, which does not hold every expert: " 8696f"each session takes ~ { slot :.1f } GB of VRAM from the expert cache, so a request alone runs about 4-11% " 8697"slower, and next to one-at-a-time WITH the draft layer the requests together are only 1.0-1.15x faster " 8698"(measured, Q4_K_XL: RTX 3060 12 GB at 8K context, 4 requests: 1.15x, alone -4%; A4000 / P100 16 GB at " 8699"32K, 2 requests: 1.0x, alone -7 to -11%). Worth it for several users at once, not for one chat " 8700"(docs/QWEN36.md)." ] 8701lines = [f"parallel requests: { a_parallel } at once (each takes ~ { slot :.1f } GB of VRAM at this context, " 8702f" { a_parallel * slot :.1f } GB in all)" ] 8703if a_parallel > PARALLEL_MAX : 8704lines .append (f"the engine runs at most { PARALLEL_MAX } at once; it will use { PARALLEL_MAX } " ) 8705if not rec : 8706lines .append ("recommended for this card: one at a time - there is no room for more sessions; kept as you chose" ) 8707elif a_parallel > rec : 8708lines .append (f"recommended for this card: { rec } - more slots leave fewer experts in VRAM, which can make every " 8709"request slower; kept as you chose" ) 8710return lines 8711 8712 8713def install_own_path (a ,family ,gpu ,hip ,amd ,cuda_tk ,multi ,port ,ram ,adopted ): 8714"""Steps 2-7 for a family with its own engine path (OWN_PATH_FAMILIES: Qwen3.6-35B-A3B): the size, the context, the 8715engine, the GGUF (pinned revision, size and SHA-256), the tokenizer from the GGUF, the config and the start 8716script. The engine places the experts itself (every one in VRAM when they fit, else the most-used ones there and 8717the rest on the CPU), so there is no pack, profile or RAM budget to choose.""" 8718fam = OWN_PATH_FAMILIES [family ] 8719say () 8720say (f" { fam [ 'title' ] } - { fam [ 'by' ] } : { fam [ 'about' ] } " ) 8721ok (f"model: { fam [ 'title' ] } " ) 8722if fam .get ("license" ): 8723say (f" Its license: { fam [ 'license' ] } " ) 8724if multi : 8725warn (f" { fam [ 'title' ] } runs on one GPU so far: using GPU { gpu . get ( 'index' , 0 ) } ( { gpu_name ( gpu ) } ) only" ) 8726names = list (fam ["models" ]) 8727if a .model and a .model not in names : 8728fail (f" { fam [ 'title' ] } has no { a . model } model file" ,"choose one of: " + ", " .join (names )) 8729say () 8730for i ,m in enumerate (names ,1 ): 8731d = fam ["models" ][m ] 8732size = fam ["sha256" ][fam ["file" ].format (q = m )][0 ] 8733from strata_control import fit_label 8734fit = f" <- { fit_label . label ( size / 1e9 , ram , low_ram_vram ( gpu )) } " # the file against the RAM and the card's memory together 8735say (f" { i } ) { m :10s } { d [ 'about' ] } ; download { size / 1e9 :.1f } GB { fit } " ) 8736rec = own_path_size (fam ,ram ) 8737if not a .model : 8738say (f" Recommended for { ram :.0f } GB of RAM: { rec } (the largest that fits; any size can be chosen)" ) 8739model = a .model or names [int (ask ("Which size?" , [str (i )for i in range (1 ,len (names )+ 1 )], 8740str (names .index (rec )+ 1 ),a .yes ))- 1 ] 8741if ram < fam ["models" ][model ]["ram_gb" ]: 8742confirm_risk (f" { model } needs about { fam [ 'models' ][ model ][ 'ram_gb' ] } GB of RAM; this PC has { ram :.0f } GB: the " 8743"OS may page and it may not start" ,bool (a .model ),a .yes , 8744f" { model } needs about { fam [ 'models' ][ model ][ 'ram_gb' ] } GB of RAM" , 8745f"choose a smaller size, or --model { model } --yes to install it anyway" ," Install it anyway?" ) 8746warn (f"installing { model } with { ram :.0f } GB of RAM, as you chose" ) 8747ok (f"size: { model } " ) 8748tag = fam ["tag" ]+ model 8749rec_ctx = own_path_context (fam ,gpu .get ("vram_gb" ,0.0 ),model ) 8750if a .context : 8751ctx = a .context 8752else : 8753ctxs = own_path_contexts ()# the model's trained length; no rope scaling on this path yet 8754say () 8755say (" Context length = how much text the model can see at once. Its cache takes " 8756f" { fam [ 'kv_bytes_per_token' ] * 32768 / 2 ** 30 :.1f } GB of VRAM per 32K tokens, room the experts would use:" ) 8757for i ,c in enumerate (ctxs ,1 ): 8758say (f" { i } ) { c // 1024 } K tokens" + (" (recommended for your GPU)" if c == rec_ctx else "" )) 8759ctx = ctxs [int (ask ("Context?" , [str (i )for i in range (1 ,len (ctxs )+ 1 )],str (ctxs .index (rec_ctx )+ 1 ), 8760a .yes ))- 1 ] 8761if ctx > 262144 : 8762warn (f" { ctx // 1024 } K is past { fam [ 'title' ] } 's trained 262,144 positions and this engine path has no rope " 8763"scaling yet: kept as you chose, but answers past 256K are untested" ) 8764too_big = own_path_context_warning (fam ,model ,float (gpu .get ("vram_gb" ,0.0 )),ctx ) 8765if too_big :# #5715: said before the start; the choice is kept (recommend, never force) 8766warn (too_big ) 8767ok (f"context: { ctx } tokens" ) 8768vision = own_path_vision (a ,fam ,gpu ,hip ) 8769ok ("images: " + {"none" :"off" ,"gpu" :"on" ,"cpu" :"on (encoder on the CPU)" }[vision ]) 8770vram_gb = float (gpu .get ("vram_gb" ,0.0 )) 8771par = getattr (a ,"parallel" ,None ) 8772par_said = False 8773if par is None and not a .yes :# offered, with its price; Enter keeps one at a time (never forced) 8774say () 8775for line in own_path_parallel_note (None ,fam ,model ,vram_gb ,ctx ): 8776say (" " + line ) 8777par_said = True 8778if own_path_parallel_recommend (fam ,model ,vram_gb ,ctx ): 8779n = int (ask ("How many requests at once (1 = one at a time)?" , [str (i )for i in range (1 ,PARALLEL_MAX + 1 )], 8780"1" ,a .yes )) 8781par = n if n > 1 else None 8782if a .rope_scaling or a .rope_scale or a .kv or a .resident_budget_gib is not None or a .low_ram not in (None ,"auto" ): 8783warn (f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: { fam [ 'title' ] } " 8784"does not use them" ) 8785folder = Path (a .gguf_dir )if a .gguf_dir else Path (a .models_dir )/ tag 8786gguf = folder / fam ["file" ].format (q = model ) 8787size = fam ["sha256" ][gguf .name ][0 ] 8788part = gguf .with_name (gguf .name + ".part" ) 8789def have (p :Path )-> bool :# --gguf-dir: the person's own file has no finish mark; verify_sha256 checks and writes it 8790return p .exists ()and (done (p )or bool (a .gguf_dir )) 8791left = 0 if have (gguf )else (size - (part .stat ().st_size if part .is_file ()else 0 ))/ 1e9 8792if left and free_gb (folder )< left : 8793fail (f"not enough free disk space in { folder } : need ~ { left :.0f } GB, { free_gb ( folder ):.0f } GB free" , ("use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL else "use --models-dir on a bigger drive" )) 8794if left and free_gb (folder )< left + 1 : 8795warn (f"little free disk space in { folder } : { free_gb ( folder ):.1f } GB free for about { left :.1f } GB. Setup goes on and should fit" ) 8796 8797step (3 ,"Python packages" ) 8798pip_install (runtime_packages (), 8799"numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil, textual (the screens)" ) 8800 8801step (4 ,"the Strata engine" ) 8802llama ,eng ,meta ,lib_dirs ,gpu ,vision = engine_step (a ,gpu ,hip ,amd ,cuda_tk ,vision ) 8803reader = None 8804if hip and vision != "none" : 8805vision ,reader = hip_reader (eng ,vision ,gpu ) 8806elif vision != "none" and not (eng / VEXE ).exists (): 8807warn ("this engine has no image encoder: images off (run setup again with --build to compile it)" ) 8808vision = "none" 8809if CONTROL and meta .get ("component" )== "missing" : 8810pass # the app: no engine yet (control_engine_step said so); the run config names the component, 8811# and the engine's families are checked when the model loads 8812elif fam ["arch" ]not in engine_families (eng ): 8813if fam .get ("feed" )and FEED_UNAVAILABLE .get (family , {}).get ("allowed" ):# the owner's rule for a feed model (feed_models.UNAVAILABLE_POLICY): warn, go on 8814warn (f" { fam [ 'title' ] } is { FEED_UNAVAILABLE [ family ][ 'reason' ] } " ) 8815else : 8816fail (f"this engine ( { meta . get ( 'version' ) } ) does not run { fam [ 'title' ] } yet" , 8817"update Strata, or compile the engine with --build, and run setup again" ) 8818ok ("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: { eng / EXE } " ) 8819 8820step (5 ,f"downloading { fam [ 'title' ] } { model } " ) 8821if have (gguf ): 8822ok (f" { gguf . name } already downloaded" ) 8823else : 8824if a .gguf_dir : 8825fail (f" { gguf } is missing" ,f"put { gguf . name } in { folder } , or drop --gguf-dir to download it" ) 8826download (fam ["hf" ]+ gguf .name ,gguf ) 8827verify_sha256 (gguf ,* fam ["sha256" ][gguf .name ],own = bool (a .gguf_dir )) 8828ok (f"model file: { gguf } " ) 8829mmproj = folder / fam ["mmproj" ] 8830if vision != "none" :# the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked 8831if not a .gguf_dir and not have (mmproj )and not mmproj .with_name (mmproj .name + ".part" ).exists (): 8832# another size of this model has it already (the same file, kept beside each size): linked here, not fetched again 8833if share_sibling_file (mmproj ,Path (a .models_dir ),mmproj .name ,fam ["sha256" ][mmproj .name ][0 ]): 8834say (f" { mmproj . name } : the copy of another { fam [ 'title' ] } size is used (no download)" ) 8835if have (mmproj ): 8836ok (f" { mmproj . name } already downloaded" ) 8837else : 8838if a .gguf_dir : 8839fail (f" { mmproj } is missing" ,f"put { mmproj . name } in { folder } , or drop --gguf-dir to download it" ) 8840download (fam ["mmproj_hf" ]+ mmproj .name ,mmproj ,"vision encoder" ) 8841verify_sha256 (mmproj ,* fam ["sha256" ][mmproj .name ],own = bool (a .gguf_dir )) 8842ok (f"vision encoder: { mmproj } " ) 8843 8844step (6 ,"preparing the model for Strata" ) 8845data ,_ = data_folder_for (a ) 8846pack = data / "packs" / tag .lower ()# only the tokenizer: the engine reads the GGUF itself 8847if not (pack / "tokenizer" / "vocab.json" ).exists (): 8848run ([sys .executable ,str (ROOT / "tools" / "strata_tokenizer.py" ),"--gguf" ,str (gguf ),"--out" ,str (pack )], 8849env = dict (os .environ ,** gguf_py_env ())) 8850ok (f"tokenizer: { pack / 'tokenizer' } " ) 8851 8852step (7 ,"writing the start script" ) 8853args = ["--native" ,str (gguf ),"--max-context" ,str (ctx ),"--prefill" ,"auto" ,"--mtp" ,str (fam ["mtp" ])] 8854if a .vram_reserve_mib is not None :# VRAM left free for other programs: the experts take that much less 8855vram = gpu .get ("vram_gb" ,0.0 ) 8856if vram > 0 : 8857args += ["--expert-vram" ,f" { max ( vram - 3.0 - a . vram_reserve_mib / 1024 , 0 ):.1f } " ] 8858ok (f"VRAM kept free for other programs: about { a . vram_reserve_mib } MiB (the experts' share is set lower)" ) 8859cfg = {"exe" :engine_exe (eng ),"args" :args ,"cwd" :str (ROOT ),"tokenizer" :str (pack / "tokenizer" ), 8860"model_name" :f" { fam [ 'name' ] } - { model . lower () } " ,"arch" :fam ["arch" ], 8861"log" :str (home ()/ f"strata- { tag . lower () } .log" ),"lib_dirs" :lib_dirs ,"port" :port } 8862if cuda_tk == 12 : 8863cfg ["cuda" ]= 12 8864if hip : 8865cfg ["backend" ]= "hip" 8866if gpu .get ("count" ,1 )> 1 or a .gpu is not None : 8867cfg ["gpu" ]= gpu ["index" ] 8868cfg ["gpus_asked" ]= True 8869if a .host : 8870cfg ["host" ]= a .host 8871if a .api_key : 8872cfg ["api_key" ]= a .api_key 8873if a .browser is not None : 8874cfg ["open_browser" ]= a .browser 8875cfg ["args" ]= recommend_pool_workers (cfg ["args" ])# --pool-workers: this engine path's CPU expert threads too 8876for line in pool_workers_note (cfg ["args" ]): 8877warn (line ) 8878cfg_path = home ()/ f"strata- { tag . lower () } .json" 8879if vision != "none" : 8880old_cfg = cfg_path if cfg_path .is_file ()else adopted 8881vt = vision_tokens (getattr (a ,"vision_tokens" ,None ),vision ,old_cfg ) 8882cfg ["args" ].append ("--vision" ) 8883cfg ["vision" ]= {"exe" :str (eng / VEXE ),"mmproj" :str (mmproj ),"model" :str (gguf ),"gpu" :vision == "gpu" , 8884"max_tokens" :vt }# the text model, opened vocab-only 8885if reader is not None :# AMD: the HIP reader with the CPU reader behind it, or the CPU reader 8886from strata_control import vision_reader as VR 8887cfg ["vision" ]= VR .vision_section (reader ,cfg ["vision" ]) 8888if vision == "cpu" : 8889cfg ["vision" ]["threads" ]= vision_threads () 8890elif getattr (a ,"vision_tokens" ,None )is not None : 8891warn ("--vision-tokens: images are off, so it is not used" ) 8892# requests at once ("parallel", opt-in): written only when given; the recommendation is said once 8893if par is not None : 8894if par >= 2 : 8895cfg ["parallel" ]= par 8896for i ,line in enumerate (own_path_parallel_note (par ,fam ,model ,vram_gb ,ctx )): 8897 (ok if i == 0 else warn )(line ) 8898else : 8899cfg ["parallel" ]= 1 8900ok ("parallel requests: one at a time (--parallel 1)" ) 8901write_setup_config (cfg_path ,cfg ,adopted if adopted is not None and adopted .name == cfg_path .name else None ,explicit_args (a )) 8902script = write_run_script (tag ,cfg_path ,port ,cfg .get ("open_browser" )is not False ) 8903ok (f"start script: { script . name } " ) 8904say () 8905say ("All set." ) 8906say (f" API (OpenAI): http://127.0.0.1: { port } /v1 (any API key; model name: anything)" ) 8907say (f" API (Anthropic): http://127.0.0.1: { port } /v1/messages" ) 8908say (f" Next time: just run { 'START-HERE.bat' if WIN else './setup.sh' } (or { script . name } ) - it starts right away" ) 8909if vision != "none" : 8910say (" Images: send them in the chat page, in chat.py (/image <path>) or over the API" ) 8911if par is None and not par_said :# the opt-in, said once (nothing changes) 8912for line in own_path_parallel_note (None ,fam ,model ,vram_gb ,ctx ): 8913say (" " + line ) 8914if a .no_start : 8915return 0 8916return start (cfg_path ,port ) 8917 8918 8919def preview_family (a )-> int : 8920"""--family qwen36: a family setup knows but the engine does not run yet (PREVIEW_FAMILIES). Downloads the chosen 8921size (pinned revision, size and SHA-256 checked) and, with --vision, the image encoder - and says plainly that 8922Strata cannot start it yet. Nothing is configured: no engine, no pack, no start script.""" 8923fam = PREVIEW_FAMILIES [a .family ] 8924names = list (fam ["models" ]) 8925say () 8926say (f" { fam [ 'title' ] } - { fam [ 'by' ] } : { fam [ 'about' ] } " ) 8927warn (f"this Strata version does not run { fam [ 'title' ] } yet (support is in development): setup downloads its " 8928"files, and the engine refuses them with a message until a version that runs it" ) 8929if a .model and a .model not in names : 8930fail (f" { fam [ 'title' ] } has no { a . model } model file" ,"choose one of: " + ", " .join (names )) 8931ram = ram_gb () 8932for i ,m in enumerate (names ,1 ): 8933d = fam ["models" ][m ] 8934size = fam ["sha256" ][fam ["file" ].format (q = m )][0 ] 8935fit = "" if ram >= d ["ram_gb" ]else f" <- needs { d [ 'ram_gb' ] } GB RAM, you have { ram :.0f } " 8936say (f" { i } ) { m :10s } { d [ 'about' ] } ; download { size / 1e9 :.1f } GB { fit } " ) 8937if a .check : 8938return 0 8939model = a .model or names [int (ask ("Which size?" , [str (i )for i in range (1 ,len (names )+ 1 )],"1" ,a .yes ))- 1 ] 8940say (f" Its license: { fam [ 'license' ] } " ) 8941want = [fam ["file" ].format (q = model )] 8942if a .vision in ("yes" ,"gpu" ,"cpu" ): 8943want .append (fam ["mmproj" ]) 8944folder = Path (a .models_dir )/ (fam ["tag" ]+ model ) 8945files = [folder / w for w in want ] 8946left = sum (fam ["sha256" ][f .name ][0 ]- (f .with_name (f .name + ".part" ).stat ().st_size 8947if f .with_name (f .name + ".part" ).is_file ()else 0 ) 8948for f in files if not (f .exists ()and done (f )))/ 1e9 8949if left and free_gb (folder )< left : 8950fail (f"not enough free disk space in { folder } : need ~ { left :.0f } GB, { free_gb ( folder ):.0f } GB free" , ("use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL else "use --models-dir on a bigger drive" )) 8951if left and free_gb (folder )< left + 1 : 8952warn (f"little free disk space in { folder } : { free_gb ( folder ):.1f } GB free for about { left :.1f } GB. Setup goes on and should fit" ) 8953step (5 ,f"downloading { fam [ 'title' ] } { model } " ) 8954for f in files : 8955url = (fam ["mmproj_hf" ]if f .name == fam ["mmproj" ]else fam ["hf" ])+ f .name 8956download (url ,f ,"vision encoder" if f .name == fam ["mmproj" ]else None ) 8957verify_sha256 (f ,* fam ["sha256" ][f .name ]) 8958ok (f" { fam [ 'title' ] } { model } : { folder } " ) 8959say () 8960say (f" { fam [ 'title' ] } is downloaded, but this Strata version cannot run it yet (its engine path is in " 8961"development); nothing was configured. Run setup again without --family qwen36 to install a model it runs." ) 8962return 0 8963 8964 8965def mac_vision (asked ,model :str ,ram :float )-> str : 8966"""The picture setting of a Mac's setup: "gpu", "cpu" or "none". Pictures are on wherever the model can read them (owner rule 89672026-10-18) and the reader follows strata_control/vision_reader.py: on a Mac, the GPU (Metal) reader, because the memory is shared 8968(no card to keep free) and the CPU reader is ~100x slower. --vision cpu is kept, with a note (recommend, never force).""" 8969from strata_control import vision_reader as VR 8970if asked in ("no" ,"none" ,"off" ): 8971return "none" 8972if asked is None and not images_default (model ,"qwen" ,ram ): 8973return "none" 8974if MODELS .get (model , {}).get ("vision" )is False : 8975if asked is not None : 8976warn (f"images are not available with { model } yet: off" ) 8977return "none" 8978mode = VR .wanted (asked ,None ,unified = True ) 8979if mode == "cpu" : 8980warn (VR .MAC_CPU_NOTE ) 8981return mode 8982 8983 8984def mac_reader (eng :Path ,vision :str ): 8985"""The picture reader the Mac engine folder carries (strata-vision: Metal built in), for `vision` "gpu" or "cpu". A folder 8986without it gets pictures off, said once.""" 8987from strata_control import vision_reader as VR 8988r = VR .choose (eng ,vision ,windows = False ,mac = True ) 8989if r .mode == "none" : 8990warn (r .note or "this engine has no picture reader: pictures off" ) 8991return r 8992 8993 8994def prepare_pack_only (a )-> int : 8995"""setup.py --prepare-pack PACK_DIR --gguf-dir DIR --family F --model M: the pack (index, dense weights, tokenizer) of a model whose GGUF files 8996are in DIR, for a card the built-in downloader does not set up (Intel Arc). llama.cpp's gguf-py is fetched when it is not here (the one 8997download); the model's files are never downloaded or changed.""" 8998if not a .gguf_dir : 8999fail ("--prepare-pack needs --gguf-dir, the folder with the model's .gguf files" ) 9000family = a .family or "qwen" 9001if family not in FAMILIES : 9002fail (f"cannot prepare a pack for the family { family } " ,"choose qwen, swift, coder or gyro" ) 9003fam ,model = FAMILIES [family ],a .model 9004if not model : 9005fail ("--prepare-pack needs --model, e.g. --model IQ3_XXS" ) 9006models_dir = Path (a .gguf_dir ) 9007files = gguf_dir_shards (models_dir ,fam ,model ) 9008problem = gguf_dir_problem (models_dir ,files [0 ],fam ,model ) 9009if problem : 9010fail (* problem ) 9011pack = Path (a .prepare_pack ) 9012step (1 ,"preparing the model for this graphics card" ) 9013llama = llama_override () 9014ok (f"llama.cpp { LLAMA_CPP_COMMIT [: 7 ] } (gguf-py)" ) 9015env = dict (os .environ ,** gguf_py_env ()) 9016if not (pack / "native_experts.txt" ).exists ()or not (pack / "tokenizer" / "vocab.json" ).exists (): 9017run ([sys .executable ,str (ROOT / "tools" / "iq_pack.py" ),"--gguf" ,str (files [0 ]),"--out" ,str (pack ), 9018* fam .get ("pack_args" , [])],env = env ) 9019if not (pack / "tokenizer" / "vocab.json" ).exists (): 9020fail ("the pack was built but has no tokenizer" ,"run it again; if it repeats, the model files may be damaged" ) 9021ok (f"model prepared: { pack } " ) 9022return 0 9023 9024 9025MAC_PREPARE_LOCK = ".preparing.lock" # beside the repacked file, holds setup's pid from the repack to the end of the pack (metal/setup_mac.py PREPARE_LOCK) 9026MAC_EXPERTS_MARGIN_GB = 10.0 # what stays free on the disk after the experts' streaming copy (metal/setup_mac.py EXPERTS_MARGIN_GB) 9027 9028 9029def mac_tools_dir ()-> Path : 9030"""metal/tools: metal_repack.py (many Unsloth shards -> one GGUF for the GPU) and stream_experts.py; both ship in the installer's bundle.""" 9031return Path (ROOT ,"metal" ,"tools" ) 9032 9033 9034def mac_ple_shard (files :list )-> Path : 9035"""The shard that holds the n-gram table (per_layer_token_embd): the repacked file leaves it out and the engine reads it from there (--ple-gguf).""" 9036sys .path .insert (0 ,str (mac_tools_dir ())) 9037import metal_repack as R 9038for f in files : 9039rd = R .Reader (f ) 9040rd .f .close () 9041if any (t ["name" ]== R .PLE for t in rd .tensors ): 9042return f 9043fail (f"no shard of { files [ 0 ]. name } holds the n-gram table (per_layer_token_embd)" ) 9044 9045 9046def mac_engine_pids ()-> list [int ]: 9047"""Pids of this user's running Metal engines (`strata`): a repack beside an engine of 70-90 GB froze the 128 GB M5 Max twice.""" 9048cmd = ["pgrep" ,"-x" ,"strata" ] 9049if hasattr (os ,"getuid" ): 9050cmd [1 :1 ]= ["-u" ,str (os .getuid ())] 9051try : 9052out = subprocess .run (cmd ,capture_output = True ,text = True ,timeout = 10 ).stdout 9053except (OSError ,subprocess .SubprocessError ): 9054return [] 9055return [int (x )for x in out .split ()if x .isdigit ()and int (x )!= os .getpid ()] 9056 9057 9058def mac_experts_file (native :Path )-> None : 9059"""A streaming Mac: <model>.experts beside the GPU's GGUF (metal/tools/stream_experts.py), written only when the disk has room (metal/setup_mac.py experts_file).""" 9060from strata_control import mac_fit as MF 9061out = native .with_name (native .name + ".experts" ) 9062if out .exists ()and done (out ): 9063ok (f"the experts' streaming copy: { out . name } " ) 9064return 9065sys .path .insert (0 ,str (mac_tools_dir ())) 9066import stream_experts as X 9067need = X .size_bytes (native )/ 1e9 9068free = free_gb (native .parent ) 9069if not os .access (native .parent ,os .W_OK ): 9070warn (f" { native . parent } cannot be written: the experts' streaming copy ( { need :.0f } GB) is not written; the " 9071f"engine streams from the model file ( { MF . STREAM_COPY_GAIN } slower)" ) 9072return 9073if free < need + MAC_EXPERTS_MARGIN_GB : 9074warn (f"the experts' streaming copy needs { need :.0f } GB and { MAC_EXPERTS_MARGIN_GB :.0f } GB to spare on the disk " 9075f"( { free :.0f } GB free): not written; the engine streams from the model file ( { MF . STREAM_COPY_GAIN } " 9076f"slower). Free some space and run ./setup.sh --setup again to add it" ) 9077return 9078say (f" Writing the experts in SSD-read order (one time, { need :.0f } GB; each expert is read with one request) ..." ) 9079run ([sys .executable ,str (mac_tools_dir ()/ "stream_experts.py" ),"--gguf" ,str (native ),"--verify" ]) 9080mark (out ) 9081ok (f"the experts' streaming copy: { out . name } " ) 9082 9083 9084def mac_prepare_lock (native :Path )-> Path : 9085"""Take the prepare lock beside the repacked file (it holds our pid from the repack to the end of the pack: metal/setup_mac.py's start() and the engine look at it), 9086and never beside a running engine: an engine of 70-90 GB beside a repack froze the 128 GB M5 Max twice. The caller removes the lock.""" 9087running = mac_engine_pids () 9088if running : 9089fail (f"a Strata engine is running (pid { running [ 0 ] } ): preparing a model beside it can freeze this Mac" , 9090"stop the model in Strata (unload it), then install again" ) 9091native .parent .mkdir (parents = True ,exist_ok = True ) 9092lock = native .parent / MAC_PREPARE_LOCK 9093lock .write_text (str (os .getpid ())) 9094return lock 9095 9096 9097def mac_repack (files :list ,model :str ,native :Path )-> None : 9098"""Unsloth's many-shard set as ONE GGUF for the GPU (metal/tools/metal_repack.py --verify: every tensor hashed against its shard; the n-gram table stays 9099in its shard); the same step as metal/setup_mac.py.""" 9100from strata_control import mac_fit as MF 9101say (f" Writing the model's experts and weights into one file for the GPU (one time, " 9102f" { MF . MAC_MODELS [ model ][ 'shard1_gb' ]:.0f } GB) ..." ) 9103run ([sys .executable ,str (mac_tools_dir ()/ "metal_repack.py" ),"--shard1" ,str (files [0 ]),"--out" ,str (native ),"--verify" ]) 9104mark (native ) 9105 9106 9107def mac_control_setup (a )-> int : 9108"""The app (and the Terminal's `strata launch`) on a Mac, STRATA_CONTROL_INSTALL=1: the same job as on Windows and Linux. It 9109downloads and prepares the model files and writes a run config whose engine is "component:strata-engine"; it builds nothing 9110(the Metal engine is a component: a ready-made package from the feed, or the one inside the installer) and runs no 9111metal/setup_mac.py. Which sizes a Mac can run, whether one stays in memory or streams its experts from the SSD, and the 9112Metal flags of the config are strata_control/mac_fit.py's, the module setup_mac.py and the model list use too.""" 9113from strata_control import mac_fit as MF 9114say ("Strata on a Mac (Apple Silicon, Metal)" ) 9115step (1 ,"checking your Mac" ) 9116info = MF .mac_info () 9117ram = float (info ["ram_gb" ]or ram_gb ()) 9118ok (f" { info [ 'chip' ] } , { ram :.0f } GB unified memory, macOS { info [ 'macos' ] or '?' } " ) 9119if info .get ("rosetta_python" ): 9120say (" (the Python that runs this is an Intel build running through Rosetta: Strata works, and the Apple Silicon Python " 9121"from python.org or Homebrew in /opt/homebrew is a little faster to start)" ) 9122problems = MF .mac_problems (info ,need_compiler = False )# the app compiles nothing: no Command Line Tools needed 9123for p in problems : 9124warn (p ) 9125data ,elsewhere = data_folder_for (a ) 9126roots = [data ,* elsewhere ] 9127models_root = Path (a .models_dir )if a .models_dir else data / "models" 9128free = free_gb (data if data .exists ()else home ()) 9129ok (f"free disk: { free :.0f } GB at { data } " ) 9130if a .check : 9131return 1 if problems else 0 9132if problems : 9133fail (problems [0 ]) 9134 9135step (2 ,"your choices" ) 9136app_sizes = [m for f in MF .all_families ()for m in MF .app_sizes (f )]# Gyro: one file, no repack; Unsloth's sets: the repack below (round 0214) 9137if a .family not in (None ,* MF .all_families ()): 9138fail (f"the app on a Mac runs the Qwen3.8-Flash-Next sizes ( { ', ' . join ( app_sizes ) } ); { a . family } is not one of them" , 9139"choose Qwen3.8-Flash-Next" ) 9140rec ,notes = MF .recommend_model (ram ) 9141if rec not in app_sizes : 9142rec = "Q2_0" 9143model = a .model or rec 9144if model not in app_sizes : 9145fail (f" { model } is not offered on a Mac in the app" ,"choose one of: " + ", " .join (app_sizes )) 9146for n in MF .model_note (model ,ram ): 9147warn (n ) 9148vision = mac_vision (a .vision ,model ,ram ) 9149ctx = a .context or MF .recommend_context (ram ) 9150if ctx > MF .TESTED_CONTEXT : 9151say (f" context { ctx } : measured on the Mac up to { MF . TESTED_CONTEXT } (needles found at 8K-32K); longer is kept" ) 9152ok (f" { model } , context { ctx } " ) 9153family = MF .MAC_MODELS [model ].get ("family" ,"qwen" ) 9154fam = FAMILIES [family ] 9155SHAPE_ENGINE .clear () 9156if fam .get ("shape" ):# a feed model of its own shape: its own Metal engine component (strata_control/shape_engine.py) 9157SHAPE_ENGINE ["shape" ],SHAPE_ENGINE ["title" ]= fam ["shape" ],fam .get ("title" ) 9158tag = fam ["tag" ]+ model 9159stream = MF .streams (model ,ram ) 9160 9161step (4 ,"the Strata engine (Metal)" ) 9162from strata_control import engine_component as EC 9163llama = llama_cpp_if_here ()# gguf-py for the preparation tools only (fetched when one runs): no git, no compiler 9164ok (f"llama.cpp { LLAMA_CPP_COMMIT [: 7 ] } (gguf-py for the preparation tools)" ) 9165reader = None 9166try : 9167if SHAPE_ENGINE .get ("shape" ): 9168found = shape_engine_fetch (a ) 9169if found is None : 9170raise EC .EngineMissing ("no engine for the model's shape" ,None ) 9171else : 9172found = EC .resolve (full = False ) 9173ok (f"engine component: { found . version } ( { found . platform } - { found . backend } )" ) 9174if vision != "none" : 9175reader = mac_reader (Path (found .root ),vision ) 9176vision = reader .mode 9177except EC .EngineMissing as e : 9178warn (f"no Metal engine is installed for this Mac yet ( { e } ). The model is downloaded and prepared now; the engine comes " 9179"with the app or its update feed, and is looked up when the model loads" ) 9180if vision != "none" : 9181warn ("pictures are off for now: the picture reader comes with the engine (run setup again once it is installed)" ) 9182vision = "none" 9183else : 9184if family == "gyro" :# an engine from before the trellis kernels refuses the file when it loads 9185try : 9186has_tq = b"inputs are rotated on the GPU" in Path (found .exe ).read_bytes () 9187except (OSError ,AttributeError ): 9188has_tq = True # cannot tell: not a reason to hold the install back 9189if not has_tq : 9190warn (f"the Metal engine component { found . version } has no kernels for Gyro's trellis experts yet: the model is " 9191"downloaded and prepared, and it runs once the app or its update feed brings a newer engine" ) 9192ok ("engine: the engine component (looked up when the model loads)" ) 9193ok ("images: " + {"none" :"off" ,"gpu" :"on (read on the Mac's GPU)" ,"cpu" :"on (read on the CPU)" }[vision ]) 9194 9195step (5 ,f"downloading { fam [ 'title' ] } { model } " ) 9196models_dir = Path (a .gguf_dir )if a .gguf_dir else models_root / tag 9197files = gguf_dir_shards (models_dir ,fam ,model )if a .gguf_dir else \ 9198 [models_dir / model_file (fam ,model ,i )for i in range (1 ,model_shards (fam ,model )+ 1 )] 9199problem = gguf_dir_problem (models_dir ,files [0 ],fam ,model )if a .gguf_dir else None 9200if problem :# files Strata cannot run, or another choice's files 9201fail (* problem ) 9202mark_whole_unless_pinned (files ,model_hf (fam ,model )if fam .get ("hf" )else None ,bool (a .gguf_dir ))# a whole file copied in by hand has no finish mark 9203repacked = family == "unsloth" and len (files )> 2 # Unsloth's many-shard set: one GGUF for the GPU (mac_repack), the n-gram table left in its shard 9204native = data / "metal" / f" { tag . lower () } -metal.gguf" 9205need = MF .install_disk_gb (model ,0 if a .gguf_dir or all (s .exists ()and done (s )for s in files )else MODELS [model ]["download_gb" ]) \ 9206- (MF .repacked_gb (model )if native .exists ()and done (native )else 0.0 ) 9207if free_gb (models_dir if models_dir .exists ()else data )< need : 9208warn (f"about { need :.0f } GB are needed on the disk: kept as you chose; it may run out" ) 9209if not a .gguf_dir : 9210models_dir .mkdir (parents = True ,exist_ok = True ) 9211missing = [s .name for s in files if not (s .exists ()and done (s ))] 9212if missing : 9213say (f" The model files go in { models_dir } " ) 9214for s in files : 9215if s .exists ()and done (s ): 9216ok (f" { s . name } already downloaded" ) 9217continue 9218download (model_hf (fam ,model )+ s .name ,s ) 9219check_shards (files ) 9220ok ("model files present" ) 9221mmproj = None 9222if vision != "none" : 9223mmproj = Path (models_root )/ fam ["mmproj" ] 9224if not mmproj .exists ():# an earlier install's copy (the same file for every family) 9225mmproj = find_in (roots ,f"models/ { fam [ 'mmproj' ] } " )or mmproj 9226kind ,mmproj = resolve_reader (fam ["mmproj" ],mmproj ,models_root ,roots ,a .gguf_dir , (ISTA_FILES .get (fam ["mmproj" ])or (None ,))[0 ]) 9227if kind == "fetch" and not (mmproj .exists ()and done (mmproj )): 9228download (fam ["mmproj_hf" ]+ fam ["mmproj" ],mmproj ,"vision encoder" ) 9229if fam ["mmproj" ]in ISTA_FILES and kind != "alt" :# (a verified Unsloth F16 file was checked against its own pin) 9230verify_sha256 (mmproj ,* ISTA_FILES [fam ["mmproj" ]]) 9231ok (f"vision encoder: { mmproj } " + (" (Unsloth's mmproj-F16.gguf, SHA-256 checked)" if kind == "alt" else "" )) 9232 9233step (6 ,"preparing the model for Strata" ) 9234pack = find_in (roots ,f"packs/ { tag . lower () } " )or data / "packs" / tag .lower () 9235env = dict (os .environ ,** gguf_py_env ()) 9236shards = [files [0 ],files [0 ]]if family == "gyro" else files # Gyro: one file, the model and its n-gram table 9237pack_todo = not (pack / "native_experts.txt" ).exists ()or not (pack / "tokenizer" / "vocab.json" ).exists () 9238prep_lock = mac_prepare_lock (native )if repacked and (pack_todo or not (native .exists ()and done (native )))else None 9239try : 9240if repacked : 9241if not (native .exists ()and done (native )): 9242mac_repack (files ,model ,native ) 9243shards = [native ,mac_ple_shard (files )] 9244if pack_todo : 9245run ([sys .executable ,str (ROOT / "tools" / "iq_pack.py" ),"--gguf" ,str (shards [0 ]),"--out" ,str (pack ), 9246* fam .get ("pack_args" , [])],env = env )# Gyro and Unsloth: --compat-bf16 (the host's copies; the GPU reads the file) 9247finally : 9248if prep_lock is not None : 9249prep_lock .unlink (missing_ok = True ) 9250ok (f"model prepared: { pack } " ) 9251use_mtp = MF .stream_mtp (stream ,ram ) 9252no_layer = bool (MF .MAC_MODELS .get (model , {}).get ("no_mtp" )) 9253if no_layer :# the model list says there is no draft layer: none is fetched (the Flash-Next head is not this model's); said on every Mac, as on Windows and Linux 9254say (" The model list says this model has no draft layer (MTP), so none is fetched or used." ) 9255use_mtp = False 9256mtp = (find_in (roots ,"mtp/mtp-q2_0.gguf" )or data / "mtp" / "mtp-q2_0.gguf" ).parent 9257rt = mtp / "rt" 9258if stream and not use_mtp : 9259ok ("the experts stream from the SSD" + ("" if no_layer else ": no MTP draft layer (one token per step is faster there)" )) 9260elif stream : 9261ok (f"the experts stream from the SSD; the MTP draft layer stays on, with --spec { MF . STREAM_SPEC } " ) 9262if use_mtp and a .mtp == "off" and not (mtp / "mtp-q2_0.gguf" ).exists (): 9263ok ("the draft layer (MTP) is off: its ~5 GB are not downloaded (`--mtp on` fetches it later)" )# round 8, N3 9264use_mtp = False 9265elif use_mtp and getattr (a ,"drafter" ,None )== "dflash2" and not (mtp / "mtp-q2_0.gguf" ).exists (): 9266ok ("DFlash2 is the drafter: the MTP draft layer's ~5 GB are not downloaded (choosing the MTP later fetches it once)" ) 9267provide_dflash2_vocab (data ,a .draft_vocab or "cjk" ) 9268use_mtp = False 9269if use_mtp and not (mtp / "mtp-q2_0.gguf" ).exists (): 9270say (" The MTP draft layer (speculative decoding) comes from the original Qwen checkpoint: only its ~5 GB of MTP tensors are downloaded." ) 9271if fetch_mtp (mtp ,env )is False :# offline: the model starts without the layer 9272use_mtp = False 9273else : 9274run ([sys .executable ,str (ROOT / "tools" / "mtp_pack.py" ),"--src" ,str (mtp ),"--experts" ,"q2_0" , 9275"--out" ,str (mtp / "mtp-q2_0.gguf" )],env = env ) 9276if use_mtp : 9277rt .mkdir (parents = True ,exist_ok = True )# the Metal engine reads mtp-q2_0.gguf beside it (no rt pack) 9278refresh_draft_vocab (rt ,a .draft_vocab or "cjk" ) 9279ok (f"MTP draft layer: { mtp / 'mtp-q2_0.gguf' } " ) 9280if repacked and stream and ram < MF .STREAM_MTP_FROM_GB : 9281mac_experts_file (shards [0 ])# a small Mac: its misses are many; a big Mac's arena holds most experts 9282 9283step (7 ,"writing the run settings" ) 9284port = a .port or 8080 9285profile = ROOT / "data" / "expert-profile.bin" 9286neutral = getattr (__import__ ("strata_control.setup_config" ,fromlist = ["x" ]),"neutral_profile_if_other_shape" ,None )# (f-0213-p8merge: F4, the owner's line) 9287if neutral is not None and fam .get ("feed" )and shards :# a feed model of another shape than the shipped profile's: a neutral profile for the file's layers x experts 9288sys .path .insert (0 ,str (ROOT / "tools" )) 9289from gguf_reader import GGUFFile 9290profile = neutral (profile ,shards [0 ],pack ,GGUFFile ,say ) 9291args = MF .engine_args (pack ,shards ,rt ,ctx ,stream ,ram ,profile ,model )# Unsloth: --native the repacked file, --ple-gguf the table's shard 9292cfg = {"exe" :engine_exe (Path ("engine" )),"args" :args ,"cwd" :str (ROOT ),"tokenizer" :str (pack / "tokenizer" ), 9293"model_name" :f" { fam [ 'name' ] } - { model . lower () } " ,"log" :str (home ()/ f"strata- { tag . lower () } .log" ), 9294"lib_dirs" : [],"port" :port ,"backend" :"metal" ,"env" : {"STRATA_METAL_STREAM" :"1" if stream else "0" }} 9295if a .host : 9296cfg ["host" ]= a .host 9297if a .api_key : 9298cfg ["api_key" ]= a .api_key 9299if a .draft_vocab : 9300cfg ["draft_vocab" ]= a .draft_vocab 9301if a .browser is not None : 9302cfg ["open_browser" ]= a .browser 9303if vision != "none" :# the Mac's one program reads on the GPU (--gpu) or the CPU (strata_control/vision_reader.py) 9304from strata_control import vision_reader as VR 9305cfg ["args" ].append ("--vision" ) 9306cfg ["vision" ]= VR .vision_section (reader , {"exe" :str (reader .exe ),"mmproj" :str (mmproj ),"model" :str (files [0 ]), 9307"gpu" :vision == "gpu" ,"max_tokens" :vision_tokens (a .vision_tokens ,vision ,None )}) 9308if vision == "cpu" : 9309cfg ["vision" ]["threads" ]= vision_threads () 9310cfg_path = home ()/ f"strata- { tag . lower () } .json" 9311write_setup_config (cfg_path ,cfg ) 9312script = write_run_script (tag ,cfg_path ,port ,cfg .get ("open_browser" )is not False ) 9313ok (f"start script: { script . name } " ) 9314say () 9315say ("All set." ) 9316return 0 9317 9318 9319def main ()-> int : 9320try :# the engine programs setup runs start no debugger on a user's machine (strata_control/childenv.py) 9321from strata_control .childenv import quiet_crash_env 9322quiet_crash_env () 9323except Exception : 9324pass 9325try :# files made by a run as administrator still belong to the user 9326from strata_control import private_files as _pf 9327_pf .adopt_user_defaults () 9328except Exception : 9329pass 9330if sys .platform == "darwin" and not CONTROL :# a Mac: metal/setup_mac.py (the Metal engine); the app (Control mode) goes on below 9331return mac_setup (sys .argv [1 :]) 9332_peek = lambda flag :next ((v .split ("=" ,1 )[1 ]if v .startswith (flag + "=" )else sys .argv [i + 2 ]if i + 2 < len (sys .argv )else None # noqa: E731 9333for i ,v in enumerate (sys .argv [1 :])if v == flag or v .startswith (flag + "=" )),None ) 9334from strata_control import retired 9335if retired .is_name (_peek ("--family" ))or (_peek ("--model" )and retired .is_name (_peek ("--model" )) 9336and (not _peek ("--family" )or retired .is_name (_peek ("--family" )))): 9337say (" " + retired .NOT_OFFERED )# DeepSeek: no longer offered (strata_control/retired.py) 9338return 2 9339if (_peek ("--family" )and _peek ("--family" )not in {** FAMILIES ,** OWN_PATH_FAMILIES }) \ 9340or (_peek ("--model" )and not _peek ("--family" )and model_alias (_peek ("--model" ))not in MODELS 9341and not any (model_alias (_peek ("--model" ))in f ["models" ]for f in OWN_PATH_FAMILIES .values ())): 9342feed_models_setup (_peek ("--feed" ))# a name the built-in tables do not know may be a model of the signed feed 9343if _peek ("--family" )in FEED_UNAVAILABLE : 9344fail (f" { FEED_UNAVAILABLE [ _peek ( '--family' )][ 'title' ] } is { FEED_UNAVAILABLE [ _peek ( '--family' )][ 'reason' ] } " ) 9345ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 9346ap .add_argument ("--family" ,choices = list (FAMILIES )+ list (PREVIEW_FAMILIES ), 9347help = "qwen = Qwen3.8-Flash-Next, swift = Swift 1.5, qwen36 = Qwen3.6-35B-A3B (pictures with --vision, " 9348"several requests at once with --parallel; docs/QWEN36.md)" ) 9349ap .add_argument ("--model" ,type = model_alias ,choices = list (dict .fromkeys ([* MODELS ,* (m for f in PREVIEW_FAMILIES .values () 9350for m in f ["models" ])]))) 9351ap .add_argument ("--context" ,type = int ) 9352ap .add_argument ("--rope-scaling" ,choices = ["none" ,"linear" ,"yarn" ], 9353help = "the RoPE extension for a context past the model's trained 262144: linear (position " 9354"interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " 9355"picks yarn; 'none' is refused for such a context" ) 9356ap .add_argument ("--rope-scale" ,type = float , 9357help = "the extension factor, finite and >= 1 (default: the final context over the trained " 9358"262144, at least 1 - 1.5 for 384K, 2 for 512K, 1 inside the trained range)" ) 9359ap .add_argument ("--kv" ,choices = ["int8" ,"q4_0" ,"k8v4" ,"fp16" ], 9360help = "KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " 9361"precise) k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell) or fp16 (16-bit, twice the memory of int8)" ) 9362ap .add_argument ("--vision" ,choices = ["yes" ,"no" ,"none" ,"gpu" ,"cpu" ], 9363help = "let the model read images (on by default where the model can; yes = the best reader for this card: the CPU " 9364"under 24 GB of VRAM, the GPU from 24 GB, any make; gpu / cpu = that reader; no = text only)" ) 9365ap .add_argument ("--vision-tokens" ,type = int ,metavar = "N" , 9366help = "the most image tokens a picture becomes (default 1024 with the encoder on the GPU, 300 on " 9367"the CPU): more reads small text and charts better, and takes longer to encode; remembered " 9368"for this model" ) 9369# image generation (Qwen-Image): in preview, not offered in setup or --help; the options still work (docs/IMAGES.md) 9370ap .add_argument ("--images" ,choices = ["qwen-image" ,"no" ], 9371help = argparse .SUPPRESS ) 9372ap .add_argument ("--image-quant" ,choices = ["Q4_K_M" ,"Q6_K" ,"Q8_0" ], 9373help = argparse .SUPPRESS ) 9374ap .add_argument ("--image-backend" ,choices = ["cuda" ,"hip" ,"vulkan" ,"cpu" ], 9375help = argparse .SUPPRESS ) 9376ap .add_argument ("--image-native" ,choices = ["on" ,"off" ], 9377help = argparse .SUPPRESS ) 9378ap .add_argument ("--image-noise" ,choices = ["on" ,"off" ], 9379help = argparse .SUPPRESS ) 9380ap .add_argument ("--image-vae" ,choices = ["on" ,"off" ], 9381help = argparse .SUPPRESS ) 9382ap .add_argument ("--image-gpu-policy" ,choices = ["auto" ,"keep" ,"shrink" ,"unload" ], 9383help = argparse .SUPPRESS ) 9384ap .add_argument ("--experimental-speed-projection" ,metavar = "on|off|GGUF" , 9385help = "EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " 9386"(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md" ) 9387ap .add_argument ("--port" ,type = int ,help = "the server's port (default: the one the install was set up with, 8080 for a new one)" ) 9388ap .add_argument ("--gpu" ,help = "one GPU, numbered as nvidia-smi numbers them (AMD: as setup lists them) (default: asked when several can be " 9389"used; with --setup it is saved, when starting it is for that start only)" ) 9390ap .add_argument ("--gpus" ,help = "several GPUs sharing one model, as nvidia-smi numbers them (AMD: as setup lists " 9391"them): \"0,2\", or \"all\" (every card that can); Strata puts the faster card last, " 9392"and the last card is the Main one. Saved, also when starting (see docs/MULTI_GPU.md)" ) 9393ap .add_argument ("--gpu-roles" ,metavar = "LIST" ,help = "a role for each GPU: main, helper or off, e.g. 1=main,0=helper (cards you do not " 9394"name are off). Main does the last steps of every answer. Saved (docs/MULTI_GPU.md)" ) 9395ap .add_argument ("--layer-split" ,help = "with --gpus: where each later GPU's layers start (\"18\", \"16,32\"), one " 9396"rising number per GPU after the first - not layers per card; default " 9397"auto, placed from each GPU's free VRAM" ) 9398ap .add_argument ("--no-remote-expert-opt" ,action = "store_true" , 9399help = "with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)" ) 9400ap .add_argument ("--host" ,help = "where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = all IPv4 " 9401"interfaces, :: = all IPv6 interfaces (issue #26; an --api-key is recommended)" ) 9402ap .add_argument ("--api-key" ,help = "require this key from clients (recommended with --host 0.0.0.0 or --host ::); " 9403"several keys: key1,key2" ) 9404ap .add_argument ("--no-browser" ,dest = "browser" ,action = "store_false" ,default = None , 9405help = "do not open the chat page in the browser when the model is ready (for a harness or an app " 9406"that uses the API; remembered for this model, also in run-<model>.bat/.sh)" ) 9407ap .add_argument ("--browser" ,dest = "browser" ,action = "store_true" , 9408help = "open the chat page again when the model is ready (the default; undoes --no-browser)" ) 9409ap .add_argument ("--data-dir" ,help = "where the model files go (~70-120 GB): default Strata-data next to this folder, " 9410"remembered for every Strata folder on this PC" ) 9411ap .add_argument ("--move-data" ,action = "store_true" , 9412help = "with --data-dir: move the model files already on this PC into the new folder (without it nothing " 9413"is moved: the old files stay usable and the new folder gets the new downloads)" ) 9414ap .add_argument ("--set-default-data-dir" ,action = "store_true" , 9415help = "with --data-dir: remember the new folder as the data folder without moving anything" ) 9416ap .add_argument ("--models-dir" ,help = "where the GGUF files go (default: <data folder>/models)" ) 9417ap .add_argument ("--dsv41-package" ,metavar = "FILE" ,help = argparse .SUPPRESS )# DeepSeek's: answered with retired.NOT_OFFERED 9418ap .add_argument ("--feed" ,metavar = "URL|DIR" , 9419help = "where the signed update feed is: default STRATA_UPDATE_FEED, a remembered https feed, " 9420"or the release's (as `strata update --feed`; a folder is a local test feed)" ) 9421ap .add_argument ("--gguf-dir" ,help = "use GGUF files you already have (a folder with every shard: " 9422"<name>-00001-of-0000N.gguf ... -0000N-of-0000N.gguf)" ) 9423ap .add_argument ("--yes" ,action = "store_true" ,help = "accept the recommended answers" ) 9424ap .add_argument ("--setup" ,action = "store_true" ,help = "install another model or change settings" ) 9425ap .add_argument ("--no-start" ,action = "store_true" ,help = "install only, do not start the model" ) 9426ap .add_argument ("--update" ,action = "store_true" , 9427help = "update the installed engine, Python packages and model settings as a start would, without " 9428"starting the model (UPDATE.bat / update.sh run it after a git pull)" ) 9429ap .add_argument ("--rollback-engine" ,action = "store_true" , 9430help = "put back the engine an update replaced (kept in engine/.previous), and keep the current one there" ) 9431ap .add_argument ("--build" ,action = "store_true" ,help = "compile the engine instead of using the ready-made one" ) 9432ap .add_argument ("--source" ,choices = SOURCES ,default = None , 9433help = "where the model files come from: auto (default: Hugging Face), huggingface or modelscope " 9434"(mainland China: the same files, checked against ModelScope's published SHA-256; " 9435"STRATA_SOURCE)" ) 9436ap .add_argument ("--prepare-pack" ,metavar = "PACK_DIR" , 9437help = "only build the pack of the GGUF files in --gguf-dir into PACK_DIR (what `strata launch` runs for an Intel Arc card): " 9438"fetches llama.cpp's gguf-py by itself, runs tools/iq_pack.py, changes nothing else" ) 9439ap .add_argument ("--inspect" ,nargs = "+" ,metavar = ("SOURCE" ,"VARIANT" ), 9440help = "what a GGUF is and whether Strata runs it, from its headers only (no download): a file, a " 9441"folder, a URL, ms:owner/repo (ModelScope) or hf:owner/repo, and optionally a variant name" ) 9442ap .add_argument ("--cuda" ,choices = ["12" ,"13" ,"auto" ],default = os .environ .get ("STRATA_CUDA" )or None , 9443help = "NVIDIA: the CUDA toolkit of this model's engine. auto (default): CUDA 13, the ready-made " 9444"engine; CUDA 12 (experimental) when a chosen card is older than CUDA 13 supports (Pascal, " 9445"Volta). 12 also runs with an older driver (Windows 528+, Linux 525+). docs/OLDER_GPUS.md" ) 9446ap .add_argument ("--prebuilt" ,default = os .environ .get ("STRATA_PREBUILT_URL" ,PREBUILT_URL ), 9447help = "where the ready-made engine is (a URL folder or a local folder)" ) 9448ap .add_argument ("--check" ,action = "store_true" ,help = "only check this PC and exit" ) 9449ap .add_argument ("--calibrate" ,action = "store_true" , 9450help = "tune the engine's settings for this PC (about 15-30 minutes, longer on a slow card), then start the model" ) 9451ap .add_argument ("--draft-vocab" ,choices = list (DRAFT_VOCABS ), 9452help = "the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " 9453"and code only (~110 MiB less VRAM, English answers 1-2%% faster), cyrillic = English, code " 9454"and the Cyrillic script (Russian: 26%% more tokens a second), fr = English, " 9455"code and French (French answers: 18%% more drafts accepted), latin = English, code and " 9456"the Latin-script languages (German, Spanish, French, Polish: 8-12%% more tokens a " 9457"second). Without this setting Strata picks cyrillic or latin by itself from the " 9458"languages of this computer, and keeps the default when one of them is Chinese, " 9459"Japanese or Korean" ) 9460ap .add_argument ("--low-ram" ,choices = ["auto" ,"on" ,"off" ,"resident" ,"mmap" ],default = "auto" , 9461help = "read the model's experts from one file in its folder instead of copying them all into RAM " 9462"(for a PC with a big GPU and little RAM); auto: when the experts would not fit the RAM. In " 9463"this mode the experts the GPU does not hold are copied into RAM once when they fit (resident), " 9464"else read through the OS file cache (mmap); resident / mmap force one of the two" ) 9465ap .add_argument ("--resident-budget-gib" ,type = float ,metavar = "N" , 9466help = "UD-Q4_K_XL, UD-IQ4_XS: the GiB of its experts kept in RAM (default: the RAM less 24 GB, 40 on 64 GB; " 9467"more is kept as you choose, with a note)" ) 9468ap .add_argument ("--vram-reserve-mib" ,type = int ,metavar = "N" , 9469help = "VRAM in MiB the engine leaves free for other programs (a game, another model; the engine's " 9470"default: 700); the expert cache takes that much less" ) 9471ap .add_argument ("--mtp" ,choices = ["on" ,"off" ], 9472help = "the draft layer (MTP): off starts the model without it, which frees about 1 GB of graphics memory " 9473"for the expert cache and takes less RAM, at the price of speed; it is kept in the run config " 9474"(\"mtp\": false) and a later setup run does not undo it. on: back to the default" ) 9475ap .add_argument ("--drafter" ,choices = ["mtp" ,"dflash2" ], 9476help = "which drafter this model will use. dflash2: the MTP draft layer's ~5 GB are not downloaded (the DFlash2 drafter is fetched by `strata drafting fetch`); " 9477"the arguments keep the --mtp folder so a later switch to the MTP works. mtp (the default): the draft layer is fetched as before. Nothing is written about it " 9478"in the run config: the choice is its \"drafting\" key" ) 9479ap .add_argument ("--parallel" ,type = int ,metavar = "N" , 9480help = "up to N requests decode together (batch slots, opt-in; default: one at a time, the others " 9481"wait). Each slot takes VRAM from the expert cache; setup says what it recommends" ) 9482ap .add_argument ("--replicas" ,type = int ,metavar = "N" , 9483help = "several GPUs: run N independent engines, each on its own equal group of the chosen cards (2 " 9484"replicas on 4 cards = two 2-card engines), requests spread over them (opt-in; more total " 9485"throughput for a model that fits fewer cards; each replica holds its own copy of the model)" ) 9486ap .add_argument ("--replica-profile" ,action = "store_true" ,default = False , 9487help = "two or more GPUs, Qwen3.8 IQ3_S/IQ3_XXS/Q2_0: one engine per card behind the server instead of one " 9488"layer split, the experts shared in RAM, the batch switches on (opt-in; about 1.8 times the " 9489"throughput at 8-16 requests at once on 4 Radeon AI PRO R9700; needs about 61 GB of RAM for 2 " 9490"engines and 66 GB for 4; a layer split you chose, replicas or --parallel always win)" ) 9491ap .add_argument ("--kv-streaming" ,choices = ["auto" ,"on" ,"off" ],default = "auto" , 9492help = "from a 64K context: keep the KV cache in RAM and only the attention's window in VRAM (more " 9493"experts fit on the GPU); auto: when the RAM has room for it" ) 9494ap .add_argument ("--backend" ,choices = ["cuda" ,"hip" ,"sycl" ], 9495help = "cuda = NVIDIA (default), hip = AMD RX 7900 / 7800 / 7700 XT, RX 9060 XT / 9070 / AI PRO R9700 on " 9496"Linux or Windows (chosen by itself when the PC has no NVIDIA card Strata can use), " 9497"sycl = Intel Arc, EXPERIMENTAL: Linux, built from source (docs/INTEL_ARC.md)" ) 9498ap .add_argument ("--skip-build" ,action = "store_true" ,help = argparse .SUPPRESS ) 9499a = ap .parse_args () 9500if getattr (a ,"gguf_dir" ,None ):# the person's own files: their finish marks go to Strata's marks/, never beside them 9501own_files_in (a .gguf_dir ) 9502if getattr (a ,"dsv41_package" ,None ):# DeepSeek's engine package: no longer offered (strata_control/retired.py) 9503say (" " + retired .NOT_OFFERED ) 9504return 2 9505if a .model and a .model not in MODELS and a .family not in PREVIEW_FAMILIES : 9506ap .error (f"--model { a . model } is a size of " + ", " .join (f"--family { f } " for f ,d in PREVIEW_FAMILIES .items () 9507if a .model in d ["models" ])) 9508if a .source : 9509os .environ ["STRATA_SOURCE" ]= a .source 9510if a .prepare_pack :# an Intel Arc card: the model's pack, nothing else (no engine, no download of the model) 9511return prepare_pack_only (a ) 9512if a .inspect :# headers only: nothing is installed 9513sys .exit (subprocess .run ([sys .executable ,str (ROOT / "tools" / "strata_inspect.py" ),* a .inspect [:2 ]]).returncode ) 9514if sys .platform == "darwin" and CONTROL :# the app on a Mac: model files only; the Metal engine is a component 9515return mac_control_setup (a ) 9516if a .backend == "sycl" :# Intel Arc: the app / Terminal's installer mode prepares the files and writes the config; a checkout builds from source 9517if CONTROL : 9518return intel_control_setup (a ) 9519return sycl_setup (sys .argv [1 :]) 9520if a .resident_budget_gib is not None and not a .resident_budget_gib > 0 : 9521ap .error ("--resident-budget-gib takes a number of GiB above 0, e.g. --resident-budget-gib 32" ) 9522if a .vision_tokens is not None and a .vision_tokens < 1 : 9523ap .error ("--vision-tokens takes a number of image tokens, 1 or more, e.g. --vision-tokens 768" ) 9524if a .vram_reserve_mib is not None and a .vram_reserve_mib < 0 : 9525ap .error ("--vram-reserve-mib takes a number of MiB, 0 or more, e.g. --vram-reserve-mib 2048" ) 9526if a .gpu is not None :# --gpu 0,2 means --gpus 0,2 (a user tried it: issue report) 9527if "," in a .gpu : 9528a .gpus ,a .gpu = a .gpus or a .gpu ,None 9529elif a .gpu .strip ().isdigit (): 9530a .gpu = int (a .gpu ) 9531else : 9532ap .error (f"--gpu takes a GPU number as nvidia-smi numbers them, e.g. --gpu 1 (or --gpus 0,2), not { a . gpu !r } " ) 9533a ._roles = None 9534if a .gpu_roles : 9535if a .gpu is not None or a .gpus : 9536ap .error ("use --gpu-roles (a role for each card) or --gpu / --gpus (which cards), not both" ) 9537from strata_control import gpu_roles as GR 9538try : 9539named = GR .parse_roles (a .gpu_roles ) 9540except ValueError as e : 9541ap .error (f"--gpu-roles: { e } " ) 9542on = [i for i ,r in named .items ()if r != "off" ] 9543if not on : 9544ap .error ("--gpu-roles: setup needs at least one card that is Main or Helper" ) 9545mains = [i for i ,r in named .items ()if r == "main" ]or [sorted (on )[- 1 ]] 9546helpers = sorted (i for i in on if i != mains [0 ]) 9547a ._roles_explicit = True 9548a ._roles = {** {i :"off" for i in named },** {i :"helper" for i in helpers },mains [0 ]:"main" } 9549order = helpers + [mains [0 ]] 9550if len (order )> 1 : 9551a .gpus = "," .join (str (i )for i in order ) 9552else : 9553a .gpu = order [0 ] 9554say ("Strata - " + (OWN_PATH_FAMILIES [a .family ]["title" ]if a .family in OWN_PATH_FAMILIES else "Qwen3.8-Flash-Next" ) 9555+ " on a normal PC (a GPU + system RAM + CPU)" ) 9556have = installed_configs () 9557if a .update or not (a .setup or a .model or a .family or a .check or a .no_start or a .calibrate or a .rollback_engine ): 9558from strata_control import retired 9559for c in retired_configs ():# DeepSeek: named, left as it is 9560say (" " + retired .left_as_is (retired .title (None ,c ))) 9561# A plain start of an installed model finds everything where it already is: it creates, moves and copies nothing 9562# (the model paths are in the run config; the data folder is the one settings.json remembers). Setting up, checking, 9563# tuning and updating look for and gather the model files (data_folder). 9564plain_start = bool (have )and not (a .setup or a .model or a .family or a .check or a .no_start or a .update 9565or a .calibrate or a .rollback_engine or a .data_dir ) 9566models_dir_given = a .models_dir is not None 9567data ,elsewhere = data_folder_in_place ()if plain_start else data_folder_for (a )# the model files 9568roots = [data ,* elsewhere ] 9569if a .models_dir is None : 9570a .models_dir = str (data / "models" ) 9571 9572if a .rollback_engine :# #670 9573return rollback_engine (12 if a .cuda == "12" else 13 ) 9574 9575# ---- 0. already installed: just start it 9576if a .update :# #475: UPDATE.bat / update.sh - never starts the model 9577return update_install (have ,a ) 9578explicit = a .setup or a .model or a .family or a .check or a .no_start 9579adopted = None # #629: the earlier install this copy is set up like 9580if not have and not explicit :# a new copy of Strata (an update unzipped elsewhere): set it 9581prev = previous_config (elsewhere ,load_settings ())# up like the last one, from the files already here 9582if prev is not None : 9583ch = choices_from_config (prev ) 9584if ch ["model" ]: 9585say (f" Found your earlier install in { prev . parent } ( { prev . stem [ len ( 'strata-' ):] } ): setting up this " 9586"copy the same way - the model files are reused, nothing big is downloaded." ) 9587a .family ,a .model ,a .context = ch ["family" ],ch ["model" ],a .context or ch ["context" ] 9588adopted = prev 9589a .kv = a .kv or ch ["kv" ] 9590a .vision = a .vision or ch ["vision" ] 9591a .experimental_speed_projection = a .experimental_speed_projection or ch ["esp" ] 9592a .host ,a .api_key = a .host or ch ["host" ],a .api_key or ch ["api_key" ] 9593a .port = a .port or ch ["port" ] 9594if a .vram_reserve_mib is None :# #493: an explicit reserve set up before 9595a .vram_reserve_mib = ch .get ("vram_reserve_mib" ) 9596if a .cuda is None and ch .get ("cuda" )== 12 :# the experimental CUDA 12 engine, as before 9597a .cuda = "12" 9598if isinstance (ch .get ("gpu" ),list ):# a layer split: set up across the same cards again 9599a .gpus = a .gpus or "," .join (str (g )for g in ch ["gpu" ]) 9600a .layer_split = a .layer_split or ch .get ("layer_split" ) 9601else : 9602a .gpu = a .gpu if a .gpu is not None else ch .get ("gpu" ) 9603a .yes = True 9604global GPU_PICK ,OLD_GPUS 9605# starting an installed model: --gpus 0,2 (or all) saves those cards for it and starts on them (it used to start 9606# on the first one alone unless given with --setup), --gpu N runs this start on one card; neither: the saved 9607# choice, and asked once when the PC has cards that could share the model 9608run_gpu = start_gpus (a .gpus )or a .gpu 9609port = a .port or 8080 # a new install's port (issue #32: --port for an existing one) 9610if a .calibrate and (a .setup or a .check or not have ):# #2036: said, not dropped 9611why = ("--setup" if a .setup else "--check" if a .check else "no model is installed yet" ) 9612warn (f"--calibrate does nothing with { why } : it tunes a model that is already installed. Run setup first, " 9613"then " + ("START-HERE.bat" if WIN else "./setup.sh" )+ " --calibrate [--model NAME]" ) 9614if have and a .calibrate and not (a .setup or a .check ): 9615targets = calibration_targets (have ,a .model ,a .family ) 9616if not targets :# #2036: --model names a model that is not installed 9617names = ", " .join (sorted ({choices_from_config (c )["model" ]or c .stem for c in have })) 9618fail (f"--calibrate: { a . model or a . family } is not installed (installed: { names } )" , 9619"calibrate an installed model, or set this one up first without --calibrate" ) 9620have = targets 9621engine_update_note () 9622pick_cfg = have [0 ] 9623if len (have )> 1 : 9624say () 9625for i ,c in enumerate (have ,1 ): 9626say (f" { i } ) { json . loads ( c . read_text ( encoding = 'utf-8-sig' )). get ( 'model_name' , c . stem ) } " ) 9627pick_cfg = have [int (ask ("Tune which one?" , [str (i )for i in range (1 ,len (have )+ 1 )],"1" ,a .yes ))- 1 ] 9628if not calibrate_config (pick_cfg ):# #447: said again where it is not lost above the start 9629say () 9630warn ("this PC is NOT tuned: the tuning failed (the reason is above); the model " 9631+ ("keeps" if a .no_start else "starts with" )+ " the default settings" ) 9632return 0 if a .no_start else start (pick_cfg ,a .port ,run_gpu ,yes = a .yes ,layer_split = a .layer_split , 9633keep = {"host" :a .host ,"api_key" :a .api_key ,"draft_vocab" :a .draft_vocab , 9634"vram_reserve_mib" :a .vram_reserve_mib ,"open_browser" :a .browser }) 9635if have and not (a .setup or a .model or a .family or a .check or a .no_start ): 9636engine_update_note () 9637if len (have )== 1 : 9638return start (have [0 ],a .port ,run_gpu ,yes = a .yes ,layer_split = a .layer_split , 9639keep = {"host" :a .host ,"api_key" :a .api_key ,"draft_vocab" :a .draft_vocab , 9640"vram_reserve_mib" :a .vram_reserve_mib ,"open_browser" :a .browser }) 9641say () 9642for i ,c in enumerate (have ,1 ): 9643say (f" { i } ) { json . loads ( c . read_text ( encoding = 'utf-8-sig' )). get ( 'model_name' , c . stem ) } " ) 9644say (f" { len ( have ) + 1 } ) install another model / change settings" ) 9645pick = int (ask ("Which one?" , [str (i )for i in range (1 ,len (have )+ 2 )],"1" ,a .yes )) 9646if pick <= len (have ): 9647return start (have [pick - 1 ],a .port ,run_gpu ,yes = a .yes ,layer_split = a .layer_split , 9648keep = {"host" :a .host ,"api_key" :a .api_key ,"draft_vocab" :a .draft_vocab , 9649"vram_reserve_mib" :a .vram_reserve_mib ,"open_browser" :a .browser }) 9650data ,elsewhere = data_folder_for (a )# "install another model": now the model files are gathered 9651roots = [data ,* elsewhere ] 9652if not models_dir_given : 9653a .models_dir = str (data / "models" ) 9654 9655# ---- 1. the PC 9656step (1 ,"checking your PC" ) 9657found = gpus () 9658amd = amd_gpus () 9659amd_ok = [g for g in amd if amd_problem (g )is None ] 9660# older NVIDIA GPUs (Pascal / Volta): the experimental CUDA 12 engine, when chosen (docs/OLDER_GPUS.md) 9661OLD_GPUS = OLD_GPUS or old_gpus_opt_in (found ,named_gpus (a .gpu ,a .gpus ),a .cuda , 9662other = bool (amd_ok )or a .backend == "hip" ) 9663if OLD_GPUS and a .backend != "hip" : 9664warn (f"older NVIDIA GPUs (Pascal / Volta) can be used ( { OLD_GPUS } ): experimental, through a second engine " 9665"built with CUDA 12 (docs/OLDER_GPUS.md)" ) 9666nv_ok = any (gpu_problem (g )is None for g in found ) 9667if not nv_ok and not amd_ok and a .backend != "hip" and maxwell_note (found ):# #3218: a warning with the way forward 9668warn (maxwell_note (found )) 9669hip = a .backend == "hip" or (a .backend is None and not nv_ok and bool (amd_ok )) 9670if a .backend is None and nv_ok and amd_ok : 9671# both kinds of card: asked (a first run on such a PC used to take NVIDIA without mentioning the Radeon) 9672say () 9673say (" This PC has NVIDIA and AMD cards Strata can use:" ) 9674say (" 1) NVIDIA: " + ", " .join (f" { g [ 'name' ] } ( { g [ 'vram_gb' ]:.0f } GB)" for g in found if gpu_problem (g )is None ) 9675+ " (recommended)" ) 9676say (" 2) AMD: " + ", " .join (f" { g [ 'name' ] } ( { g [ 'vram_gb' ]:.0f } GB { ', unified memory' if g . get ( 'uma' ) else '' } )" 9677for g in amd_ok ) 9678+ f" ( { 'the ready-made AMD engine' if WIN else 'compiled here' } , pictures on" 9679" - docs/AMD_HIP.md)" ) 9680say (" One engine drives the cards of one make: a model is never split across NVIDIA and AMD cards, and two models at the same" ) 9681say (" time, one on each, is not supported yet." ) 9682from strata_control import gpu_fit 9683bigger = gpu_fit .other_vendor_note ([{** g ,"vendor" :"nvidia" ,"usable" :gpu_problem (g )is None }for g in found ]+ 9684 [{** g ,"vendor" :"amd" ,"usable" :True }for g in amd_ok ],"nvidia" ) 9685if bigger : 9686say (" " + bigger ) 9687hip = ask ("Which cards?" , ["1" ,"2" ],"1" ,a .yes or a .check )== "2" 9688if a .check and not hip : 9689say (f" (the AMD card: { 'START-HERE.bat' if WIN else './setup.sh' } --backend hip)" ) 9690cuda_tk = 13 # NVIDIA: the toolkit of this model's engine (cuda_choice) 9691if hip :# AMD: compiled here; Windows: ready-made 9692if WIN and a .gpus : 9693fail ("several AMD cards sharing one model (--gpus) is Linux-only for now" ,"use one card: --gpu N" ) 9694say (" Your AMD GPUs:" if amd else " No AMD GPU found (" + ("Windows lists no AMD display adapter)." if WIN 9695else "the amdgpu driver's KFD topology is empty)." )) 9696for g in amd : 9697say (f" GPU { g [ 'index' ] } : { g [ 'name' ] } , { amd_mem_text ( g ) } - " + (amd_problem (g )or "can be used" )) 9698if not WIN :# WSL: the Linux HIP engines hang there; a warning, the run goes on 9699from strata_control .engine_component import wsl_amd_note 9700wsl_note = wsl_amd_note ("hip" ,wsl = is_wsl ()) 9701if wsl_note : 9702warn (wsl_note ) 9703usable = [g for g in amd if amd_problem (g )is None ] 9704if not WIN and (amd or amd_pci_devices ()):# a warning only: recommend, never force 9705acc = amd_device_access_problem () 9706if acc : 9707warn (acc ) 9708if not amd and not WIN :# the KFD topology is empty: name a Strix Halo the kernel sees 9709for d in amd_pci_devices (): 9710if d ["pci_id" ]in STRIX_HALO_PCI_IDS : 9711say (f" The kernel lists an AMD Strix Halo (PCI 1002: { d [ 'pci_id' ]:04x } ) but /dev/kfd's topology is " 9712"empty: ROCm cannot use it yet (docs/STRIX_HALO.md: the amdgpu driver and /dev/kfd access, " 9713"your user in the render and video groups)" ) 9714if not usable : 9715fail ("no AMD GPU Strata can use" ,f"the AMD backend runs on { AMD_CARDS } " ) 9716if a .gpus :# a layer split across these cards, the first one the main 9717chosen = amd_parse_gpus (a .gpus ,amd ) 9718gpu = chosen [0 ] 9719elif a .gpu is not None : 9720gpu = next ((g for g in usable if g ["index" ]== a .gpu ),None ) 9721if gpu is None : 9722fail (f"AMD GPU { a . gpu } cannot be used" ,"use one of: " + ", " .join (f"--gpu { g [ 'index' ] } " for g in usable )) 9723chosen = [gpu ] 9724else : 9725gpu = min (usable ,key = amd_rank )# a discrete card before an APU, then the most memory 9726chosen = [gpu ] 9727if len (usable )> 1 and any (g .get ("uma" )for g in usable )!= all (g .get ("uma" )for g in usable ): 9728others = [g for g in usable if g is not gpu ] 9729say (f" Using GPU { gpu [ 'index' ] } ( { gpu [ 'name' ] } ); setup recommends the card with its own memory over " 9730"the APU's shared memory. To use another: " 9731+ ", " .join (f"--gpu { g [ 'index' ] } ( { g [ 'name' ] } )" for g in others )) 9732# the engine is compiled for every chosen card's architecture 9733gpu = {** gpu ,"count" :len (amd ),"archs" :sorted ({g ["arch" ]for g in chosen })} 9734chosen = [gpu ]+ chosen [1 :] 9735sel = [g ["index" ]for g in chosen ] 9736multi = sel if len (sel )> 1 else [] 9737a .gpu = gpu ["index" ]if len (amd )> 1 else a .gpu 9738if multi : 9739ok ("GPUs: " + " + " .join (gpu_name (x )for x in chosen )+ " together (the model's layers are split across them)" ) 9740ok (f"GPU: { gpu [ 'name' ] } , { amd_mem_text ( gpu ) if gpu . get ( 'uma' ) else format ( gpu [ 'vram_gb' ], '.1f' ) + ' GB VRAM' } , " 9741f" { gpu [ 'arch' ] } (AMD: docs/ { 'STRIX_HALO' if is_strix_halo ( gpu ) else 'AMD_HIP' } .md)" ) 9742if WIN and str (gpu .get ("arch" )or "" ).startswith ("gfx12" ):# only a pointer; no default changes 9743say (" If Windows resets the AMD driver (VIDEO_ENGINE_TIMEOUT_DETECTED, flicker, the engine dies mid-answer): " 9744"docs/TROUBLESHOOTING.md, \"Windows AMD: the driver resets\"" ) 9745if gpu .get ("uma" ): 9746for line in igpu_notes (gpu ,ram_gb ()): 9747 (warn if line .startswith ("!" )else say )(line .lstrip ("!" )) 9748for line in unused_apu_notes (chosen ,amd ,ram_gb ()): 9749 (warn if line .startswith ("!" )else say )(line .lstrip ("!" )) 9750for line in rdna2_notes (gpu ): 9751say (line ) 9752else : 9753if not found : 9754fail ("no NVIDIA GPU found (nvidia-smi did not answer)" , 9755"install the NVIDIA driver from https://www.nvidia.com/drivers and restart the PC" 9756+ (f"; AMD ( { ', ' . join ( AMD_ARCHS ) } ): --backend hip" if amd else "" )) 9757if len (found )> 1 or gpu_problem (found [0 ])is not None : 9758gpu_table (found ) 9759sel = choose_gpus (a ,found )# asked when two or more cards can share the model 9760multi = sel if len (sel )> 1 else [] 9761a .gpu = sel [- 1 ]if getattr (a ,"_roles" ,None )else sel [0 ]# the main GPU: the checks and the sizing below are its (roles: Main is last) 9762GPU_PICK = a .gpu 9763gpu = gpu_info (a .gpu ) 9764chosen = [gpu_info (i )for i in sel ] 9765gpu ["archs" ]= sorted ({x ["arch" ]for x in chosen })# the engine needs code for every one of them 9766if multi : 9767ok ("GPUs: " + " + " .join (gpu_name (x )for x in chosen )+ " together (the model's layers are split across them)" ) 9768ok (f"GPU: { gpu [ 'name' ] } , " + (f"unified memory ( { gpu [ 'vram_gb' ]:.0f } GB usable by the GPU)" if gpu .get ("uma" )else f" { gpu [ 'vram_gb' ]:.1f } GB VRAM" ) 9769+ f", compute capability { cc ( gpu ) } , driver { gpu [ 'driver' ] } " ) 9770cuda_tk ,why = cuda_choice (gpu ["archs" ],a .cuda ,driver_major (gpu ))# one engine per model: its oldest card decides 9771if why : 9772 (warn if cuda_tk == 13 or str (a .cuda )== "12" else ok )(f"CUDA { cuda_tk } : { why } " ) 9773min_driver = CUDA12_COMPAT_DRIVER if cuda_tk == 12 else MIN_DRIVER 9774if driver_major (gpu )< min_driver : 9775fail (f"the NVIDIA driver is too old ( { gpu [ 'driver' ] } ; { min_driver } or newer is needed)" 9776+ ("" if cuda_tk == 12 else f" (the CUDA 12 engine package needs { cuda12_min_driver ()[ 1 ] } or newer, { cuda12_min_driver ()[ 2 ] } )" ), 9777"update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again" ) 9778if cuda_tk == 12 : 9779cuda12_min_driver (feed = True )# the CUDA 12 package's driver floor: the installed package, else the signed feed (#4247) 9780if note := cuda12_driver_warning (driver_major (gpu )): 9781warn (note ) 9782if gpu ["vram_gb" ]< 11 : 9783warn ("less than 12 GB of " + ("GPU memory (this APU's carve-out + shared memory)" if gpu .get ("uma" )else "VRAM" ) 9784+ ": Strata will run, but most experts stay on the CPU and it will be slow" ) 9785ram = ram_gb () 9786cpu ,avx2 ,avx512 = cpu_info () 9787need = min (d ["ram_gb" ]for d in MODELS .values ()if not d .get ("mem_total" ))# Gyro counts VRAM + RAM: not a RAM floor 9788low_ok = low_ram_fits ("IQ1_M" ,ram ,low_ram_vram (gpu ))and a .low_ram != "off" # the smallest model, mapped 9789if ram < need - 4 and not a .check and not low_ok : 9790# every model keeps ALL its experts in RAM (23+ GB); VRAM only holds a copy of the most-used ones, so a 9791# bigger GPU does not lower this. The owner's rule: a stop by default, a risk the user can take (--model 9792# with --yes, or y) 9793confirm_risk (f"RAM: { ram :.0f } GB - the smallest model (the Coder) needs about { need } GB: Strata keeps all of " 9794"the model's experts in RAM (23-50 GB, whatever the GPU), so the OS will page them from disk. " 9795"Expect it to be very slow, and it may not start at all." ,bool (a .model ),a .yes , 9796f"RAM: { ram :.0f } GB - the smallest model (the Coder) needs about { need } GB" , 9797"Strata keeps all of the model's experts in RAM (23-50 GB, whatever the GPU) and the GPU holds a " 9798"copy of the most-used ones: it needs 32 GB of RAM or more (48 GB for the full model); --model " 9799"NAME --yes installs one anyway" ) 9800warn (f"going on with { ram :.0f } GB of RAM, as you chose" ) 9801ram_msg = (f"RAM: { ram :.0f } GB" if ram >= need - 4 else f"RAM: { ram :.0f } GB (less than the { need } GB the smallest model needs)" 9802+ ("; the GPU's VRAM makes up for it (the low-RAM mode)" if ram < need - 4 and low_ok else "" )) 9803 (ok if ram >= need - 4 or low_ok else warn )(ram_msg )# #977: a RAM below every model's floor is not [ok] 9804pf = page_file_gb () 9805if pf is not None and pf < 4 : 9806warn (page_file_advice (pf ,page_file_setting ())) 9807ok (f"CPU: { cpu } ( { 'ARM64' if is_arm64 () else 'AVX-512' if avx512 else 'AVX2' if avx2 else 'no AVX2' } )" ) 9808# (a unified-memory GPU - a DGX Spark's GB10 - is on the CPU's own link, not PCIe: nvidia-smi's "1.0 x1" there means nothing) 9809link = None if hip or gpu .get ("uma" )else pcie_link (int (gpu .get ("index" ,0 ))) 9810if link is not None : 9811line ,problem = pcie_lines (link ) 9812ok (line ) 9813if problem : 9814warn (problem ) 9815floor = cpu_floor (avx2 ) 9816if floor == "unsupported" : 9817fail ("this CPU has neither AVX2 nor SSE4.2; Strata needs at least SSE4.2 (Intel Nehalem, 2008, or newer)" ) 9818if is_arm64 (): 9819# DGX Spark / GB10 (#3622): the engine is the linux-aarch64 package of the signed feed when the release has one, else compiled here 9820# (spark/build_engine.sh). A warning, not a stop. 9821warn ("ARM64 CPU (a DGX Spark): the CPU's share of the experts runs on ggml-cpu's NEON kernels. Tested: Qwen3.8-Flash-Next IQ3_S and " 9822"the NVFP4 pack, on one DGX Spark (GB10). The Q2_0 and Gyro packs need the x86 kernels and do not " 9823"run on this CPU" ) 9824elif not avx2 : 9825# #394 #595 #623: the ready-made engine is AVX2; an older CPU gets one compiled here, whose CPU experts run on 9826# ggml-cpu's kernels for this CPU. Experimental: measured only on newer CPUs with the older path forced, and by 9827# users on a few Xeons. A warning, not a stop. 9828warn (f"this CPU has no AVX2: Strata support for it is EXPERIMENTAL and slow. Setup compiles the engine on this " 9829f"PC for { 'AVX' if floor == 'avx' else 'SSE4.2' } (STRATA_ISA_FLOOR= { floor } ; 10-20 minutes, once), and the " 9830"CPU's share of the experts runs on ggml-cpu's kernels, a few times slower than on an AVX2 CPU. " 9831"See \"Older CPUs\" in docs/INSTALL.md" ) 9832if hip and WIN : 9833fail ("the older-CPU engine is compiled from source, and setup compiles the AMD engine on Linux only" , 9834"use Linux for an AMD card on this CPU, or an NVIDIA card" ) 9835a .build = True 9836if a .check : 9837say () 9838any_fits = False 9839for m ,d in MODELS .items (): 9840verdict = ("EXPERIMENTAL, " if d .get ("experimental" )else "" )+ model_fit_label (m ,ram ,gpu ) 9841if d .get ("budget" )and hip and d .get ("nvidia_only" ):# #429: not run on AMD yet 9842verdict += " - NVIDIA only so far, untested on AMD" 9843if hip and d .get ("repo" ):# the ready-made NVFP4 packs: no AMD kernels at all 9844verdict = "NVIDIA only (the AMD engine has no NVFP4 kernels)" 9845else : 9846any_fits = any_fits or (model_fit_label (m ,ram ,gpu )== "fits" and not d .get ("mem_total" )) 9847say (f" { m :8s } needs ~ { model_files_gb ( m ):.0f } GB of RAM + VRAM: { verdict } " ) 9848if not any_fits : 9849# #977: every size says "does not fit", so the verdict says so too (and the exit code, for scripts). It only 9850# reports: --model NAME --yes still installs one anyway. 9851say (f"\nThis PC cannot run Strata yet: no model size fits { ram :.0f } GB of RAM (the smallest needs about " 9852f" { need } GB). --model NAME --yes installs one anyway, slowly." ) 9853return 1 9854say ("\nThis PC can run Strata. Run it again without --check to install." ) 9855return 0 9856 9857# ---- 2. the questions 9858step (2 ,"your choices" ) 9859if not a .family and not a .yes and FEED_MODELS is None : 9860feed_models_setup (getattr (a ,"feed" ,None ))# the signed feed's models, listed after the built-in ones (nothing happens when it has none) 9861fams = menu_families (hip ) 9862feed_late = [f for f in fams if FAMILIES [f ].get ("feed" )]# models of the signed feed come last in the list (none: nothing here changes) 9863fams = [f for f in fams if f not in feed_late ] 9864if a .family : 9865family = a .family 9866else : 9867tier = tier_pick (ram ,low_ram_vram (gpu )) 9868rec_fam = STRIX_HALO_FAMILY if strix_halo_recommends (gpu ,ram )and STRIX_HALO_FAMILY in fams else tier [0 ]if tier and tier [0 ]in fams else fams [0 ] 9869for i ,f in enumerate (fams ,1 ): 9870d = FAMILIES [f ] 9871say (f" { i } ) { d [ 'title' ]:20s } { d [ 'by' ] } - { d [ 'about' ] } " + (" [experimental]" if d .get ("experimental" )else "" ) 9872+ family_menu_note (f ,hip ,gpu ,avx2 ,avx512 ) 9873+ (f" (recommended for Strix Halo: { STRIX_HALO_MODEL } )" if f == rec_fam and rec_fam != fams [0 ]else "" )) 9874rest = [* (f for f in OWN_PATH_FAMILIES if not OWN_PATH_FAMILIES [f ].get ("feed" )), 9875* (f for f in OWN_PATH_FAMILIES if OWN_PATH_FAMILIES [f ].get ("feed" )),* feed_late ] 9876for j ,f in enumerate (rest ,len (fams )+ 1 ):# families with an engine path of their own 9877d = {** FAMILIES ,** OWN_PATH_FAMILIES }[f ] 9878say (f" { j } ) { d [ 'title' ]:20s } { d [ 'by' ] } - { d [ 'about' ] } [new]" + (f" ( { FEED_UNAVAILABLE [ f ][ 'reason' ] } )" if f in FEED_UNAVAILABLE else "" )) 9879for u in FEED_UNAVAILABLE .values ():# a feed model this engine does not run: said, never offered (unless the owner's rule allows it, above) 9880if not u .get ("allowed" ): 9881say (f" -) { u [ 'title' ]:20s } { u [ 'by' ] } - { u [ 'reason' ] } " ) 9882allf = fams + rest 9883if tier_note (ram ,low_ram_vram (gpu ))and rec_fam == "swift" : 9884say (" " + tier_note (ram ,low_ram_vram (gpu ))) 9885family = allf [int (ask ("Which model?" , [str (i )for i in range (1 ,len (allf )+ 1 )], 9886str (allf .index (rec_fam )+ 1 ),a .yes ))- 1 ] 9887if family in OWN_PATH_FAMILIES :# Qwen3.6: its own engine path, its own steps 2-7 9888return install_own_path (a ,family ,gpu ,hip ,amd ,cuda_tk ,multi ,port ,ram ,adopted ) 9889fam = FAMILIES [family ] 9890SHAPE_ENGINE .clear () 9891if fam .get ("shape" ):# a feed model of its own shape: its own engine component (strata_control/shape_engine.py) 9892SHAPE_ENGINE ["shape" ],SHAPE_ENGINE ["title" ]= fam ["shape" ],fam .get ("title" ) 9893if fam .get ("ready" )and hip : 9894# not a risk the user could take: the HIP engine has no NVFP4 expert kernels at all, so it would not start 9895fail (f" { fam [ 'title' ] } runs on NVIDIA cards only: the AMD engine has no NVFP4 kernels" , 9896"UD-IQ4_XS is about the same size and runs on AMD: --family unsloth --model UD-IQ4_XS" ) 9897if fam .get ("ready" )and a .gguf_dir : 9898warn (f"--gguf-dir does not apply to { fam [ 'title' ] } : its files are ready-made packs, not GGUF shards" ) 9899a .gguf_dir = None 9900ok (f"model: { fam [ 'title' ] } " ) 9901if fam .get ("feed" )and fam .get ("drafter" )== "none" and a .mtp is None : 9902a .mtp = "off" # the feed says this model has no draft layer: the Flash-Next one (fetched below for every qwen4exp model) is not its own 9903a .feed_no_drafter = True # and no drafter at its starts either: the run config says "drafting": "off" (setup_config; APP-LIN 0.2.14) 9904say (" The model list says this model has no draft layer (MTP), so none is fetched or used." ) 9905if fam .get ("ready" )and nvfp4_cpu_note (avx2 ,avx512 ):# #2347: a note (the AVX2 rows work), not a refusal 9906warn (nvfp4_cpu_note (avx2 ,avx512 )) 9907if fam .get ("license" ): 9908say (f" Its license: { fam [ 'license' ] } " ) 9909say () 9910names = [m for m in MODELS if family in MODELS [m ].get ("families" , ("qwen" ,"swift" ))] 9911names .sort (key = lambda m :bool (MODELS [m ].get ("experimental" )))# an experimental size last, never the default 9912if a .model and a .model not in names : 9913# #444: say which family has that size, and (with --gguf-dir) which files Strata can run at all 9914elsewhere_fams = [f for f in FAMILIES if f in MODELS [a .model ].get ("families" , ("qwen" ,"swift" ))] 9915fail (f" { fam [ 'title' ] } has no { a . model } model file" ,"choose one of: " + ", " .join (names ) 9916+ (f" (or { a . model } : " + ", " .join (f"--family { f } --model { a . model } " for f in elsewhere_fams )+ ")" 9917if elsewhere_fams else "" ) 9918+ (f".\n { SUPPORTED_GGUFS } " if a .gguf_dir else "" )) 9919installed = installed_size (family ,names ,have ) 9920for i ,m in enumerate (names ,1 ): 9921d = MODELS [m ] 9922fit = f" <- { model_fit_label ( m , ram , gpu ) } " # "fits" or "may run slower": the weight files against the RAM and the card's memory together 9923if d .get ("mem_total" ):# Gyro: the download includes the n-gram table, the memory figure does not 9924say (f" { i } ) { m } { size_tag ( family , m , installed ) } { d [ 'about' ] } ; download { d [ 'download_gb' ]:.1f } GB " 9925f"(the n-gram table is in the file), memory { d [ 'ram_gb' ] } GB { fit } " ) 9926continue 9927if d .get ("budget" ): 9928keeps = (f"~ { resident_budget_gib ( m , ram ) } GB" if unsloth_budget (m ,ram ,gpu ,a .resident_budget_gib ) 9929else "all" ) 9930say (f" { i } ) { m } { size_tag ( family , m , installed ) } { d [ 'about' ] } ; download { d [ 'download_gb' ]:.0f } GB, keeps { keeps } of its " 9931f" { d [ 'arena_gb' ]:.0f } GB of experts in RAM { fit } " ) 9932continue 9933say (f" { i } ) { m :8s } { size_tag ( family , m , installed ) } { d [ 'about' ] } ; download { d [ 'download_gb' ]:.0f } GB, uses ~ { d [ 'arena_gb' ]:.0f } GB of RAM { fit } " ) 9934rec = str (names .index (installed or recommended_size (family ,names ,ram ,low_ram_vram (gpu )))+ 1 ) 9935model = a .model or names [int (ask ("Which size?" , [str (i )for i in range (1 ,len (names )+ 1 )],rec ,a .yes ))- 1 ] 9936budget ,q4_split = None ,False 9937in_budget = bool (MODELS [model ].get ("budget" ))and unsloth_budget (model ,ram ,gpu ,a .resident_budget_gib ) 9938if MODELS [model ].get ("budget" ): 9939# Unsloth's files: every expert in RAM where they fit with UNSLOTH_RESIDENT_BESIDE_GB beside them (Phase 2, 9940# unsloth_budget), as ISTA's. Else a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM 9941# mode (no experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode had no layer split) 9942# unless the RAM holds the GGUFs and 24 GB more: then several, without the budget, if asked for (#498). #642: 9943# from RESIDENT_SPLIT_ENGINE several GPUs, when asked for, keep the budget (unsloth_together) 9944if MODELS [model ].get ("experimental" ): 9945warn (f" { model } is EXPERIMENTAL (docs/UNSLOTH_Q4.md)" + ( 9946": most of its experts are read from the SSD while it answers, so it is several times slower than the " 9947"2-3-bit models" if in_budget else "" )+ "; quality checked against llama.cpp" ) 9948if hip and MODELS [model ].get ("nvidia_only" ): 9949# #429 (jkuepker): checked before the 111 GB download. The HIP engine has no prompt kernels for its 9950# Q4_K / Q5_K experts (STRATA_MMQ_KQUANTS is CUDA-only) and it has not been run on AMD: asked, not refused 9951confirm_risk (f" { model } has not been run on AMD cards yet: its prompt kernels are NVIDIA-only, so on " 9952f" { gpu_name ( gpu ) } long prompts read much more slowly, and it may not work at all" , 9953bool (a .model ),a .yes ,f" { model } is NVIDIA-only so far" ,"choose one of the 2-3-bit models, " 9954f"or --model { model } --yes to try it on AMD anyway" ," Try it anyway?" ) 9955warn (f"installing { model } on an AMD card, as you chose (please report how it runs)" ) 9956if ram < MODELS [model ]["ram_gb" ]and model_fit_label (model ,ram ,gpu )!= "fits" : 9957have = resident_budget_gib (model ,ram ) 9958total = int (MODELS [model ]["arena_gb" ]/ 1.073741824 ) 9959confirm_risk (f" { model } needs { MODELS [ model ][ 'ram_gb' ] } GB of RAM or more; this PC has { ram :.0f } GB: " 9960f"it would keep { have } GiB of its { total } GiB of experts in RAM and read the other " 9961f" { total - have } GiB from the SSD while it answers (single-digit tokens/s on most SSDs), and " 9962"it may run out of RAM" ,bool (a .model ),a .yes , 9963f" { model } needs { MODELS [ model ][ 'ram_gb' ] } GB of RAM or more; this PC has { ram :.0f } GB" , 9964f"choose a smaller size, or --model { model } --yes to install it anyway" ," Install it anyway?" ) 9965warn (f"installing { model } with { ram :.0f } GB of RAM, as you chose" ) 9966if in_budget : 9967budget = budget_choice (model ,ram ,a .resident_budget_gib ) 9968if multi and not unsloth_together (a ,model ,ram ,fallback_card (a ,gpu ,chosen ),chosen ): 9969gpu = fallback_card (a ,gpu ,chosen ) 9970multi ,sel ,chosen = [], [gpu ["index" ]], [gpu ] 9971q4_split = bool (multi )and not resident_split ()# #498: on several GPUs without the RAM budget (#642: kept) 9972if not q4_split : 9973ok (f"RAM budget: { budget :g } GiB of { model } 's experts in RAM, the rest read from the model files on the SSD" ) 9974else : 9975ok (f"all { MODELS [ model ][ 'arena_gb' ]:.0f } GB of { model } 's experts in RAM (they and " 9976f" { UNSLOTH_RESIDENT_BESIDE_GB } GiB more fit this PC's { ram :.0f } GB; --resident-budget-gib N keeps only " 9977"N GiB of them)" ) 9978if a .low_ram not in ("auto" ,"off" ): 9979warn (f"--low-ram { a . low_ram } does not apply to { model } : it always reads part of its experts from the files" ) 9980elif a .resident_budget_gib is not None : 9981warn (f"--resident-budget-gib is for UD-Q4_K_XL and UD-IQ4_XS: { model } keeps all of its experts in RAM or in " 9982"the low-RAM mode" ) 9983low_ram = low_ram_wanted (model ,ram ,a .low_ram ) 9984# #642: the engines from RESIDENT_SPLIT_ENGINE run the low-RAM mode on the chosen cards as on one (decided below) 9985if low_ram and multi and not resident_split ()and not low_ram_together (a ,model ,ram ,fallback_card (a ,gpu ,chosen ),chosen ): 9986gpu = fallback_card (a ,gpu ,chosen ) 9987multi ,sel ,chosen = [], [gpu ["index" ]], [gpu ] 9988# (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one 9989# before RESIDENT_SPLIT_ENGINE, #642) 9990if MODELS [model ].get ("mem_total" ): 9991if mem_have (model ,ram ,gpu ["vram_gb" ])< MODELS [model ]["ram_gb" ]:# recommend, never force: a warning 9992warn (f" { model } needs { MODELS [ model ][ 'ram_gb' ] } GB of VRAM and RAM together; this PC has " 9993f" { mem_have ( model , ram , gpu [ 'vram_gb' ]):.0f } GB ( { ram :.0f } GB RAM + { gpu [ 'vram_gb' ]:.0f } GB VRAM): it " 9994"may be slow, run out of memory or not start" ) 9995elif not low_ram and budget is None and ram < MODELS [model ]["ram_gb" ]- 4 : 9996confirm_paging (model ,ram ,a .low_ram ,a .yes ,bool (a .model )) 9997ok (f"size: { model } " ) 9998from strata_control import gpu_fit 9999_q4 = gpu_fit .strix_q4_stall_note (model , [gpu ]if isinstance (gpu ,dict )else (gpu or []))# REMOVE with the Strix stall fix (see gpu_fit.STRIX_Q4_NOTE) 10000if _q4 : 10001warn (_q4 ) 10002if MODELS [model ].get ("license" ):# the ready-made packs: each size has its own license 10003say (f" Its license: { MODELS [ model ][ 'license' ] } " ) 10004tag = fam ["tag" ]+ model # names of the pack, config and start script 10005small = min (x ["vram_gb" ]for x in chosen )# each card keeps its layers' KV of the whole context 10006rec_ctx = 131072 # 128K on every card (owner, 2026-11-01); a card it leaves little room on is warned about below, never lowered 10007# #406: the RAM rule is part of the recommendation (the smaller of the two), no longer a cap over the user's choice 10008rec_ctx = min (rec_ctx ,ram_ctx (model ,ram ,low_ram )) 10009if a .context : 10010ctx = a .context 10011else : 10012say () 10013say (" Context length = how much text the model can see at once (your chat, files, tool output)." ) 10014say (" Longer needs more VRAM for it, so fewer experts fit on the GPU:" ) 10015for i ,c in enumerate (CONTEXTS ,1 ): 10016need_c = ctx_ram_need (model ,c ,low_ram ) 10017note = (" (recommended for your GPU)" if c == rec_ctx else "" )+ \ 10018 (" (experimental: setup adds rope scaling)" if c > 262144 else "" )+ \ 10019 (f" (needs ~ { need_c :.0f } GB RAM, this PC has { ram :.0f } : may run out of memory)" 10020if c > 131072 and need_c is not None and need_c > ram else "" ) 10021say (f" { i } ) { c // 1024 } K tokens { note } " ) 10022ctx = CONTEXTS [int (ask ("Context?" , [str (i )for i in range (1 ,len (CONTEXTS )+ 1 )], 10023str (CONTEXTS .index (rec_ctx )+ 1 ),a .yes ))- 1 ] 10024# #406 #364: a context past the RAM rule (an explicit --context, a pick in the list, or the earlier install's) is 10025# kept, with what it risks. It used to become 128K: users ran 256K fine where setup's estimate said no. 10026need_gb = ctx_ram_need (model ,ctx ,low_ram ) 10027if need_gb is not None and ram < need_gb and ctx > 131072 : 10028warn (f" { ctx // 1024 } K with { model } needs ~ { need_gb :.0f } GB of RAM by setup's estimate " 10029f"( { MODELS [ model ][ 'arena_gb' ]:.0f } GB of experts + the context + room for the rest); this PC has " 10030f" { ram :.0f } . Kept as you chose: it may be slower or run out of RAM under load. { rec_ctx // 1024 } K is the " 10031"recommended size." ) 10032scaling = a .rope_scaling 10033if ctx > 262144 and scaling is None and not a .yes : 10034# the interactive path: one question, yarn preselected (llama.cpp's extension method, recall-tested 10035# here at 512K). With --yes nothing prints: resolve_rope takes yarn below and the ok() line says so. 10036say () 10037say (f" A { ctx // 1024 } K context runs the model past its trained 262,144 positions: the rotary angles" ) 10038say (" get rescaled (llama.cpp's RoPE extension). yarn keeps the trained angles on the high-frequency" ) 10039say (" pairs and corrects the magnitudes; linear shrinks every angle. Override any time with" ) 10040say (" --rope-scaling." ) 10041scaling = ask ("RoPE extension method?" , ["yarn" ,"linear" ],"yarn" ,a .yes ) 10042try : 10043scaling ,rope_scale = resolve_rope (ctx ,scaling ,a .rope_scale ) 10044except ValueError as e : 10045fail (str (e )) 10046if scaling is not None : 10047origin = ("final context / trained 262144; override with --rope-scale" if a .rope_scale is None 10048else "as requested" ) 10049ok (f"rope scaling: { scaling } , factor { rope_scale :g } ( { origin } )" ) 10050ok (f"context: { ctx } tokens" ) 10051# the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21) 10052kv = "fp16" if ctx <= 8192 else (a .kv or "int8" ) 10053if ctx > 8192 and not a .kv and not a .yes : 10054say () 10055say (" KV cache precision (the model's memory of the conversation):" ) 10056say (" 1) 8-bit (recommended: what every published number was measured with)" ) 10057say (" 2) 4-bit half the memory (about 4% faster at 128K), but measurably less precise on long" ) 10058say (" documents; long-context lookups (needle tests) still pass" ) 10059kv = ["int8" ,"q4_0" ][int (ask ("KV cache?" , ["1" ,"2" ],"1" ,a .yes ))- 1 ] 10060if ctx > 8192 : 10061ok (f"KV cache: { KV_WORDS . get ( kv , kv ) } " ) 10062if MODELS [model ].get ("vision" ,fam .get ("vision" ))is False :# UD-IQ4_XS: images, unlike UD-Q4_K_XL 10063vision = "none" 10064if a .vision not in (None ,"no" ,"none" ): 10065warn (f"images are not available with { model } yet: off" ) 10066elif hip : 10067# Unsloth's files on AMD: pictures on by default, the reader by the 24 GB rule (hip_vision; docs/QUANTS.md) 10068vision = hip_vision (a .vision if a .vision is not None or not images_default (model ,family ,ram ,gpu ) 10069else "yes" ,float ((gpu or {}).get ("vram_gb" )or 0.0 )) 10070elif a .vision : 10071vision = flash_vision_encoder (a .vision ,gpu )if a .vision != "no" else "none" 10072vision = "none" if vision in ("no" ,"none" )else vision 10073else : 10074small = 0 < float (gpu .get ("vram_gb" )or 0.0 )< IMAGES_GPU_ENCODER_MIN_VRAM_GB 10075say () 10076say (" Images: the model can also read pictures (screenshots, photos, scanned pages). This adds a 0.9 GB" ) 10077if small : 10078say (" download. On a card under 24 GB the encoder runs on the CPU (a few seconds per picture, nothing taken" ) 10079say (" from the GPU, pictures read at up to 300 tokens; --vision-tokens 1024 for more detail): the GPU" ) 10080say (" encoder keeps ~1.4 GB of VRAM free, which costs 3-5% of text speed on 16 GB cards (measured) and" ) 10081say (" more on some PCs. --vision gpu if you want pictures in under a second." ) 10082else : 10083say (" download and keeps ~1.4 GB of VRAM free for the image encoder, so text is a few % slower." ) 10084# on by default wherever the model can read pictures (the reader by the 24 GB rule) 10085default = "y" if images_default (model ,family ,ram ,gpu )else "n" 10086vision = flash_vision_encoder ("yes" ,gpu )if ask ("Do you want images?" , ["y" ,"n" ],default ,a .yes )== "y" else "none" 10087ok ("images: " + {"none" :"off" ,"gpu" :"on" ,"cpu" :"on (encoder on the CPU)" }[vision ]) 10088if vision != "none" and MODELS [model ].get ("vision_untested" ): 10089warn (f"images with { model } are untested: users report them working, but we have not run this file with " 10090"images (#967); tell us if the answers look wrong" ) 10091# The low-RAM mode's two variants. resident: the experts the GPU's cache does not hold (and, as far as RAM allows, 10092# the ones the prompt path borrows cache room from) are copied from the pack's experts.bin into RAM once, so 10093# nothing is read from the SSD while it answers (engine 0.1.30, --resident-experts; the engine falls back to mmap 10094# with a warning when they do not fit the RAM it finds free). mmap: they are read through the OS file cache. 10095# The GPU's share: its VRAM less the dense weights and buffers, this context's KV cache and the image encoder's room. 10096resident = False 10097if low_ram and not fam .get ("ready" ):# NVFP4's packs: the RAM-budget mode instead (step 7) 10098arena = MODELS [model ]["arena_gb" ] 10099vram = low_ram_vram (gpu )- (VISION [vision ]["reserve_mib" ]/ 1024 if vision != "none" else 0 ) 10100with_mtp = a .mtp != "off" # the draft layer's ~1 GB comes out of the expert cache 10101share = low_ram_gpu_share (model ,vram ,ctx ,kv ,with_mtp ) 10102rest = arena - low_ram_gpu_gb (model ,vram ,ctx ,kv ,with_mtp ) 10103resident = a .low_ram == "resident" or (a .low_ram != "mmap" and low_ram_resident (model ,ram ,vram ,ctx ,kv ,with_mtp )) 10104if multi :# every chosen card's share (the image encoder on the main one); #364 #384: the mapped variant 10105held = min (arena ,low_ram_gpu_gb (model ,vram ,ctx ,kv ,with_mtp )+ 10106sum (low_ram_gpu_gb (model ,low_ram_vram (x ),ctx ,kv ,with_mtp )for x in chosen [1 :])) 10107share ,rest = held / arena ,arena - held 10108# #642: the resident variant on a split, by the same rule as on one card - what no card holds fits the RAM 10109resident = resident_split ()and (a .low_ram == "resident" or 10110 (a .low_ram != "mmap" and ram >= rest + LOW_RAM_HEADROOM_GB )) 10111if resident : 10112ok (f"low-RAM mode on { len ( chosen ) } GPUs: they hold ~ { 100 * share :.0f } % of { model } 's experts " 10113f"( { arena :.0f } GB) and the other ~ { rest :.0f } GB stay in RAM ( { ram :.0f } GB), read once from a copy " 10114"in the model folder" ) 10115else : 10116ok (f"low-RAM mode on { len ( chosen ) } GPUs: { model } 's experts ( { arena :.0f } GB) are read from the model " 10117f"folder through the OS file cache instead of a copy in RAM ( { ram :.0f } GB); the GPUs hold " 10118f"~ { 100 * share :.0f } % of them" ) 10119if share < 0.6 : 10120warn ("most of the experts are read from the SSD while it answers: expect it to be much slower " 10121"than with enough RAM (a faster SSD and a smaller size help)" ) 10122elif resident : 10123ok (f"low-RAM mode: the GPU holds ~ { 100 * share :.0f } % of { model } 's experts ( { arena :.0f } GB) and the other " 10124f"~ { rest :.0f } GB stay in RAM ( { ram :.0f } GB), read once from a copy in the model folder" ) 10125else : 10126ok (f"low-RAM mode: { model } 's experts ( { arena :.0f } GB) are read from the model folder through the OS file " 10127f"cache instead of a copy in RAM ( { ram :.0f } GB); the GPU holds ~ { 100 * share :.0f } % of them" ) 10128if share < 0.6 : 10129warn ("most of the experts are read from the SSD while it answers: expect it to be much slower than " 10130"with enough RAM (a faster SSD and a smaller size help)" ) 10131# EXPERIMENTAL: the experimental-speed-projection control vector (data/experimental-speed-projection), off unless 10132# chosen here; with it loaded, the web app and the API switch it off per request 10133esp = None 10134esp_choice = (a .experimental_speed_projection or "" ).strip () 10135if family in ("qwen" ,"coder" ):# the Coder: the same model's residual stream 10136if not esp_choice : 10137say () 10138say (" EXPERIMENTAL - speed projection: a small control vector applied while the model runs (layers 4-44)." ) 10139say (" It changes how the model answers: its package describes it as a refusal-direction projection (the" ) 10140say (" model declines far fewer requests). Off unless you choose it; when on, the web app can switch it off" ) 10141say (" per chat. Details: data/experimental-speed-projection/README.md" ) 10142esp_choice = "on" if ask ("Turn on the experimental speed projection?" , ["y" ,"n" ],"n" ,a .yes )== "y" else "off" 10143if esp_choice .lower ()not in ("off" ,"no" ,"n" ,"0" ): 10144esp = ESP_VECTOR if esp_choice .lower ()in ("on" ,"yes" ,"y" ,"1" )else Path (esp_choice ).expanduser ().resolve () 10145if not esp .is_file (): 10146fail (f"the experimental speed projection's vector is missing: { esp } " ) 10147ok ("experimental speed projection: " + ("ON (experimental)" if esp else "off" )) 10148elif esp_choice .lower ()not in ("" ,"off" ,"no" ,"n" ,"0" ): 10149warn ("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off" 10150if family == "swift" else f"the experimental speed projection is not tested with { model } : left off" ) 10151ready = bool (fam .get ("ready" ))# NVFP4: ready-made packs (NVFP4_REPOS), no GGUF shards 10152if ready : 10153models_dir = Path (a .models_dir ) 10154for r in elsewhere :# already downloaded and checked in a Strata folder elsewhere 10155if all (ready_verified (ready_where (r / "models" ,f ),f [5 ])for f in ready_needed (model ,r / "models" )): 10156models_dir = r / "models" 10157ok (f"model files found in { models_dir } " ) 10158break 10159shards = [ready_where (models_dir ,f )for f in ready_files (model )] 10160else : 10161models_dir = Path (a .gguf_dir )if a .gguf_dir else Path (a .models_dir )/ tag 10162shards = gguf_dir_shards (models_dir ,fam ,model )if a .gguf_dir else \ 10163 [models_dir / model_file (fam ,model ,i )for i in range (1 ,model_shards (fam ,model )+ 1 )] 10164problem = gguf_dir_problem (models_dir ,shards [0 ],fam ,model )if a .gguf_dir else None 10165if problem :# #444: files Strata cannot run, or another choice's files 10166fail (* problem ) 10167if not ready and not a .gguf_dir and not all (sh .exists ()and done (sh )for sh in shards ): 10168for r in elsewhere :# already downloaded in a Strata folder on another drive 10169cand = [r / "models" / tag / sh .name for sh in shards ] 10170if all (c .exists ()and done (c )for c in cand ): 10171models_dir ,shards = cand [0 ].parent ,cand 10172ok (f"model files found in { models_dir } " ) 10173break 10174mark_whole_unless_pinned ([]if ready else shards ,model_hf (fam ,model )if fam .get ("hf" )else None ,bool (a .gguf_dir ))# #173: a whole file copied in by hand has no finish mark 10175have_model = all (ready_verified (ready_where (models_dir ,f ),f [5 ])for f in ready_needed (model ,models_dir ))if ready else \ 10176all (s .exists ()and (done (s )or a .gguf_dir )for s in shards ) 10177# #425 (jctaborda): a download that resumes needs room only for what is still missing - the finished shards and 10178# the .part files already on the disk count 10179on_disk = sum (f .stat ().st_size for s in shards for f in (s ,s .with_name (s .name + ".part" ))if f .is_file ())/ 1e9 10180to_fetch = 0 if a .gguf_dir or have_model else max (MODELS [model ]["download_gb" ]- on_disk ,0 ) 10181if ready and not have_model and MODELS [model ].get ("prepare" )and prepared_done (model ,models_dir ): 10182to_fetch = sum (f [4 ]for f in ready_needed (model ,models_dir ) 10183if not ready_verified (ready_where (models_dir ,f ),f [5 ]))/ 1e9 # the small files only 10184# count only what step 6 will still write: a pack whose experts.bin is already there (the AVX-512 Q2_0 10185# conversion, or the low-RAM mode's copy) and an existing MTP draft layer need no new room 10186pack_now = find_in (roots ,f"packs/ { tag . lower () } " )or data / "packs" / tag .lower () 10187pack_bin = ready or ((pack_now / "experts.bin" ).exists ()and (pack_now / "index.txt" ).exists ())# ready: in the download 10188mtp_have = find_in (roots ,"mtp/rt/experts.bin" )is not None 10189q2_avx = model == "Q2_0" and avx512 and family == "qwen" 10190prep_gb = MODELS [model ].get ("prepare_gb" ,0.0 )if ready and MODELS [model ].get ("prepare" )and \ 10191not prepared_done (model ,models_dir )else 0.0 10192margin = 2 if mtp_have else 8 # working room: a guess, not bytes that will be written 10193mtp_fetch = 5.2 if (not mtp_have and not ready and a .mtp != "off" and getattr (a ,"drafter" ,None )!= "dflash2" )else 0.0 # the draft layer's tensors step 6 fetches (strata_control.discovery.MTP_FETCH_GB) 10194copy_gb = MODELS [model ]["arena_gb" ]+ 1 if low_ram and not q2_avx and not pack_bin else 0 # the low-RAM mode's copy of the experts (goes to the data folder's packs) 10195real = to_fetch + prep_gb + mtp_fetch + \ 10196 (40 if q2_avx and not pack_bin else 0 )+ (1 if vision != "none" else 0 )+ copy_gb 10197need = real + margin 10198free_now = free_gb (models_dir ) 10199problem = disk_room_problem (models_dir ,pack_now ,real - copy_gb ,copy_gb , 10200 (f" ( { on_disk :.0f } GB of the model is already there)" if on_disk >= 1 and not have_model else "" )) 10201if problem : 10202fail (* problem ) 10203if free_now < need : 10204warn (f"little free disk space in { models_dir } : { free_now :.0f } GB free for about { real :.0f } GB of files. " 10205"Setup goes on and should fit; free up space if it stops" ) 10206 10207# ---- 3. python packages 10208step (3 ,"Python packages" ) 10209pip_install (runtime_packages (), 10210"numpy, jinja2, regex, pyyaml, tqdm, requests, pillow, psutil, textual (the screens)" ) 10211 10212# ---- 4. the engine 10213step (4 ,"the Strata engine" ) 10214llama ,eng ,meta ,lib_dirs ,gpu ,vision = engine_step (a ,gpu ,hip ,amd ,cuda_tk ,vision ) 10215reader = None 10216if hip and vision != "none" :# AMD: the engine folder's reader (GPU, else CPU), settled now the engine is known 10217vision ,reader = hip_reader (eng ,vision ,gpu ) 10218if (ready or family == "gyro" )and meta .get ("source" )!= "local" and \ 10219tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ())< MODELS [model ]["engine" ]: 10220# a ready-made engine from before NVFP4 / Gyro cannot read these experts: one compiled from this source can 10221warn (f"the ready-made engine { meta . get ( 'version' ) } has no { 'NVFP4' if ready else 'Gyro' } experts yet: compiling " 10222"the engine from this source" ) 10223eng = build_engine (gpu ,vision ,a .yes ,llama ,toolkit = cuda_tk ) 10224meta = json .loads ((eng / "BUILD.json" ).read_text (encoding = "utf-8" )) 10225lib_dirs = meta .get ("lib_dirs" )or meta .get ("cuda_dirs" )or cuda_lib_dirs (cuda_tk ) 10226engine_ver = tuple (int (x )for x in str (meta .get ("version" ,"0" )).split ("." )[:4 ]if x .isdigit ()) 10227need_engine = MODELS [model ].get ("engine" ,UNSLOTH_ENGINE ) 10228# checked before the 94-188 GB download 10229if (MODELS [model ].get ("budget" )or family == "gyro" )and engine_ver < need_engine : 10230fail (f" { model } needs engine { '.' . join ( map ( str , need_engine )) } or newer; this one is { meta . get ( 'version' ) } " , 10231"update Strata (or compile the engine with --build) and run setup again" ) 10232ok ("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: { eng / EXE } " ) 10233 10234# ---- 5. the model files 10235step (5 ,f"downloading { fam [ 'title' ] } { model } " ) 10236if ready :# pinned files of the pack's repository, each SHA-256-checked 10237say (f" The model files go in { models_dir / MODELS [ model ][ 'repo' ]. replace ( '/' , '--' ) } " ) 10238if model_source ()== "modelscope" : 10239warn ("these packs are on Hugging Face only: downloading them from " + hf_endpoint ()) 10240ready_fetch (model ,models_dir ) 10241elif not a .gguf_dir : 10242missing = [s .name for s in shards if not (s .exists ()and done (s ))] 10243if missing :# #495: files downloaded by hand go here, or --gguf-dir 10244say (f" The model files go in { models_dir } " ) 10245say (f" Files you already have: put them here with their original names ( { ', ' . join ( missing ) } ), or use " 10246"--gguf-dir <their folder>." ) 10247if model_source ()== "modelscope" : 10248say (f" Downloading from ModelScope ( { ms_endpoint () } ); --source huggingface downloads from Hugging Face" ) 10249warn ("ModelScope serves the repositories' current files, not the pinned revisions: each file is checked " 10250"against the SHA-256 ModelScope itself publishes (self-attested); the MTP tensors against the " 10251"pinned checkpoint's own hashes" ) 10252elif hf_endpoint ()!= HF_DEFAULT : 10253say (f" Downloading from { hf_endpoint () } (HF_ENDPOINT)" ) 10254for s in shards : 10255if s .exists ()and done (s ): 10256ok (f" { s . name } already downloaded" ) 10257continue 10258# the original's shard 2 is the same file for all its sizes and the Coder: reuse one that is already here 10259other = [p for p in Path (a .models_dir ).glob ("*/Qwen3.8-Flash-Next-GSQ-RCO-*-00002-of-00002.gguf" )if done (p )] 10260if family in ("qwen" ,"coder" )and s .name .endswith ("00002-of-00002.gguf" )and other and not s .exists (): 10261try : 10262os .link (other [0 ],s ) 10263mark (s ) 10264ok (f" { s . name } shared with { other [ 0 ]. parent . name } (identical file)" ) 10265continue 10266except OSError : 10267pass 10268download (model_hf (fam ,model )+ s .name ,s ) 10269if not ready : 10270check_shards (shards ) 10271for s in ([]if ready else shards ):# the Unsloth files: pinned sizes and SHA-256 10272if s .name in fam .get ("sha256" , {}): 10273verify_sha256 (s ,* fam_pin (fam ,s ),own = bool (a .gguf_dir )) 10274ok ("model files present" ) 10275mmproj = Path (a .models_dir )/ fam .get ("mmproj" ,MMPROJ ) 10276if not mmproj .exists ():# an earlier install's copy (the same file for every family) 10277mmproj = find_in (roots ,f"models/ { fam . get ( 'mmproj' , MMPROJ ) } " )or mmproj # a feed model without a picture reader has no fam["mmproj"] 10278if vision != "none" : 10279# the person's own folder (or the one above it) has the pinned picture file: used where it is ('near'); a verified Unsloth mmproj-F16.gguf they 10280# already have is used when no pinned file is anywhere ('alt'); else the pinned file is downloaded 10281kind ,mmproj = resolve_reader (fam ["mmproj" ],mmproj ,a .models_dir ,roots ,a .gguf_dir , 10282 (fam .get ("mmproj_sha256" )or ISTA_FILES .get (fam ["mmproj" ])or (None ,))[0 ]) 10283if kind == "fetch" : 10284download (fam ["mmproj_hf" ]+ fam ["mmproj" ],mmproj ,"vision encoder" ) 10285if fam .get ("mmproj_sha256" )and kind != "alt" :# the NVFP4 family pins it by size and SHA-256 too 10286verify_sha256 (mmproj ,* fam ["mmproj_sha256" ]) 10287ok (f"vision encoder: { mmproj } " + (" (Unsloth's mmproj-F16.gguf, SHA-256 checked)" if kind == "alt" else "" )) 10288if vision == "cpu" and "BF16" in mmproj .name :# a tip only (recommend, never force; #625) 10289say (" tip: on the CPU a Q8_0 copy of this encoder is a third smaller and about as exact (embedding " 10290"cosine 0.999 vs BF16); see 'A Q8_0 encoder' in docs/DETAILS.md" ) 10291 10292# ---- 6. the pack and the MTP draft layer 10293step (6 ,"preparing the model for Strata" ) 10294pack = find_in (roots ,f"packs/ { tag . lower () } " )or data / "packs" / tag .lower () 10295env = dict (os .environ ,** gguf_py_env ()) 10296prepared = bool (ready and MODELS [model ].get ("prepare" )) 10297if prepared and not prepared_done (model ,models_dir ): 10298say (" NVIDIA's checkpoint is turned into a Strata pack on this PC (once; 20-40 minutes, reads the 102 GB, writes about" ) 10299say (f" { MODELS [ model ][ 'prepare_gb' ]:.0f } GB). Nothing of NVIDIA's weights leaves this PC." ) 10300ensure_nvfp4_local_packages () 10301run ([sys .executable ,str (ROOT / "tools" / "nvfp4_local_pack.py" ),"prepare" , 10302"--model" ,str (ready_where (models_dir , ("src" ,MODELS [model ]["repo" ],"" ,"" ,0 ,"" ))), 10303"--out" ,str (prepared_dir (model ,models_dir ))],env = env ) 10304ok ("prepared; the downloaded checkpoint is no longer needed and can be deleted to get its 102 GB back: " 10305+ str (ready_where (models_dir , ("src" ,MODELS [model ]["repo" ],"" ,"" ,0 ,"" )))) 10306if ready :# the downloaded pack folder is the pack, experts.bin included 10307pack = ready_paths (model ,models_dir )["pack" ] 10308elif model == "Q2_0" and avx512 and family == "qwen" : 10309# the Q2_0 experts repacked for the AVX-512 kernel (the measured speed): a one-time ~40 GB conversion 10310if not (pack / "index.txt" ).exists ()or not (pack / "experts.bin" ).exists ():# index.txt is written last 10311say (" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ..." ) 10312run ([sys .executable ,str (ROOT / "tools" / "strata_pack.py" ),"build" ,"--gguf" ,str (shards [0 ]), 10313"--out" ,str (pack ),"--skip-hash" ,"--force" ],env = env )# --force: #634 refuses an occupied pack 10314run ([sys .executable ,str (ROOT / "tools" / "pack_index.py" ),"--pack" ,str (pack )],env = env ) 10315if not (pack / "tokenizer" / "vocab.json" ).exists (): 10316run ([sys .executable ,str (ROOT / "tools" / "strata_tokenizer.py" ),"--gguf" ,str (shards [0 ]), 10317"--out" ,str (pack )],env = env )# writes <pack>/tokenizer/ 10318elif not (pack / "native_experts.txt" ).exists ()or not (pack / "tokenizer" / "vocab.json" ).exists (): 10319# every tensor as the GGUF stores it; the experts are read from the GGUF at start (seconds to build) 10320# (UD-Q4_K_XL: --compat-bf16 - its Q8_0 hyper-connection projections become BF16, the form the engine reads) 10321run ([sys .executable ,str (ROOT / "tools" / "iq_pack.py" ),"--gguf" ,str (shards [0 ]),"--out" ,str (pack ), 10322* fam .get ("pack_args" , [])],env = env ) 10323if low_ram and not ready and not (pack / "experts.bin" ).exists (): 10324say (f" Writing the experts into one file for the low-RAM mode (one time, { MODELS [ model ][ 'arena_gb' ]:.0f } GB) ..." ) 10325run ([sys .executable ,str (ROOT / "tools" / "iq_pack.py" ),"--gguf" ,str (shards [0 ]),"--out" ,str (pack ), 10326"--experts-bin" ,* fam .get ("pack_args" , [])],env = env )# #3193: Gyro needs --compat-bf16 here too 10327ok (f"model prepared: { pack } " ) 10328mtp = ready_paths (model ,models_dir )["mtp" ]if prepared else \ 10329 (find_in (roots ,"mtp/rt/experts.bin" )or data / "mtp/rt/experts.bin" ).parent .parent 10330rt = mtp / "rt" 10331corrupt = (rt / "experts.bin" ).exists ()and not prepared and mtp_corrupt (mtp ,env ) 10332if corrupt : 10333warn ("some MTP tensors are not the checkpoint's (a download mirror that ignored range requests, #327): " 10334"fetching them again and rebuilding the draft layer" ) 10335if a .mtp == "off" and not (rt / "experts.bin" ).exists (): 10336ok ("the draft layer (MTP) is off: its ~5 GB are not downloaded (`--mtp on` fetches it later)" )# round 8, N3 10337elif getattr (a ,"drafter" ,None )== "dflash2" and not (rt / "experts.bin" ).exists (): 10338ok ("DFlash2 is the drafter: the MTP draft layer's ~5 GB are not downloaded (choosing the MTP later fetches it once)" ) 10339provide_dflash2_vocab (data ,a .draft_vocab or saved_draft_vocab (home ()/ f"strata- { tag . lower () } .json" )or "cjk" ) 10340elif corrupt or not (rt / "experts.bin" ).exists (): 10341say (" The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:" ) 10342say (" only its ~5 GB of MTP tensors are downloaded." ) 10343if fetch_mtp (mtp ,env )is not False :# (False: offline, nothing to pack) 10344run ([sys .executable ,str (ROOT / "tools" / "mtp_pack.py" ),"--src" ,str (mtp ),"--experts" ,"q2_0" , 10345"--out" ,str (mtp / "mtp-q2_0.gguf" )],env = env ) 10346run ([sys .executable ,str (ROOT / "tools" / "mtp_rt.py" ),"--gguf" ,str (mtp / "mtp-q2_0.gguf" ),"--out" ,str (rt )], 10347env = env ) 10348# a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en) 10349draft_vocab = a .draft_vocab or saved_draft_vocab (home ()/ f"strata- { tag . lower () } .json" ) 10350if (rt / "experts.bin" ).exists (): 10351refresh_draft_vocab (rt ,draft_vocab or "cjk" ) 10352ok (f"MTP draft layer: { rt } " ) 10353refresh_dflash2_vocab (data ,draft_vocab or "cjk" )# an existing DFlash2 copy follows the choice too 10354for line in draft_vocab_note (gpu .get ("vram_gb" ,0.0 ),draft_vocab ):# #474: a recommendation, nothing changes 10355say (" " + line ) 10356 10357# ---- 7. the start script 10358step (7 ,"writing the start script" ) 10359sys .path .insert (0 ,str (ROOT / "tools" )) 10360from gguf_reader import GGUFFile # the PLE table's shard: shard 2 (original) or 1 (Swift) 10361if ready :# the dense GGUF as --native and --native-dense-gguf (--native alone would look for a second shard), 10362rp = ready_paths (model ,models_dir )# the FP8 n-gram table, the BF16 token embedding 10363ple = rp ["ple" ] 10364model_args = ["--pack" ,str (pack ),"--native" ,str (rp ["dense" ]),"--native-dense-gguf" ,str (rp ["dense" ]), 10365"--ple-gguf" ,str (ple ),* (["--embd-gguf" ,str (rp ["embd" ])]if "embd" in rp else [])] 10366else : 10367ple = next ((s for s in shards if any (t .name == "per_layer_token_embd.weight" for t in GGUFFile (s ).tensors )),None ) 10368if ple is None : 10369fail ("the model has no per_layer_token_embd tensor (is this a Qwen3.8-Flash-Next GGUF?)" ) 10370# (a 4-shard file: the engine finds the PLE table's shard itself from shard 1, the measured setup) 10371model_args = ["--pack" ,str (pack ),"--native" ,str (shards [0 ]), 10372* (["--ple-gguf" ,str (ple )]if len (shards )<= 2 else [])] 10373from strata_control import setup_config # the seam: the lines that built the run config live in strata_control/setup_config.py 10374_built = setup_config .config_for (setup_config .SetupInputs ( 10375a = a ,adopted = adopted ,chosen = chosen ,cuda_tk = cuda_tk ,draft_vocab = draft_vocab ,eng = eng ,engine_ver = engine_ver ,esp = esp ,fam = fam ,family = family ,gpu = gpu ,hip = hip ,in_budget = in_budget ,lib_dirs = lib_dirs ,low_ram = low_ram ,meta = meta ,mmproj = mmproj ,model = model ,model_args = model_args ,models_dir = models_dir ,multi = multi ,pack = pack ,ple = ple ,port = port ,q4_split = q4_split ,ram = ram ,reader = reader ,ready = ready ,rope_scale = rope_scale ,rt = rt ,scaling = scaling ,shards = shards ,tag = tag ,vision = vision ,ctx = ctx ,kv = kv ,resident = resident ,budget = budget ,GGUFFile = GGUFFile ),sys .modules [__name__ ]) 10376cfg ,cfg_path ,cal ,args ,ctx ,kv ,resident = (_built .cfg ,_built .cfg_path ,_built .cal ,_built .args ,_built .ctx ,_built .kv ,_built .resident ) 10377write_setup_config (cfg_path ,cfg ,adopted if adopted is not None and adopted .name == cfg_path .name else None ,explicit_args (a ), 10378after_carry = (lambda c :uma_cache_guard (c ,model ,gpu ))if gpu .get ("uma" )else None ) 10379script = write_run_script (tag ,cfg_path ,port ,cfg .get ("open_browser" )is not False ) 10380# offered only when someone answers: --yes installs and adopted earlier installs are not held up by it 10381if cal is None and not hip and not a .no_start and not a .yes and ask ( 10382"Tune Strata for this PC now? It measures a few engine settings (about 15-30 minutes, longer on a slow card; the PC is busy " 10383"meanwhile; later: START-HERE --calibrate)" , ["y" ,"n" ],"y" ,a .yes )== "y" : 10384tuned = calibrate_config (cfg_path ) 10385else : 10386tuned = None # not asked for: nothing to repeat below 10387ok (f"start script: { script . name } " ) 10388 10389say () 10390say ("All set." ) 10391say (f" API (OpenAI): http://127.0.0.1: { port } /v1 (any API key; model name: anything)" ) 10392say (f" API (Anthropic): http://127.0.0.1: { port } /v1/messages" ) 10393if a .host and a .host not in ("127.0.0.1" ,"localhost" ): 10394say (f" Other devices: the server window prints this PC's address (http://<IP>: { port } /)" 10395+ ("" if a .api_key else " - no API key set: anyone on your network can use it" )) 10396say (f" Next time: just run { 'START-HERE.bat' if WIN else './setup.sh' } (or { script . name } ) - it starts right away" ) 10397if vision != "none" : 10398say (" Images: send them in the chat page, in chat.py (/image <path>) or over the API" ) 10399if cfg .get ("images" ): 10400say (f" Image generation: POST http://127.0.0.1: { port } /v1/images/generations (OpenAI's images API)" ) 10401if a .parallel is None :# #465: the opt-in, said once (nothing changes) 10402for line in parallel_note (None , [g .get ("vram_gb" ,0.0 )for g in chosen ],MODELS [model ]["arena_gb" ],ctx ,kv , 10403"--kv-resident" in cfg ["args" ]): 10404say (" " + line ) 10405if tuned is False :# #447: a failed tuning is repeated here, not only above 10406say (" Tuning: FAILED (the reason is above): the default settings stay - " 10407f" { 'START-HERE.bat' if WIN else './setup.sh' } --calibrate tries again" ) 10408if a .no_start : 10409return 0 10410# offered only when someone answers (--yes asks nothing), default no; the benchmark starts its own server and stops it 10411if not a .yes and sys .stdin .isatty ()and ask ( 10412"Run a quick benchmark now? It measures this install for about 10 minutes and writes a report you can share " 10413f"(later: { 'BENCH.bat' if WIN else './bench.sh' } )" , ["y" ,"n" ],"n" ,a .yes )== "y" : 10414subprocess .call ([sys .executable ,str (ROOT / "tools" / "strata_bench.py" ),"--config" ,str (cfg_path ),"--port" ,str (port )]) 10415return start (cfg_path ,port ) 10416 10417 10418if __name__ == "__main__" : 10419try : 10420sys .exit (main ()) 10421except acquisition .AcquisitionRefused as e :# a start that would have installed something: said, not done 10422say (f"\n [X] { e } " ) 10423sys .exit (e .exit_code ) 10424except KeyboardInterrupt : 10425say ("\nstopped." ) 10426sys .exit (1 ) 10427