okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-dl99-fixes: the Qwen3.6 first-run download (no engine-race stop, no cancelled engine download, progress to 100%, the picture reader's real figure, the engine-not-ready sentence)361c8d94a

main
628.9 KiB10427 linesraw
1#!/usr/bin/env python3
2"""Strata one-click setup and start (Windows and Linux, NVIDIA or AMD GPUs).
3
4    START-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
13  1. checks your PC: NVIDIA or AMD GPU and driver, RAM, CPU, free disk space
14  2. asks the questions
15  3. installs the Python packages it needs into .venv (numpy, jinja2, ..., and NVIDIA's CUDA libraries)
16  4. gets the Strata engine: a ready-made build for RTX 20/30/40/50 cards (no compiler needed); if none fits your PC,
17     it installs the missing build tools (asks first) and compiles the engine for your GPU.  AMD (--backend hip, chosen by
18     itself on a PC with no usable NVIDIA card): the ready-made HIP engine on Windows, compiled here on Linux
19  5. downloads the model from Hugging Face (resumable), and the vision encoder if you want images
20  6. prepares the model for Strata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint)
21  7. 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."""
89    return _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),
112    else huggingface.co.  The pinned revisions and the SHA-256 checks are the same whichever host serves the files."""
113    return (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."""
118    return 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)."""
123    return 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
131    from the repository's current files, without the SHA-256 check (nothing pins them).  Off by default, announced when set."""
132    on = (os.environ.get("STRATA_ALLOW_UNPINNED") or "").strip() == "1"
133    if on and not _unpinned_said:
134        _unpinned_said.append(1)
135        warn("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")
137    return on
138
139
140def file_pin(url: str):
141    """(bytes, sha256) pinned for the Hugging Face file `url` names (REPO_PINS), else None."""
142    m = HF_FILE.match(url)
143    if m is None:
144        return None
145    name = m.group("path").rsplit("/", 1)[-1]
146    by_commit = REV_PINS.get((m.group("repo"), m.group("rev")), {})        # a repository with files at more than one commit (UNSLOTH_V31_REVISION)
147    return 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:
164    return (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."""
169    try:
170        _urlopen(urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}),
171                               timeout=timeout).close()
172        return True
173    except OSError:                                    # HTTPError too: an error page is not the file
174        return False
175
176
177def model_source() -> str:
178    """"modelscope" or "huggingface".  ModelScope only when --source modelscope / STRATA_SOURCE=modelscope asks for it;
179    everything else (auto, a HF_ENDPOINT mirror chosen on purpose, #495) is Hugging Face.  Setup does not switch hosts
180    by itself (#908): ModelScope serves a repository's current files, not our pinned revision."""
181    want = (os.environ.get("STRATA_SOURCE") or "auto").strip().lower()
182    key = (want, os.environ.get("HF_ENDPOINT") or "", ms_endpoint())
183    if key not in _sources:
184        _sources[key] = "modelscope" if want in ("ms", "modelscope") else "huggingface"
185    return _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."""
190    if "huggingface" in url or "hf-mirror" in url:
191        return ("; if huggingface.co does not reach you (mainland China), the same files are on ModelScope: run setup "
192                "with --source modelscope (docs/INSTALL.md)")
193    return ""
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)."""
198    return 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."""
203    names = ("HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy")
204    if any(os.environ.get(n) for n in names):
205        return "; a proxy is set in this terminal (HTTPS_PROXY): check that it is the right one and that it is running"
206    return "; 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."""
211    m = HF_FILE.match(url)
212    if m is None or m.group("repo") not in HF_REVISIONS:
213        return None
214    return m.group("repo"), m.group("path")
215
216
217def ms_url(repo: str, path: str) -> str:
218    return 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."""
223    if repo not in _ms_files:
224        try:
225            api = f"{ms_endpoint()}/api/v1/models/{repo}/repo/files?Recursive=true"
226            with _urlopen(urllib.request.Request(api, headers={"User-Agent": "strata-setup"}),
227                                        timeout=60) as r:
228                files = 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}
230        except (OSError, ValueError, KeyError, TypeError):
231            return None
232    return _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 = {
295    NVFP4_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}},
303    NVFP4_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
502    UNSLOTH_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,
784    UNSLOTH_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=""):
807    print(msg, flush=True)
808
809
810def step(n, title):
811    say()
812    say(f"=== Step {n}: {title} ===")
813
814
815def ok(msg):
816    say(f"  [ok] {msg}")
817
818
819def warn(msg):
820    say(f"  [!]  {msg}")
821
822
823def fail(msg, hint=None):
824    say(f"\n  [X]  {msg}")
825    if hint:
826        say(f"       {hint}")
827    say("\nSetup stopped. Fix the item above and run it again - everything already done is kept and skipped.")
828    sys.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
833    to "wake" a slow step answered "Go on anyway?" with its default.  Dropped before a question is asked, on a terminal
834    only (a pipe or a test keeps its input)."""
835    try:
836        if not sys.stdin.isatty():
837            return
838        if WIN:
839            import msvcrt
840            while msvcrt.kbhit():
841                msvcrt.getwch()
842        else:
843            import termios
844            termios.tcflush(sys.stdin.fileno(), termios.TCIFLUSH)
845    except (ImportError, OSError, ValueError, AttributeError):
846        pass
847
848
849def ask(question, choices, default, yes):
850    if yes:
851        return default
852    flush_typed_ahead()
853    while True:
854        try:
855            a = input(f"{question} [{default}]: ").strip()
856        except EOFError:
857            fail("input ended before a setup answer was received",
858                 "run setup in a terminal, or pass --yes to accept the recommended answers")
859        if not a:
860            return default
861        if a.lower() in [c.lower() for c in choices]:
862            return next(c for c in choices if c.lower() == a.lower())
863        say(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."""
869    acquisition.require("a download")
870    try:
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
873        return netpolicy.urlopen(req, timeout=timeout)
874    except urllib.error.URLError as e:
875        if tls.is_certificate_error(e):               # not the raw urlopen text, and never a way to skip the check
876            raise tls.CertificateProblem(tls.host_of(req.full_url if hasattr(req, "full_url") else str(req))) from None
877        raise
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
882    5 s, and a host that did not answer is not asked again in this run. Raises netpolicy.NetFailure, HTTPError or CertificateProblem."""
883    return 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."""
888    extra = "".join(" " + h[2:3].upper() + h[3:] + "." for h in (proxy_hint(), source_hint(url)) if h)
889    if e.detail():
890        say(f"  ({e.host}: {e.detail()})")             # the raw reason, for the log
891    fail(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."""
896    acquisition.require("an install or build step (" + Path(str(cmd[0])).name + ")")
897    if CONTROL:                                        # the app: only this Python running a bundled tool
898        argv = [str(c) for c in cmd]
899        if len(argv) < 2 or os.path.normcase(argv[0]) != os.path.normcase(sys.executable) or argv[1] == "-m" or \
900                Path(argv[1]).resolve().parent not in ((ROOT / "tools").resolve(), (ROOT / "metal" / "tools").resolve()):
901            raise acquisition.AcquisitionRefused("the desktop app's installer only runs its bundled preparation tools; "
902                                                 + " ".join(argv[:2]))
903    say("  > " + " ".join(str(c) for c in cmd))
904    env = dict(os.environ if env is None else env)
905    env.setdefault("STRATA_EXIT_WITH_PARENT", "1")     # tools/mtp_fetch.py ends when setup ends (#3257: a cancel left it writing)
906    r = subprocess.run([str(c) for c in cmd], cwd=cwd, env=env,
907                       stdout=subprocess.PIPE if quiet else None, stderr=subprocess.STDOUT if quiet else None,
908                       text=True, errors="replace")
909    if check and r.returncode != 0:
910        if quiet and r.stdout:
911            say(r.stdout[-4000:])
912        fail(f"command failed (exit {r.returncode}): {Path(str(cmd[0])).name}")
913    return 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):
918    it is run again, and each run continues where the last one stopped.  The progress lines it prints are what the app shows."""
919    cmd = [sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)]
920    env = {**env, "STRATA_SOURCE": model_source()}
921    def on_disk() -> int:
922        try:
923            return sum(f.stat().st_size for f in Path(mtp).rglob("*") if f.is_file())
924        except OSError:
925            return 0
926    for n in range(1, tries + 1):
927        before = on_disk()
928        r = run(cmd, env=env, check=False)
929        rc = 0 if r is None else r.returncode              # (a test double answers None)
930        if rc == 0:
931            return True
932        if rc == 5:                                        # tools/mtp_fetch.py OFFLINE: its [X] lines above say so; the model is set up and starts without the layer,
933            return False                                   # and the next launch with a connection fetches it (offline users: never a stop)
934        if rc == 4:                                       # tools/mtp_fetch.py NO_ANSWER: its [X] lines above name the host and the next step
935            say("\nSetup stopped. Fix the item above and run it again - everything already done is kept and skipped.")
936            sys.exit(1)
937        if r is not None and on_disk() <= before:          # the network rule: run again only when the last run moved bytes
938            break
939        if n < tries:
940            warn(f"the draft layer's download stopped (exit {rc}); trying again, it continues where it stopped "
941                 f"({n + 1} of {tries})")
942            time.sleep(5)
943    fail(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):
949    try:
950        return subprocess.run(cmd, capture_output=True, text=True, errors="replace", timeout=60).stdout or ""
951    except (OSError, subprocess.TimeoutExpired):
952        return ""
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
957    the file's full path, size and modification time, so a file that changed (or a different file at the same place) has no mark."""
958    try:
959        st = path.stat()
960        key = f"{path.resolve()}|{st.st_size}|{st.st_mtime_ns}"
961    except OSError:
962        return None
963    return 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,
968    so 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
969    ctime is the creation time there (an in-place rewrite keeps it), so the file system's own ChangeTime is read (GetFileInformationByHandleEx,
970    FileBasicInfo); if that cannot be read, st_ctime_ns is used."""
971    if os.name != "nt":
972        return st.st_ctime_ns
973    try:
974        from ctypes import wintypes
975
976        class _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)]
979        k32 = ctypes.WinDLL("kernel32", use_last_error=True)
980        k32.CreateFileW.restype = wintypes.HANDLE
981        k32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD,
982                                    wintypes.HANDLE]
983        k32.GetFileInformationByHandleEx.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
984        k32.GetFileInformationByHandleEx.restype = wintypes.BOOL
985        k32.CloseHandle.argtypes = [wintypes.HANDLE]
986        # FILE_READ_ATTRIBUTES, share read / write / delete, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS (a folder opens too)
987        h = k32.CreateFileW(str(path), 0x80, 0x7, None, 3, 0x02000000, None)
988        if h is None or h == ctypes.c_void_p(-1).value:
989            return st.st_ctime_ns
990        try:
991            info = _BasicInfo()
992            if not k32.GetFileInformationByHandleEx(h, 0, ctypes.byref(info), ctypes.sizeof(info)):      # 0 = FileBasicInfo
993                return st.st_ctime_ns
994            return int(info.ChangeTime) * 100                    # 100 ns steps since 1601; only compared, never shown
995        finally:
996            k32.CloseHandle(h)
997    except (OSError, AttributeError, ValueError):
998        return 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
1003    time AND change time (_change_time_ns), so a file rewritten in place with its size and modification time kept is hashed again.  Only this
1004    mark 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."""
1005    try:
1006        real = path.resolve()
1007        st = real.stat()
1008        key = f"alt-reader|{real}|{st.st_size}|{st.st_mtime_ns}|{_change_time_ns(real, st)}"
1009    except OSError:
1010        return None
1011    return 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)."""
1019    try:
1020        _OWN_DIRS.append(Path(folder).expanduser().resolve())
1021    except OSError:
1022        _OWN_DIRS.append(Path(folder).expanduser())
1023
1024
1025def _is_own_file(path: Path) -> bool:
1026    if not _OWN_DIRS:
1027        return False
1028    try:
1029        parent = Path(path).expanduser().absolute().parent.resolve()
1030    except OSError:
1031        return False
1032    return 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."""
1037    for m in (path.with_name(path.name + ".done"), _kept_mark(path)):
1038        try:
1039            if m is not None and m.exists():
1040                return m.read_text(encoding="utf-8", errors="replace")
1041        except OSError:
1042            pass
1043    return None
1044
1045
1046def done(path: Path) -> bool:
1047    """A step's finish mark: <path>.done exists (written only after the step completed)."""
1048    return 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
1053    in 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
1054    does setup say so and go on (the step is repeated on the next run), it does not stop."""
1055    text = text or time.strftime("%Y-%m-%d %H:%M")
1056    beside: BaseException | str = "a folder of the person's own model files"
1057    if not _is_own_file(path):
1058        try:
1059            path.with_name(path.name + ".done").write_text(text, encoding="utf-8")
1060            return
1061        except OSError as e:
1062            beside = e
1063    kept = _kept_mark(path)
1064    try:
1065        if kept is not None:
1066            kept.parent.mkdir(parents=True, exist_ok=True)
1067            kept.write_text(text, encoding="utf-8")
1068            return
1069    except OSError:
1070        pass
1071    warn(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)."""
1077    class 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)]
1083    m = MS()
1084    m.dwLength = ctypes.sizeof(MS)
1085    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
1086    return m
1087
1088
1089def ram_gb():
1090    if WIN:
1091        return _memory_status().ullTotalPhys / 2**30
1092    if sys.platform == "darwin":
1093        try:
1094            value = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True,
1095                                   text=True, errors="replace", timeout=3, check=True).stdout.strip()
1096            return int(value) / 2**30
1097        except (OSError, ValueError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
1098            return 0.0
1099    total = 0.0
1100    try:
1101        with open("/proc/meminfo") as stream:
1102            for line in stream:
1103                if line.startswith("MemTotal"):
1104                    total = int(line.split()[1]) * 1024 / 2**30
1105                    break
1106    except (OSError, ValueError):
1107        pass
1108    if total <= 0.0:
1109        return 0.0
1110    # In a container /proc/meminfo is the host's: the container's own limit is the RAM the engine gets.
1111    limit = _cgroup_memory_limit()
1112    if limit is not None and limit / 2**30 < total:
1113        return limit / 2**30
1114    return 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
1119    it (strata_control/cgroup_memory.py). None when no level sets a limit or the files cannot be read."""
1120    from strata_control import cgroup_memory
1121    return 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
1129    dialog set; ExistingPageFiles is where the page files are now."""
1130    try:
1131        import winreg
1132        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _MM_KEY) as k:
1133            v, _t = winreg.QueryValueEx(k, name)
1134    except (ImportError, OSError):
1135        return None
1136    return [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,
1141    initial MB, maximum MB), both -1 when Windows manages the size and the drive '?' when it manages every drive;
1142    None for anything else."""
1143    s = line.strip()
1144    if len(s) < 2 or s[1] != ":":
1145        return None
1146    parts = s.split()
1147    try:
1148        initial, maximum = (int(parts[1]), int(parts[2])) if len(parts) >= 3 else (-1, -1)
1149    except ValueError:
1150        initial, maximum = -1, -1
1151    if maximum <= 0:
1152        initial, maximum = -1, -1
1153    return 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:
1161    its size comes from the directory entry."""
1162    root = f"{drive}:\\"
1163    try:
1164        du = shutil.disk_usage(root)
1165    except OSError:
1166        return None
1167    current = 0
1168    try:
1169        with os.scandir(root) as it:
1170            for e in it:
1171                if e.name.lower() == "pagefile.sys":
1172                    current = e.stat(follow_symlinks=False).st_size
1173                    break
1174    except OSError:
1175        pass
1176    return 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,
1181    maximum MB, MB now, the drive's free MB)], the sizes -1 for a system-managed file; "?:" (every drive automatic) is
1182    the drive ExistingPageFiles names.  None off Windows or when the setting cannot be read."""
1183    if not WIN:
1184        return None
1185    lines = _mm_multi_sz("PagingFiles")
1186    if lines is None:
1187        return None
1188    auto = []                                          # "?:\pagefile.sys": where Windows keeps it now, else C:
1189    for s in _mm_multi_sz("ExistingPageFiles") or []:
1190        i = s.find(":")
1191        if i > 0:
1192            auto.append(s[i - 1].upper())
1193    auto = auto or [(os.environ.get("SystemDrive") or "C:")[0].upper()]
1194    files = []
1195    for line in lines:
1196        e = parse_paging_file(line)
1197        if e is None:
1198            continue
1199        drive, initial, maximum = e
1200        for d in (auto if drive == "?" else [drive]):
1201            free, now = _drive_mb(d) or (0.0, 0.0)
1202            files.append((d, initial, maximum, now, free))
1203    return 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."""
1208    return 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
1213    room there too: under Windows' driver model every allocation on the card is also charged to the commit (RAM + page
1214    file), so with the page file off or tiny the engine cannot use the free VRAM (issue #60).  What counts is the size
1215    the files have now (the commit limit minus RAM), or a file's configured initial size when that is larger (within
1216    its drive's free space) - never what a file may grow to: a page file Windows grows on demand may not grow in time
1217    while the card's memory is charged (#60: "System managed" and 4096-32768 MB still failed, a fixed 64 GB worked)."""
1218    if not WIN:
1219        return None
1220    m = _memory_status()
1221    mb = max(0.0, (m.ullTotalPageFile - m.ullTotalPhys) / 2**20)
1222    files = page_file_setting()
1223    if files:
1224        mb = max(mb, sum(max(now, min(max(initial, 0), now + free)) for _d, initial, _m, now, free in files))
1225    return 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`,
1230    page_file_setting) has Windows grow it on demand."""
1231    grows = ("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 ""
1234    return (f"Windows' page file is {pf:.1f} GB: the graphics card's memory needs room there too (issue #60), so the "
1235            f"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 "
1237            f"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
1242    as the engine's pool counts them (detect_cpu_topology: physical cores, by Windows' EfficiencyClass or Linux's
1243    cpu_capacity); None on a CPU whose cores are all alike, or when the OS does not say."""
1244    classes = []                                       # one entry per physical core: its efficiency/capacity class
1245    try:
1246        if WIN:
1247            k32 = ctypes.windll.kernel32
1248            n = ctypes.c_ulong(0)
1249            k32.GetLogicalProcessorInformationEx(0, None, ctypes.byref(n))   # RelationProcessorCore: the size
1250            if not n.value:
1251                return None
1252            buf = ctypes.create_string_buffer(n.value)
1253            if not k32.GetLogicalProcessorInformationEx(0, buf, ctypes.byref(n)):
1254                return None
1255            raw, at = buf.raw[:n.value], 0
1256            while at + 10 <= len(raw):   # SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX: Relationship, Size, then
1257                rel, size = struct.unpack_from("<II", raw, at)               # PROCESSOR_RELATIONSHIP (Flags,
1258                if size <= 0:                                                # EfficiencyClass, ...)
1259                    break
1260                if rel == 0:
1261                    classes.append(raw[at + 9])
1262                at += size
1263        else:
1264            classes = linux_core_classes()
1265            if classes is None:
1266                return None
1267    except (OSError, ValueError, AttributeError):
1268        return None
1269    if not classes or max(classes) == min(classes):
1270        return None
1271    p = sum(1 for c in classes if c == max(classes))
1272    return 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
1278    one under 90% of the largest - Turbo Boost Max 3.0 gives the "favored" P-cores a slightly higher capacity (1024
1279    against 1012), so "below the maximum" counted 2 of a Core Ultra 7 270K Plus's 8 P-cores."""
1280    pmu = linux_hybrid_pmu(sys_root + "/devices")
1281    seen, top = {}, 0
1282    for cpu in sorted((Path(sys_root) / "devices" / "system" / "cpu").glob("cpu[0-9]*"), key=lambda p: int(p.name[3:])):
1283        cap = cpu / "cpu_capacity"
1284        pkg, core = cpu / "topology" / "physical_package_id", cpu / "topology" / "core_id"
1285        if not cap.exists() and pmu is None:
1286            return None
1287        key = (pkg.read_text(encoding="utf-8").strip(), core.read_text(encoding="utf-8").strip()) \
1288            if pkg.exists() and core.exists() else cpu.name
1289        num = int(cpu.name[3:])
1290        capacity = int(cap.read_text(encoding="utf-8").strip()) if cap.exists() else 0
1291        top = max(top, capacity)
1292        if pmu is not None and num in pmu[1]:
1293            seen.setdefault(key, None)           # a listed E-core (the atom list and, #3262, the LP-E list)
1294        elif pmu is not None and num in pmu[0]:
1295            seen.setdefault(key, False)          # a listed P-core
1296        else:                                    # in no list (or no lists at all): its capacity decides
1297            seen.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
1299    return [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."""
1304    out = set()
1305    for part in text.strip().split(","):
1306        lo, _, hi = part.strip().partition("-")
1307        if lo.isdigit():
1308            out.update(range(int(lo), int(hi or lo) + 1))
1309    return 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
1314    that has no such lists."""
1315    try:
1316        p = cpulist((Path(root) / "cpu_core" / "cpus").read_text(encoding="utf-8"))
1317        e = cpulist((Path(root) / "cpu_atom" / "cpus").read_text(encoding="utf-8"))
1318    except OSError:
1319        return None
1320    try:   # #3262: Meteor Lake / Arrow Lake-H list their LP-E cores in a third set, in neither of the two above
1321        e |= cpulist((Path(root) / "cpu_lowpower" / "cpus").read_text(encoding="utf-8"))
1322    except OSError:
1323        pass
1324    return (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
1329    plus HALF of the E-cores - an E-core runs the expert kernels ~2.2x slower and each layer waits for its slowest
1330    part (i9-14900KF, 8P + 16E: 15 workers decoded 165 / 116 tok/s against 106 / 84 with all 23).  Only on a CPU with
1331    more E-cores than P-cores: on an i7-13700KF (8P + 8E, docs/AMD_HIP.md's gfx1030 report) all 15 workers decoded
1332    38-42 tok/s against 36 with 8, so there the engine's own count stays.  None: the engine's own default (one worker
1333    per physical core but the host's) stays."""
1334    if not cores:
1335        return None
1336    p, e = cores
1337    if e <= p:
1338        return None
1339    return 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
1344    measured count, or the user's own).  A recommendation: the config line can be edited or removed."""
1345    n = hybrid_pool_workers(cpu_cores())
1346    if n is None or "--pool-workers" in args:
1347        return args
1348    n = min(n, POOL_WORKERS_CAP)   # setup never writes a big worker count (see plan_pool_workers)
1349    p, e = cpu_cores()
1350    ok(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)")
1352    return [*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."""
1357    cores = {}
1358    for cpu in (Path(sys_root) / "devices" / "system" / "cpu").glob("cpu[0-9]*"):
1359        pkg, core = cpu / "topology" / "physical_package_id", cpu / "topology" / "core_id"
1360        try:
1361            cores.setdefault(pkg.read_text(encoding="utf-8").strip(), set()).add(core.read_text(encoding="utf-8").strip())
1362        except OSError:
1363            return None
1364    return (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
1369    GetLogicalProcessorInformationEx lists (RelationProcessorPackage 3, RelationProcessorCore 0)."""
1370    try:
1371        if not WIN:
1372            return linux_sockets()
1373        k32 = ctypes.windll.kernel32
1374        counts = {}
1375        for rel in (0, 3):
1376            n = ctypes.c_ulong(0)
1377            k32.GetLogicalProcessorInformationEx(rel, None, ctypes.byref(n))
1378            if not n.value:
1379                return None
1380            buf = ctypes.create_string_buffer(n.value)
1381            if not k32.GetLogicalProcessorInformationEx(rel, buf, ctypes.byref(n)):
1382                return None
1383            raw, at, c = buf.raw[:n.value], 0, 0
1384            while at + 8 <= len(raw):
1385                size = struct.unpack_from("<II", raw, at)[1]
1386                if size <= 0:
1387                    break
1388                c += 1
1389                at += size
1390            counts[rel] = c
1391        return (counts[3], counts[0] // counts[3]) if counts[3] else None
1392    except Exception:
1393        return 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
1398    cores, one fewer for the host loop.  Nothing is written to the config."""
1399    if not sockets or sockets[0] < 2 or sockets[1] < 3:
1400        return []
1401    n = sockets[1] - 1
1402    return [f"tip: this PC has {sockets[0]} CPU sockets of {sockets[1]} cores. Expert workers on the other socket have "
1403            f"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
1420    quota (0: none)."""
1421    cores = list(cores_per_package or [])
1422    if cores and sum(cores) > 0:
1423        local = cores[0]
1424    else:                                              # no layout: half the logical processors on a many-thread CPU
1425        local = logical // 2 if logical >= 16 else logical
1426    n = max(1, local - 1)                              # the host thread has the first core
1427    if n >= POOL_RESERVE_FROM:
1428        n -= POOL_RESERVE
1429    if 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
1430        n = min(n, max(1, hybrid[0] - 1 + hybrid[1] // 2))
1431    if quota > 0:
1432        n = min(n, max(1, int(quota) - 1))
1433    return 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."""
1438    logical = os.cpu_count() or 1
1439    sockets = cpu_sockets()
1440    return 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
1445    count stays as it is and the engine runs with it."""
1446    if "--pool-workers" not in args:
1447        return []
1448    try:
1449        asked = int(args[args.index("--pool-workers") + 1])
1450    except (IndexError, ValueError):
1451        return []
1452    hybrid = cpu_cores() if layout is None else None
1453    logical, cores = layout or cpu_core_layout()
1454    rec = plan_pool_workers(logical, cores, hybrid=hybrid)
1455    if asked <= rec:
1456        return []
1457    why = ("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")
1461    return [f"the config asks for {asked} CPU expert workers, {why}: extra workers can make Strata slower. Recommended: "
1462            f"--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
1467    VISION_THREADS_CAP - a 256-thread server does not need 128 of them."""
1468    return 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),
1473    the same test the engine makes (cpu_avx512_ok), not just AVX-512F."""
1474    name, avx2, avx512 = sysinfo.processor() or "unknown CPU", False, False
1475    if WIN:
1476        pf = ctypes.windll.kernel32.IsProcessorFeaturePresent
1477        avx2 = bool(pf(40)) or _cpuid_avx2()      # PF_AVX2_INSTRUCTIONS_AVAILABLE, else the CPU itself (#159)
1478        n = out(["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_Processor).Name"]).strip()
1479        name = n or name
1480        avx512 = bool(pf(41)) and _cpuid_avx512_full()
1481    else:
1482        try:
1483            txt = open("/proc/cpuinfo").read()
1484            mflags = re.search(r"^flags\s*:\s*(.*)$", txt, re.M)
1485            if 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.
1488                cores = re.findall(r"^\s*Model name:\s*(.+)$", out(["lscpu"]), re.M)
1489                name = " + ".join(dict.fromkeys(c.strip() for c in cores)) or (sysinfo.processor() or "arm64 CPU")
1490                return name, False, False
1491            flags = set(mflags.group(1).split())
1492            avx2 = "avx2" in flags
1493            avx512 = {"avx512f", "avx512bw", "avx512vl", "avx512_vnni", "avx512vbmi"} <= flags
1494            m = re.search(r"^model name\s*:\s*(.*)$", txt, re.M)
1495            name = m.group(1) if m else name
1496        except OSError:
1497            pass
1498    return 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
1503    POPCNT, else ""."""
1504    try:
1505        regs = (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
1507                         0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08,  # [r8]=eax, [r8+4]=ebx, [r8+8]=ecx
1508                         0x41, 0x89, 0x50, 0x0C, 0x5B, 0xC3]),                             # [r8+12]=edx; pop rbx
1509                  ctypes.addressof(regs), 1)
1510        ecx1 = regs[2]
1511        if (ecx1 >> 27) & 1 and (ecx1 >> 28) & 1:                     # OSXSAVE, AVX
1512            xcr0 = (ctypes.c_uint32 * 2)()
1513            _run_stub(bytes([0x49, 0x89, 0xC8, 0x31, 0xC9, 0x0F, 0x01, 0xD0,                    # r8=rcx; ecx=0; xgetbv
1514                             0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, 0xC3]), ctypes.addressof(xcr0))
1515            if xcr0[0] & 6 == 6:
1516                return "avx"
1517        return "sse4.2" if (ecx1 >> 20) & 1 and (ecx1 >> 23) & 1 else ""
1518    except Exception:
1519        return ""
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."""
1524    return 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
1529    below were measured on (docs/DGX_SPARK_LINUX.md); any other unified-memory NVIDIA GPU gets the ordinary settings."""
1530    return 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 /
1535    Ivy Bridge, AMD Bulldozer), "none" (SSE4.2 + POPCNT: Nehalem, Westmere), or "unsupported".  STRATA_ISA_FLOOR=avx|
1536    none asks for that build on any PC (testing it on a newer one)."""
1537    forced = os.environ.get("STRATA_ISA_FLOOR", "").strip().lower()
1538    if forced in ("avx", "none"):
1539        return forced
1540    if is_arm64():
1541        return ""
1542    if avx2:
1543        return ""
1544    if WIN:
1545        f = _cpuid_floor()
1546    else:
1547        try:
1548            txt = open("/proc/cpuinfo").read()
1549            flags = set(re.search(r"^flags\s*:\s*(.*)$", txt, re.M).group(1).split())
1550        except (OSError, AttributeError):
1551            flags = set()
1552        f = "avx" if "avx" in flags else "sse4.2" if {"sse4_2", "popcnt"} <= flags else ""
1553    return {"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."""
1558    try:
1559        code = bytes([0x53, 0x49, 0x89, 0xC8, 0xB8, 0x07, 0x00, 0x00, 0x00, 0x31, 0xC9, 0x0F, 0xA2,   # push rbx; r8=rcx; cpuid(7,0)
1560                      0x41, 0x89, 0x18, 0x41, 0x89, 0x48, 0x04, 0x5B, 0xC3])                   # [r8]=ebx,[r8+4]=ecx; pop rbx
1561        k32 = ctypes.windll.kernel32
1562        k32.VirtualAlloc.restype = ctypes.c_void_p
1563        buf = k32.VirtualAlloc(None, len(code), 0x3000, 0x40)
1564        if not buf:
1565            return False
1566        ctypes.memmove(buf, code, len(code))
1567        regs = (ctypes.c_uint32 * 2)()
1568        ctypes.CFUNCTYPE(None, ctypes.c_void_p)(buf)(ctypes.addressof(regs))
1569        ebx, ecx = regs[0], regs[1]
1570        need_ebx = (1 << 16) | (1 << 30) | (1 << 31)                   # F, BW, VL
1571        need_ecx = (1 << 1) | (1 << 11)                                # VBMI, VNNI
1572        return (ebx & need_ebx) == need_ebx and (ecx & need_ecx) == need_ecx
1573    except Exception:
1574        return 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)."""
1579    k32 = ctypes.windll.kernel32
1580    k32.VirtualAlloc.restype = ctypes.c_void_p
1581    k32.VirtualFree.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32)
1582    buf = k32.VirtualAlloc(None, len(code), 0x3000, 0x40)
1583    if not buf:
1584        raise OSError("VirtualAlloc failed")
1585    try:
1586        ctypes.memmove(buf, code, len(code))
1587        ctypes.CFUNCTYPE(None, *[ctypes.c_void_p] * len(args))(buf)(*args)
1588    finally:
1589        k32.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):
1594    Windows' IsProcessorFeaturePresent(PF_AVX2) says no on some PCs whose CPU has it (a Ryzen 9 3950X, #159)."""
1595    try:
1596        def cpuid(leaf):
1597            regs = (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
1599                             0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08,  # [r8]=eax, [r8+4]=ebx, [r8+8]=ecx
1600                             0x41, 0x89, 0x50, 0x0C, 0x5B, 0xC3]),                             # [r8+12]=edx; pop rbx
1601                      ctypes.addressof(regs), leaf)
1602            return list(regs)
1603        if cpuid(0)[0] < 7:
1604            return False
1605        ecx1 = cpuid(1)[2]
1606        if not (ecx1 >> 27) & 1 or not (ecx1 >> 28) & 1:             # OSXSAVE, AVX
1607            return False
1608        xcr0 = (ctypes.c_uint32 * 2)()
1609        _run_stub(bytes([0x49, 0x89, 0xC8, 0x31, 0xC9, 0x0F, 0x01, 0xD0,                        # r8=rcx; ecx=0; xgetbv
1610                         0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, 0xC3]), ctypes.addressof(xcr0))
1611        if xcr0[0] & 6 != 6:                                           # the OS saves XMM and YMM
1612            return False
1613        return bool((cpuid(7)[1] >> 5) & 1)
1614    except Exception:
1615        return 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)."""
1620    s = out(["nvidia-smi", "--query-gpu=index,name,memory.total,compute_cap,driver_version",
1621             "--format=csv,noheader,nounits"])
1622    found = []
1623    for line in s.strip().splitlines():
1624        try:
1625            idx, name, mem, cc, drv = [x.strip() for x in line.split(",")]
1626            try:
1627                mem_gb = float(mem) / 1024.0   # nvidia-smi nounits: MiB
1628            except ValueError:
1629                if not is_arm64():
1630                    raise   # 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
1634                shared = max(0.0, ram_gb() - UMA_OS_LEFT_GB)
1635                found.append({"index": int(idx), "name": name, "vram_gb": shared, "arch": cc.replace(".", ""),
1636                              "driver": drv, "uma": True, "dedicated_gb": 0.0, "shared_gb": shared})
1637                continue
1638            found.append({"index": int(idx), "name": name, "vram_gb": mem_gb, "arch": cc.replace(".", ""),
1639                          "driver": drv})
1640        except ValueError:
1641            continue
1642    return 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
1647    VRAM too, and a full expert cache beside it has crashed laptops."""
1648    text = out(["nvidia-smi", "-i", str(g.get("index", 0)), "--query-gpu=display_active", "--format=csv,noheader"])
1649    return 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
1654    does not say."""
1655    return 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
1660    process 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
1662    administrator's setting, Strata never changes it."""
1663    if not mode or mode.lower() == "default" or mode.lower().startswith("n/a") or mode.lower().startswith("[n/a"):
1664        return None
1665    return (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 "
1667            f"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
1672    one, so the current generation is not asked), "gpu_gen", "host_gen", "width", "max_width"}; None when nvidia-smi
1673    does not say."""
1674    s = 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"])
1676    try:
1677        gen, gpu_gen, host_gen, width, max_width = (int(x.strip()) for x in s.strip().splitlines()[0].split(","))
1678    except (ValueError, IndexError):
1679        return None
1680    return {"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."""
1688    lim = []
1689    if link["gpu_gen"] > link["gen"]:
1690        lim.append(f"the card supports {link['gpu_gen']}.0, the board {link['host_gen']}.0")
1691    line = f"PCIe: {link['gen']}.0 x{link['width']}" + (f" ({'; '.join(lim)})" if lim else "")
1692    rate = PCIE_GBPS.get(link["gen"], 0) * link["width"]
1693    if 0 < rate < 12:
1694        line += (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")
1696    warn_line = None
1697    if 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
1699        warn_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)")
1702    return 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:
1715    return 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
1723    engine (-DSTRATA_EXPERIMENTAL_SM60=ON).  So does naming such a card (--gpu N / --gpus), --cuda 12, or a PC that
1724    has no newer card (old_gpus_opt_in)."""
1725    return os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1" or OLD_GPUS is not None
1726
1727
1728def sm60_card(arch) -> bool:
1729    return 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)."""
1734    return 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
1739    source build exists.  Empty when there is no Maxwell card.  A warning with the way forward, never a switch: setup
1740    does not route a Maxwell card to an engine that holds no code for it."""
1741    cards = [g for g in found if maxwell_card(g["arch"])]
1742    if not cards:
1743        return ""
1744    names = ", ".join(f"GPU {g['index']} ({g['name']})" for g in cards)
1745    return (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:
1754    the user named one (`named`: --gpu / --gpus), asked for --cuda 12, set STRATA_EXPERIMENTAL_SM60=1, or the PC has
1755    no card the ready-made engine runs on and no supported AMD card (`other`; it used to stop there).  A PC with a
1756    newer card keeps recommending it."""
1757    old = [g for g in found if sm60_card(g["arch"])]
1758    if not old:
1759        return None
1760    if os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1":
1761        return "STRATA_EXPERIMENTAL_SM60=1"
1762    if str(cuda) == "12":
1763        return "--cuda 12"
1764    picked = [g for g in old if g["index"] in set(named)]
1765    if picked:
1766        return "you chose " + ", ".join(f"GPU {g['index']} ({g['name']})" for g in picked)
1767    if not other and not any(int(g["arch"]) >= CUDA13_MIN_ARCH for g in found):
1768        return "it is the only kind of NVIDIA GPU in this PC"
1769    return 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)."""
1774    try:
1775        if gpus and str(gpus).strip().lower() != "all":
1776            return [int(x) for x in str(gpus).split(",") if x.strip()]
1777        return [int(gpu)] if gpu is not None else []
1778    except ValueError:
1779        return []
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
1787    from the engine package (installed, else - with `feed` - the signed feed, else the figure the packages carry) and not from a constant
1788    of 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."""
1789    got = _CUDA12_FLOORS.get(True) or _CUDA12_FLOORS.get(feed)
1790    if got:
1791        return got
1792    from strata_control import driver_floor
1793    roots = [engine_component.components_dir(), home() / "engine-feed"]
1794    source = None
1795    if feed and not acquisition.is_forbidden():
1796        try:
1797            from strata_cli import update_cmd
1798            source = update_cmd._feed_source(argparse.Namespace(feed=None), home())
1799        except Exception:                                  # noqa: BLE001 - no feed address: the built-in figure
1800            source = None
1801    try:
1802        from strata_control import targets
1803        platform_name = targets.host_platform()
1804    except Exception:                                      # noqa: BLE001
1805        platform_name = ""
1806    figure, where = driver_floor.cuda12_floor(platform_name, roots=roots, feed_source=source)
1807    _CUDA12_FLOORS[feed] = got = (driver_floor.major(figure), figure, where)
1808    return 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
1813    than CUDA 13 supports (Pascal / Volta: CUDA 13 cannot compile for them) - one engine runs per model, so its oldest
1814    card decides.  `cuda` (--cuda 12|13) overrides it; setup recommends, it does not refuse (the caller warns)."""
1815    archs = sorted({int(x) for x in archs})
1816    old = [a for a in archs if a < CUDA13_MIN_ARCH]
1817    if str(cuda) == "13":
1818        return 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 ""))
1820    if str(cuda) == "12":
1821        return 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 "") + ")"
1823    if old:
1824        return 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")
1826    if driver and CUDA12_COMPAT_DRIVER <= int(driver) < MIN_DRIVER:      # #3843: a driver too old for CUDA 13 still runs the CUDA 12 engine
1827        return 12, (f"the NVIDIA driver {driver} is older than CUDA 13 needs ({MIN_DRIVER}): this model runs the CUDA 12 engine "
1828                    f"(a newer driver from https://www.nvidia.com/drivers gives the CUDA 13 engine)")
1829    return 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
1834    own (cuda12_min_driver), the same one `strata update` enforces, so setup no longer says "works" where the update says "no engine" (#4247 #4188).
1835    Recommend, never force: setup goes on (an engine compiled here, or one the person brings, may still run)."""
1836    floor, figure, where = cuda12_min_driver()
1837    if not driver or int(driver) >= floor:
1838        return None
1839    return (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)."""
1846    return 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."""
1851    return 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)."""
1856    if int(g["arch"]) < 75 and not (sm60_card(g["arch"]) and experimental_sm60()):
1857        return (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 "") + ")")
1861    if together and g["vram_gb"] < SPLIT_MIN_VRAM_GB - 0.5:
1862        return (f"not supported together with other GPUs - {g['vram_gb']:.0f} GB of VRAM (a card sharing the model "
1863                f"needs {SPLIT_MIN_VRAM_GB} GB or more)")
1864    return 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
1869    work), then the most VRAM."""
1870    return (-int(g["arch"]), -round(g["vram_gb"]), g["index"])
1871
1872
1873def gpu_name(g) -> str:
1874    return f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB)"
1875
1876
1877def gpu_table(found) -> None:
1878    say("  Your NVIDIA GPUs:")
1879    for g in found:
1880        p = gpu_problem(g)
1881        say(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)."""
1886    ok_ = sorted([g for g in found if gpu_problem(g, together=True) is None], key=gpu_rank)
1887    return 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
1892    under SPLIT_PROMPT_VRAM_GB beside one that has it).  Empty: the split is recommended as before."""
1893    if len(cards) < 2 or cards[0]["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5:
1894        return []
1895    return [g for g in cards[1:] if g["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5]
1896
1897
1898def split_short_note(g) -> str:
1899    return (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)."""
1906    if str(text).strip().lower() == "all":
1907        sel = [g["index"] for g in together_ok(found)]
1908        if not sel:
1909            gpu_table(found)
1910            fail("--gpus all: this PC does not have two GPUs Strata can use together")
1911        return sel
1912    try:
1913        sel = [int(x) for x in str(text).split(",") if x.strip()]
1914    except ValueError:
1915        fail(f"--gpus takes GPU numbers as nvidia-smi numbers them, e.g. --gpus 0,2 (or --gpus all), not {text!r}")
1916    if len(sel) < 2 or len(set(sel)) != len(sel):
1917        fail("--gpus takes two or more different GPUs, e.g. --gpus 0,2 (one GPU: --gpu 0)")
1918    return 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
1923    named these cards (--gpus 0,1, or a config that has them): a card that is only short of VRAM for sharing the model
1924    is then a risk to confirm, not a stop (the owner's rule; --yes with the named cards is the consent)."""
1925    together = len(sel) > 1
1926    for i in sel:
1927        g = next((x for x in found if x["index"] == i), None)
1928        p = "not found on this PC" if g is None else gpu_problem(g, together)
1929        if p is None:
1930            continue
1931        if named and g is not None and gpu_problem(g) is None:     # it runs Strata; only its VRAM is small
1932            confirm_risk(f"GPU {i} ({g['name']}) has {g['vram_gb']:.0f} GB of VRAM: a card sharing the model needs "
1933                         f"{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,
1935                         f"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?")
1937            warn(f"GPU {i} ({g['name']}) is used together with the others, as you chose")
1938            continue
1939        say()
1940        gpu_table(found)
1941        can = together_ok(found)
1942        single = [x for x in found if gpu_problem(x) is None]
1943        ones = " or ".join(f"--gpu {x['index']}" for x in single)
1944        both = "--gpus " + ",".join(str(x["index"]) for x in can) if can else ""
1945        hint = ((f"use these together: {both}" + (f" (or one card: {ones})" if not together else "")) if can else
1946                f"use one card: {ones}" if single else "Strata needs an NVIDIA RTX 20 series or newer card")
1947        fail(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
1952    reader'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
1953    list of numbers ([75, 86, 89, 120]); [60, "sm_61", "70-real", "compute_89"] and "60,61 70" are read too (#3810: a string was
1954    iterated character by character and setup stopped with int(';'))."""
1955    if value is None or value == "":
1956        return []
1957    parts = list(value) if isinstance(value, (list, tuple, set)) else re.split(r"[;,\s]+", str(value))
1958    out: list = []
1959    for part in parts:
1960        m = re.search(r"\d+", str(part))
1961        if m and int(m.group()) not in out:
1962            out.append(int(m.group()))
1963    return 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."""
1968    if value is None or value == "":
1969        return []
1970    parts = list(value) if isinstance(value, (list, tuple, set)) else re.split(r"[;,\s]+", str(value))
1971    return [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."""
1976    info = engine_dir(toolkit) / "BUILD.json"
1977    try:
1978        meta = json.loads(info.read_text(encoding="utf-8"))
1979    except (OSError, ValueError):
1980        return None
1981    return 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."""
1986    try:
1987        meta = json.loads((ROOT / "engine" / "BUILD.json").read_text(encoding="utf-8"))
1988    except (OSError, ValueError):
1989        return None
1990    return arch_names(meta.get("archs")) if meta.get("backend") == "hip" else None
1991
1992
1993def engine_runs_on(g, toolkit=13) -> bool:
1994    ea = engine_archs(toolkit)
1995    if ea is None or not ea[0]:
1996        return True
1997    archs, ptx = ea
1998    return 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
2003    are the ones Strata can use, AMD cards as setup lists them ("all": every supported AMD card)."""
2004    if not text:
2005        return None
2006    found = gpus()
2007    if str(text).strip().lower() == "all" and not WIN and not together_ok(found):
2008        amd = amd_gpus()
2009        if len([g for g in amd if amd_problem(g) is None]) >= 2:
2010            return [g["index"] for g in amd_parse_gpus("all", amd)]
2011    if not found and not WIN:                          # #1594: no NVIDIA card, AMD ones: "1,0" names those, as setup lists them
2012        amd = amd_gpus()
2013        if amd:
2014            return [g["index"] for g in amd_parse_gpus(text, amd)]
2015    return 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
2020    together recommended), else the supported card with the most VRAM.  Returns their numbers, in the engine order, the Main card last when roles are chosen."""
2021    if a.gpus:
2022        sel = parse_gpus(a.gpus, found)
2023        check_gpus(sel, found, yes=a.yes, named=str(a.gpus).strip().lower() != "all")
2024        return sel
2025    if a.gpu is not None:
2026        check_gpus([a.gpu], found)
2027        return [a.gpu]
2028    single = sorted([g for g in found if gpu_problem(g) is None], key=lambda x: (-round(x["vram_gb"]), x["index"]))
2029    if not single:
2030        gpu_table(found)
2031        fail("none of your GPUs can run Strata", "it needs an NVIDIA RTX 20 series or newer (compute capability 7.5+)")
2032    can = together_ok(found)
2033    if not can:
2034        for g in found:                                # said, not asked: a card that works alone but cannot share a model beside a bigger one
2035            if g["index"] != single[0]["index"] and gpu_problem(g) is None:
2036                say(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, "
2037                    f"so the model runs on GPU {single[0]['index']} alone.")
2038        return [single[0]["index"]]
2039    return 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),
2044    not the Main card of the roles - unless the person named the roles (--gpu-roles), then their Main card."""
2045    if getattr(a, "_roles_explicit", False) or not getattr(a, "_roles", None):
2046        return gpu
2047    return 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."""
2052    from strata_control import gpu_roles
2053    return gpu_roles.nvidia_speeds()
2054
2055
2056def roles_cards(found) -> list:
2057    sp = card_speeds()
2058    return [{"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
2064    Off) and ONE question, "Use these roles?".  n takes the person's own: 1=main,0=helper (cards left out are Off).  Returns the card
2065    numbers in the engine's order (Main last) and keeps the roles in a._roles for the config (docs/MULTI_GPU.md)."""
2066    from strata_control import gpu_roles
2067    cards = roles_cards(found)
2068    roles = dict(gpu_roles.recommend(cards)["roles"])
2069    say()
2070    say("  Strata recommends a role for each graphics card. Main does the last steps of every answer; a Helper holds part of the model;")
2071    say("  Off leaves the card alone (a card with 8 GB or less starts Off beside a bigger card). Details: docs/MULTI_GPU.md.")
2072    by = {c["index"]: c for c in cards}
2073    for i in sorted(roles):
2074        say(f"    GPU {i + 1}  {gpu_roles.short_name(by[i]):<22} {by[i]['vram_gb']:>4.0f} GB   {roles[i].capitalize()}")
2075    for g in found:
2076        if gpu_problem(g, together=True) is not None and roles.get(g["index"]) == "off":
2077            say(f"     (GPU {g['index'] + 1}, {g['name']}: {gpu_problem(g, together=True)})")
2078    if ask("Use these roles?", ["y", "n"], "y", a.yes or a.check) == "n":
2079        while True:
2080            try:
2081                text = input("Roles, e.g. " + ",".join(f"{i}={r}" for i, r in sorted(roles.items())) + " (cards you leave out are Off): ").strip()
2082            except EOFError:
2083                fail("input ended before a setup answer was received", "run setup in a terminal, or pass --yes to accept the recommended roles")
2084            if not text:
2085                break
2086            try:
2087                roles = gpu_roles.roles_from_text(text, cards)
2088                break
2089            except ValueError as e:
2090                say(f"  {e}")
2091    roles = gpu_roles.normalize(roles, cards)
2092    lst = gpu_roles.order(roles, cards)
2093    if not lst:
2094        fail("every graphics card is Off", "setup needs one card for Main (the app and `strata launch` can start with all cards Off)")
2095    a._roles = roles
2096    a._roles_cards = cards
2097    ok(gpu_roles.describe(roles, cards))
2098    return 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
2103    that 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
2105    used to refuse the pair.  #642: the engines from RESIDENT_SPLIT_ENGINE run it on a split, so it is kept.  True
2106    when the config changed."""
2107    a = cfg.get("args", [])
2108    if "--resident-experts" not in a or resident_split():
2109        return False
2110    a[a.index("--resident-experts")] = "--mmap-experts"
2111    warn("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")
2115    return 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
2120    name on the Hub ("quant"; the catalog name of the v3.1 UD-IQ4_XS is another)."""
2121    return 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)."""
2126    return 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
2131    the repository's pinned one (HF_REVISIONS)."""
2132    base = fam["hf"].format(q=model_quant(model))
2133    rev = MODELS.get(model, {}).get("revision")
2134    return 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
2139    in 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."""
2140    pin = fam["sha256"][s.name]
2141    if s.exists() and s.name in fam.get("sha256_alt", {}):
2142        have = s.stat().st_size
2143        if have != pin[0]:
2144            for alt in fam["sha256_alt"][s.name]:
2145                if alt[0] == have:
2146                    return alt
2147    return pin
2148
2149
2150def model_shards(fam: dict, model: str) -> int:
2151    return 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)."""
2156    a = cfg.get("args", [])
2157    native = Path(a[a.index("--native") + 1]).name.upper() if "--native" in a and a.index("--native") + 1 < len(a) \
2158        else ""
2159    mine = [m for m, d in MODELS.items() if d.get("budget") and f"-{model_quant(m).upper()}-" in native]
2160    if 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
2161        count = re.search(r"-OF-(\d{5})\.GGUF$", native)
2162        mine = [m for m in mine if count and MODELS[m].get("shards") == int(count.group(1))] or mine
2163    return 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
2169    at 165 GiB (2x RTX 3090: MemAvailable never under 68 GiB); the 0-free case of #384 was 47 GB with a 70 GB model."""
2170    return 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
2175    the budget with a layer split (it exited with code 2), so the split runs without it - all the experts loaded into
2176    RAM at start - where the RAM holds the GGUFs and 24 GB more; else setup says so and asks (#737: a recommendation,
2177    not 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
2179    of it, the rest ranked by the whole expert profile - and the budget is that copy's size, so it is kept, as
2180    split_mmap keeps --resident-experts.  True when the config changed."""
2181    a = cfg.get("args", [])
2182    if "--resident-budget-gib" not in a or resident_split():
2183        return False
2184    model = budget_model(cfg)
2185    need, ram = unsloth_split_need_gb(model), ram_gb()
2186    if ram < need:
2187        confirm_risk(f"{model} cannot share its RAM budget across GPUs (the engine has no layer split with it), and "
2188                     f"without the budget it needs ~{need:.0f} GB of RAM (its GGUF files and {UNSLOTH_RAM_LEFT_GB} GB "
2189                     f"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,
2191                     f"{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)")
2193    i = a.index("--resident-budget-gib")
2194    del a[i:i + 2]
2195    ok(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)")
2197    return 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
2207    the CPU's activation quantization where no expert is left to it (dual RTX 4090: +63% mixed, +132% code over the
2208    plain 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
2210    config is not touched."""
2211    if len(gpu_sel(cfg.get("gpu"))) < 2:
2212        return
2213    args = cfg.setdefault("args", [])
2214    if off or cfg.get("remote_expert_opt") is False:
2215        if REMOTE_EXPERT_OPT in args:
2216            args.remove(REMOTE_EXPERT_OPT)
2217        return
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)
2220    pw = args.index("--pipeline-windows") if "--pipeline-windows" in args else -1
2221    if pw >= 0 and pw + 1 < len(args) and args[pw + 1] != "0":
2222        if REMOTE_EXPERT_OPT in args:
2223            warn("--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)")
2226        else:
2227            ok("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)")
2229        return
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).
2233    if not any(a.split("=", 1)[0] in HELPER_CACHE_FLAGS for a in args):
2234        return
2235    if REMOTE_EXPERT_OPT not in args:
2236        args.append(REMOTE_EXPERT_OPT)
2237        ok("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
2243    saved in its config)."""
2244    if isinstance(cfg.get("gpu"), list) or cfg.get("gpus_asked"):
2245        return cfg
2246    found = gpus()
2247    can = together_ok(found)
2248    if not can:
2249        return 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)
2253    budget = "--resident-budget-gib" in cfg.get("args", [])
2254    if budget and not resident_split() and ram_gb() < unsloth_split_need_gb(budget_model(cfg)):
2255        return cfg
2256    pair = can[:2]
2257    cfg["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
2260    resident = "--resident-experts" in cfg.get("args", []) and not resident_split()
2261    say()
2262    say("  This PC has " + " and ".join(gpu_name(g) for g in pair) + ": Strata can share the model across both.")
2263    say("  Together they hold about twice the model's experts and read prompts about 20% faster (docs/MULTI_GPU.md).")
2264    if resident:
2265        say("  This model runs in the low-RAM mode with its experts kept in RAM, on one GPU (recommended: steady RAM")
2266        say("  use). On both, the experts the GPUs do not hold are read through the OS file cache instead: faster in")
2267        say("  two reports (#364, #384), but RAM can fill up to 0 free during long prompts.")
2268    if budget and resident_split():
2269        say(f"  This model ({budget_model(cfg)}) runs on one GPU with a RAM budget of its experts (recommended: the tested")
2270        say("  setup). On both it keeps the budget: each card caches the experts of its own layers, and the RAM holds")
2271        say("  the hottest of the rest (#642).")
2272    elif budget:
2273        say(f"  This model ({budget_model(cfg)}) runs on one GPU with a RAM budget of its experts (recommended: the tested")
2274        say("  setup). On both it has no budget: all its experts are loaded into RAM at start, which this PC's RAM")
2275        say("  holds - about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s).")
2276    short = split_short(pair)             # #448: one card recommended (asked "n" by default), as for --resident
2277    for g in short:
2278        say(f"  {split_short_note(g)}.")
2279    tk = config_toolkit(cfg)
2280    missing = [g for g in pair if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))]
2281    if missing:
2282        say("  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))
2284    elif 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":
2286        cfg["gpu"] = [g["index"] for g in pair]
2287        cfg["layer_split"] = cfg.get("layer_split") or "auto"
2288        split_mmap(cfg)
2289        split_budget(cfg)
2290        recommend_remote_expert_opt(cfg)
2291        ok("from now on this model runs on " + " + ".join(gpu_name(g) for g in pair))
2292    else:
2293        ok("staying on one GPU (START-HERE.bat --gpus " + ",".join(str(g["index"]) for g in pair) + " switches)")
2294    write_config(cfg_path, cfg)
2295    return 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
2300    lower number).  None when there is no NVIDIA GPU.  The dict also says how many there are ("count")."""
2301    found = gpus()
2302    if not found:
2303        return None
2304    pick = GPU_PICK if pick is None else pick
2305    if pick is not None:
2306        g = next((x for x in found if x["index"] == pick), None)
2307        if g is None:
2308            fail(f"there is no GPU {pick}: " + ", ".join(f"{x['index']} = {x['name']}" for x in found))
2309    else:
2310        g = max(found, key=lambda x: (round(x["vram_gb"]), -x["index"]))
2311    return {**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
2317    PC - CUDA 12.9 with glibc 2.43 - is not taken instead)."""
2318    pick = os.environ.get("STRATA_NVCC")
2319    if pick:
2320        if not Path(pick).exists():
2321            warn(f"STRATA_NVCC={pick}: no such file; looking for a CUDA toolkit as usual")
2322        else:
2323            v = re.search(r"release (\d+)\.(\d+)", out([pick, "--version"]))
2324            ver = (int(v.group(1)), int(v.group(2))) if v else None
2325            if ver and below is not None and ver >= below:
2326                warn(f"STRATA_NVCC={pick} is CUDA {ver[0]}.{ver[1]}; this build needs one older than "
2327                     f"{below[0]}.{below[1]}")
2328                return (None, None)
2329            return (pick, ver) if ver else (None, None)
2330    cands = [shutil.which("nvcc")]
2331    for var in ("CUDA_PATH", "CUDA_HOME"):           # CUDA_HOME: Linux's usual name (#601)
2332        if os.environ.get(var):
2333            cands.append(str(Path(os.environ[var]) / "bin" / ("nvcc.exe" if WIN else "nvcc")))
2334    if WIN:
2335        base = Path(r"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA")
2336        if base.exists():
2337            cands += [str(p / "bin" / "nvcc.exe") for p in sorted(base.iterdir(), reverse=True)]
2338    else:
2339        cands += [str(p / "bin" / "nvcc") for p in sorted(Path("/usr/local").glob("cuda*"), reverse=True)]
2340        cands += [str(p / "bin" / "nvcc") for p in sorted(Path("/opt").glob("cuda*"), reverse=True)]   # Arch (#46)
2341    best = (None, None)
2342    for c in dict.fromkeys(cands):                     # every toolkit found; the newest wins
2343        if c and Path(c).exists():
2344            v = re.search(r"release (\d+)\.(\d+)", out([c, "--version"]))
2345            ver = (int(v.group(1)), int(v.group(2))) if v else None
2346            if ver and (below is None or ver < below) and (best[1] is None or ver > best[1]):
2347                best = (c, ver)
2348    return 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
2355    The version range is CUDA's requirement alone, so a caller with no CUDA (`cuda_v is None`) asks vswhere for no
2356    range at all: the CPU image encoder is built by MSVC, which is happy with any version (tools/hip/build_windows.bat
2357    already calls vswhere that way).  With the range applied to every caller, a machine whose only C++ tools are
2358    Visual Studio 2026 gets None back and nothing can be built there (#881).  STRATA_VCVARS=<vcvars64.bat> picks one
2359    by hand, for an install vswhere cannot use."""
2360    override = os.environ.get("STRATA_VCVARS")
2361    if override:
2362        v = Path(override)
2363        return v if v.exists() else None
2364    vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Microsoft Visual Studio/Installer/vswhere.exe"
2365    if not vswhere.exists():
2366        return 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
2369    args = [str(vswhere), "-latest", "-products", "*"]
2370    if cuda_v is not None:
2371        upper = "19.0" if tuple(cuda_v) >= (13, 3) else "18.0"
2372        args += ["-version", f"[17.0,{upper})"]      # 17 = Visual Studio 2022: the sources are C++20, and nvcc silently drops -std=c++20 under 2019 (#3566)
2373    args += ["-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"]
2374    p = out(args).strip()
2375    v = Path(p) / "VC/Auxiliary/Build/vcvars64.bat" if p else None
2376    return 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)."""
2384    try:
2385        done = subprocess.run([path, "--version"], capture_output=True, text=True, errors="replace", timeout=30)
2386    except (OSError, subprocess.SubprocessError):
2387        return False, ()
2388    if done.returncode != 0:
2389        return False, ()
2390    found = re.search(r"(\d+)\.(\d+)(?:\.(\d+))?", done.stdout or "")
2391    return 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,
2396    then ~/.local/bin.  One that does not run (a pip launcher whose Python is gone) is skipped, and so is a cmake older than the
2397    one CMakeLists.txt needs while another is found; with only an older one it is returned and the build says so."""
2398    exe = name + (".exe" if WIN else "")
2399    candidates = [str(d / exe) for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent) if (d / exe).exists()]
2400    on_path = shutil.which(name)
2401    if on_path and on_path not in candidates:
2402        candidates.append(on_path)
2403    local = Path.home() / ".local" / "bin" / exe
2404    if local.exists() and str(local) not in candidates:
2405        candidates.append(str(local))
2406    older = None
2407    for c in candidates:
2408        runs, version = _tool_version(c, name)
2409        if not runs:
2410            continue
2411        if name == "cmake" and version and version[:2] < CMAKE_MIN:
2412            older = older or c
2413            continue
2414        return c
2415    return older
2416
2417
2418def free_gb(path):
2419    path.mkdir(parents=True, exist_ok=True)
2420    return 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
2425    preparation, 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
2426    and 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
2427    files 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."""
2428    free = free or free_gb
2429    packs = pack_dir.parent
2430    free_models = free(models_dir)
2431    models_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")
2433    if free_models < other_gb:
2434        return models_problem
2435    if not copy_gb:
2436        return None
2437    free_packs = free(packs)
2438    try:
2439        same_drive = os.stat(models_dir).st_dev == os.stat(packs).st_dev
2440    except OSError:
2441        same_drive = False
2442    needs = copy_gb + (other_gb if same_drive else 0)
2443    if free_packs < needs:
2444        return (f"not enough free disk space for the low-RAM copy of the experts in {pack_dir}: it needs about {needs:.0f} GB "
2445                f"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.")
2447    return 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
2453    reused it ("already downloaded") instead of the published one (PR #324)."""
2454    z.unlink(missing_ok=True)
2455    z.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)."""
2475    raw = (os.environ.get("STRATA_DL_CONNECTIONS") or "").strip()
2476    try:
2477        n = int(raw) if raw else DL_CONNECTIONS
2478    except ValueError:
2479        n = DL_CONNECTIONS
2480    return 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."""
2504    raw = (headers.get("ETag") or "").strip()
2505    if raw[:2] in ("W/", "w/"):
2506        raw = raw[2:]
2507    return 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
2513    that fits, and the same object (ETag) as the first answer.  _NoRange: this server cannot be used with ranges;
2514    OSError: a bad answer worth asking again (another edge)."""
2515    if r.status != 206:
2516        raise _NoRange(f"HTTP {r.status}")
2517    m = _CONTENT_RANGE.match(r.headers.get("Content-Range") or "")
2518    if not m or (int(m.group(1)), int(m.group(2)), int(m.group(3))) != (pos, end, total):
2519        raise _NoRange(f"Content-Range {(r.headers.get('Content-Range') or '')!r} for bytes {pos}-{end}/{total}")
2520    cl = (r.headers.get("Content-Length") or "").strip()
2521    if cl and cl.isdigit() and int(cl) != end - pos + 1:
2522        raise OSError(f"Content-Length {cl} for {end - pos + 1} bytes asked")
2523    got = _etag(r.headers)
2524    if etag and got and got != etag:
2525        raise 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."""
2530    view = memoryview(data)
2531    f.seek(pos)
2532    done_n = 0
2533    while done_n < len(view):
2534        n = f.write(view[done_n:])
2535        if not n:
2536            raise OSError("the disk took no more bytes")
2537        done_n += n
2538
2539
2540def _read_exact(f, pos: int, n: int) -> bytes:
2541    f.seek(pos)
2542    parts = []
2543    while n > 0:
2544        b = f.read(n)
2545        if not b:
2546            break
2547        parts.append(b)
2548        n -= len(b)
2549    return 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."""
2554    q = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)
2555    try:
2556        if "Expires" in q:
2557            ttl = float(q["Expires"][0]) - time.time()
2558        elif "X-Amz-Expires" in q and "X-Amz-Date" in q:
2559            t0 = calendar.timegm(time.strptime(q["X-Amz-Date"][0], "%Y%m%dT%H%M%SZ"))
2560            ttl = t0 + float(q["X-Amz-Expires"][0]) - time.time()
2561        else:
2562            return None
2563    except (ValueError, OverflowError):
2564        return None
2565    return 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
2570    resolved once and reused; it is resolved again a little before it expires and after a 401/403/410."""
2571
2572    def __init__(self, url: str, total: int):
2573        self.url, self.total = url, total
2574        self.final, self.deadline = None, None
2575        self.etag = None                                 # the object the first answer named; every later answer must match
2576        self.lock = threading.Lock()
2577
2578    def resolve(self, stale=None) -> str:
2579        with self.lock:
2580            if stale is not None and self.final is not None and self.final != stale:
2581                return self.final                        # another connection already got a fresh address
2582            req = urllib.request.Request(self.url, headers={"User-Agent": "strata-setup", "Range": "bytes=0-0"})
2583            with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r:
2584                cr = (r.headers.get("Content-Range") or "").strip()
2585                if r.status != 206 or cr != f"bytes 0-0/{self.total}":
2586                    raise _NoRange(f"HTTP {r.status}, Content-Range {cr!r}")
2587                tag = _etag(r.headers)
2588                if self.etag and tag and tag != self.etag:
2589                    raise _Changed(f"the file on the server changed while it was downloaded ({self.etag[:12]} -> {tag[:12]})")
2590                self.etag = self.etag or tag
2591                r.read(1)
2592                final = r.geturl() or self.url
2593            ttl = _url_ttl(final)
2594            self.final = final
2595            self.deadline = time.monotonic() + max(ttl - 120, 0) if ttl else None
2596            return final
2597
2598    def get(self) -> str:
2599        with self.lock:
2600            cur, expired = self.final, self.deadline is not None and time.monotonic() >= self.deadline
2601        return 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
2607    def __init__(self, total: int, done: set, conns: int = 1):
2608        self.total, self.n, self.conns = total, -(-total // DL_CHUNK), conns
2609        self.done, self.flight = set(done), {}
2610        self.lock = threading.Lock()
2611        self.stop = threading.Event()                    # the whole download stops (Ctrl-C, a fatal error)
2612        self.abort_round = threading.Event()             # a piece failed for good: end this round, run the next
2613        self.fatal, self.errors = None, []
2614
2615    def size(self, i: int) -> int:
2616        return min((i + 1) * DL_CHUNK, self.total) - i * DL_CHUNK
2617
2618    def add(self, i: int, n: int):
2619        with self.lock:
2620            self.flight[i] = self.flight.get(i, 0) + n
2621
2622    def finish(self, i: int):
2623        with self.lock:
2624            self.flight.pop(i, None)
2625            self.done.add(i)
2626
2627    def have(self) -> int:
2628        with self.lock:
2629            return sum(self.size(i) for i in self.done) + sum(self.flight.values())
2630
2631    def snapshot(self) -> set:
2632        with self.lock:
2633            return set(self.done)
2634
2635
2636def _ranges(done) -> list:
2637    out = []
2638    for i in sorted(done):
2639        if out and out[-1][1] == i:
2640            out[-1][1] = i + 1
2641        else:
2642            out.append([i, i + 1])
2643    return 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."""
2648    i = 0
2649    while i in done:
2650        i += 1
2651    return 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."""
2657    side = part.with_name(part.name + ".chunks")
2658    n = -(-total // DL_CHUNK)
2659    try:
2660        size = part.stat().st_size if part.is_file() else None
2661    except OSError:
2662        size = None
2663    if side.is_file():
2664        try:
2665            data = json.loads(side.read_text(encoding="utf-8"))
2666            if data.get("v") == 1 and data.get("total") == total and data.get("chunk") == DL_CHUNK and size is not None:
2667                done = {i for a, b in data["done"] for i in range(int(a), min(int(b), n))}
2668                return {i for i in done if min((i + 1) * DL_CHUNK, total) <= size}
2669        except (OSError, ValueError, TypeError, KeyError):
2670            pass
2671        side.unlink(missing_ok=True)                    # not this file's list: start the file over
2672        part.unlink(missing_ok=True)
2673        return set()
2674    if size is None:
2675        return set()
2676    if size > total:
2677        part.unlink(missing_ok=True)
2678        return set()
2679    return 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
2684    list could not be written (an older list stays, which only costs re-downloading a few pieces after a stop)."""
2685    try:
2686        with open(part, "r+b") as g:
2687            os.fsync(g.fileno())
2688        side = part.with_name(part.name + ".chunks")
2689        tmp = side.with_name(side.name + ".tmp")
2690        tmp.write_text(json.dumps({"v": 1, "total": total, "chunk": DL_CHUNK, "done": _ranges(done)}), encoding="utf-8")
2691        with open(tmp, "r+b") as g:
2692            os.fsync(g.fileno())
2693        atomic.replace(tmp, side)
2694        return True
2695    except OSError:
2696        return 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
2701    names one).  A .part written from another address (the other mirror, another revision) or from another version of
2702    the file is dropped with its piece list: two sources are not mixed inside one file, even when they should hold the
2703    same bytes.  A .part from an older setup has no record and is kept as before."""
2704    src = part.with_name(part.name + ".src")
2705    try:
2706        old = json.loads(src.read_text(encoding="utf-8")) if src.is_file() else None
2707    except (OSError, ValueError):
2708        old = {}
2709    if old is not None:
2710        same = isinstance(old, dict) and old.get("url") == url and not (old.get("etag") and etag and old.get("etag") != etag)
2711        if not same:
2712            part.unlink(missing_ok=True)
2713            part.with_name(part.name + ".chunks").unlink(missing_ok=True)
2714            src.unlink(missing_ok=True)
2715            old = None
2716    if old is None or (etag and not old.get("etag")):
2717        try:
2718            src.write_text(json.dumps({"url": url, "etag": etag}), encoding="utf-8")
2719        except OSError:
2720            pass
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
2725    download left may have gaps behind it) and drop the list."""
2726    side = part.with_name(part.name + ".chunks")
2727    if not side.is_file():
2728        return
2729    try:
2730        data = json.loads(side.read_text(encoding="utf-8"))
2731        keep = _prefix_bytes({i for a, b in data["done"] for i in range(int(a), int(b))}, int(data["total"]))
2732        if data.get("chunk") != DL_CHUNK:
2733            keep = 0
2734    except (OSError, ValueError, TypeError, KeyError):
2735        keep = 0
2736    try:
2737        if part.is_file():
2738            with open(part, "r+b") as g:
2739                g.truncate(min(keep, part.stat().st_size))
2740    except OSError:
2741        part.unlink(missing_ok=True)
2742    side.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
2747    are spread over every connection and no single slow one holds the finish."""
2748    with st.lock:
2749        if not todo:
2750            return []
2751        n = max(1, min(DL_RUN, len(todo) // (2 * st.conns)))
2752        run = [todo.pop(0)]
2753        while len(run) < n and todo and todo[0] == run[-1] + 1:
2754            run.append(todo.pop(0))
2755        return 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
2760    when its last byte is down.  Every answer is checked to be exactly the range asked for (status, Content-Range, length,
2761    ETag); a connection that breaks continues from the byte it reached."""
2762    start = run[0] * DL_CHUNK
2763    end = min((run[-1] + 1) * DL_CHUNK, st.total) - 1
2764    pos, tries = start, 0
2765    with st.lock:
2766        for i in run:
2767            st.flight[i] = 0
2768    while True:
2769        if st.stop.is_set():
2770            return
2771        url, err, wait, ra = None, None, None, 0.0
2772        attempt_pos = pos
2773        try:
2774            url = src.get()
2775            req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={pos}-{end}"})
2776            with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r:
2777                _check_ranged(r, pos, end, st.total, src.etag)
2778                while pos <= end:
2779                    if st.stop.is_set():
2780                        return
2781                    cur = pos // DL_CHUNK
2782                    cur_end = min((cur + 1) * DL_CHUNK, st.total)             # one past the piece's last byte
2783                    b = r.read(min(1 << 20, cur_end - pos))
2784                    if not b:
2785                        raise IOError("the connection closed early")
2786                    try:
2787                        _write_all(f, pos, b)
2788                    except OSError as e:
2789                        raise _DiskError(str(e)) from e
2790                    pos += len(b)
2791                    st.add(cur, len(b))
2792                    if pos == cur_end:
2793                        st.finish(cur)
2794                        if pos <= end and st.abort_round.is_set():            # a piece failed for good: stop at a piece edge
2795                            with st.lock:
2796                                for i in run:
2797                                    if i not in st.done and st.flight.get(i) == 0:
2798                                        st.flight.pop(i, None)
2799                            return
2800            return
2801        except (_NoRange, _DiskError, _Changed):
2802            raise
2803        except urllib.error.HTTPError as e:
2804            err = e
2805            if e.code in (401, 403, 410) and url is not None:       # the signed address ran out: ask for a new one
2806                try:
2807                    src.resolve(stale=url)
2808                    wait = 0
2809                except (_NoRange, _Changed):
2810                    raise
2811                except (OSError, http.client.HTTPException):
2812                    pass
2813            elif e.code in (429, 503):
2814                try:
2815                    ra = min(float(e.headers.get("Retry-After") or 0), 60)
2816                except (TypeError, ValueError):
2817                    pass
2818        except (OSError, http.client.HTTPException) as e:
2819            err = 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.
2824        tries = 1 if pos > attempt_pos else tries + 1
2825        if tries >= DL_CHUNK_TRIES:
2826            raise _PieceFailed(str(err))
2827        st.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):
2831    try:
2832        with open(part, "r+b", buffering=0) as f:
2833            while not (st.stop.is_set() or st.abort_round.is_set()):
2834                run = _take_run(st, todo)
2835                if not run:
2836                    return
2837                _fetch_run(src, st, f, run)
2838    except _PieceFailed as e:
2839        st.errors.append(e)
2840        st.abort_round.set()
2841    except (_NoRange, _DiskError, _Changed) as e:
2842        st.fatal = st.fatal or e
2843        st.stop.set()
2844    except OSError as e:                                # the .part itself could not be opened
2845        st.fatal = st.fatal or _DiskError(str(e))
2846        st.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
2851    often with the bytes so far; it answers a sentence at most once a minute while nothing arrives, and None otherwise."""
2852
2853    AFTER = 120.0
2854
2855    def __init__(self, now: float = 0.0):
2856        self.have, self.since, self.said = -1, now, 0.0
2857
2858    def check(self, have: int, total: int, now: float) -> str | None:
2859        if have != self.have:
2860            self.have, self.since, self.said = have, now, 0.0
2861            return None
2862        idle = now - self.since
2863        if idle < self.AFTER or now - self.said < 60:
2864            return None
2865        self.said = now
2866        return (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
2875    is not (no DNS answer, no route, refused): that fails at once, with no wait and no message (offline users, owner 11-01)."""
2876    import errno
2877    import socket
2878    if isinstance(exc, urllib.error.HTTPError):
2879        return exc.code in (429, 500, 502, 503, 504)
2880    if isinstance(exc, urllib.error.URLError):
2881        if not isinstance(exc.reason, BaseException):
2882            return False
2883        exc = exc.reason
2884    if isinstance(exc, (socket.gaierror, ConnectionRefusedError)):
2885        return False
2886    if isinstance(exc, OSError) and exc.errno in (errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN):
2887        return False
2888    return 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
2893    50-100 GB download a single stream.  False: the server does not do ranges, or the probe failed (the caller then reads one stream)."""
2894    for attempt in range(len(waits) + 1):
2895        try:
2896            src.resolve()
2897            return True
2898        except _NoRange:
2899            return False
2900        except (OSError, http.client.HTTPException) as exc:
2901            if attempt >= len(waits) or not _probe_retryable(exc):
2902                return False
2903            sleep(waits[attempt])
2904    return 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
2909    does not do ranges (the caller reads the file in one stream)."""
2910    src = _Source(url, total)
2911    if not _probe_ranges(src):
2912        return False                                    # the one-stream path has its own retries and messages
2913    part.parent.mkdir(parents=True, exist_ok=True)
2914    _claim_part(part, url, src.etag)                    # a .part from another address or version is dropped here
2915    done = _load_pieces(part, total)
2916    st = _Pieces(total, done, conns)
2917    if not part.exists():
2918        part.touch()
2919    if not part.with_name(part.name + ".chunks").is_file() and not _save_pieces(part, total, done):
2920        return False                                    # no piece list can be kept here: the pieces would not be told from holes
2921    last_print = last_save = 0.0
2922    stall = StallNote(time.time())
2923
2924    def report(force=False):
2925        nonlocal last_print, last_save
2926        now = time.time()
2927        if now - last_print > 2 or force:
2928            last_print = now
2929            have = st.have()
2930            print(f"\r  {label}: {have / 1e9:6.2f} / {total / 1e9:.2f} GB ({100 * have / total:.0f}%)   ", end="", flush=True)
2931            note = stall.check(have, total, now)
2932            if note:
2933                print()
2934                warn(note)
2935        if now - last_save > DL_SAVE_EVERY:
2936            last_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
2941    clock = netpolicy.StallClock()
2942    idle_rounds, before = 0, -1
2943    try:
2944        while True:
2945            todo = [i for i in range(st.n) if i not in st.done]
2946            if not todo:
2947                break
2948            now_have = st.have()
2949            clock.progress(now_have)
2950            idle_rounds = 0 if now_have > before else idle_rounds + 1
2951            before = now_have
2952            if clock.expired() or idle_rounds >= DL_ROUNDS:
2953                break
2954            st.abort_round.clear()
2955            st.errors.clear()
2956            threads = [threading.Thread(target=_piece_worker, args=(src, st, todo, part), daemon=True)
2957                       for _ in range(min(conns, len(todo)))]
2958            for t in threads:
2959                t.start()
2960            while any(t.is_alive() for t in threads):
2961                for t in threads:
2962                    t.join(0.25)
2963                report()
2964            if st.fatal is not None:
2965                break
2966            if st.errors:
2967                print()
2968                warn(f"download interrupted ({st.errors[0]}); retrying in 10 s ...")
2969                _save_pieces(part, total, st.snapshot())
2970                time.sleep(10)
2971    except BaseException:
2972        st.stop.set()                                   # Ctrl-C: let the connections stop, keep what is finished
2973        _save_pieces(part, total, st.snapshot())
2974        raise
2975    report(force=True)
2976    print()
2977    if isinstance(st.fatal, _Changed):
2978        part.unlink(missing_ok=True)
2979        part.with_name(part.name + ".chunks").unlink(missing_ok=True)
2980        part.with_name(part.name + ".src").unlink(missing_ok=True)
2981        fail(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)")
2983    if isinstance(st.fatal, _DiskError):
2984        _save_pieces(part, total, st.snapshot())
2985        fail(f"cannot write {part.name}: {st.fatal}", "free some disk space (or pick another --models-dir) and run it again")
2986    if isinstance(st.fatal, _NoRange):
2987        _save_pieces(part, total, st.snapshot())
2988        return False                                    # the server stopped doing ranges: one stream from the unbroken start
2989    if len(st.done) < st.n:
2990        _save_pieces(part, total, st.snapshot())
2991        have = st.have()
2992        if clock.expired():                             # no new byte for 5 minutes (W6)
2993            fail(*clock.words(netpolicy.what_words(label), have, total))
2994        fail(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)")
2996    try:
2997        with open(part, "r+b") as g:
2998            g.truncate(total)
2999            os.fsync(g.fileno())
3000    except OSError:
3001        pass
3002    part.with_name(part.name + ".chunks").unlink(missing_ok=True)
3003    return 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
3008    written again.  A broken connection asks again from the block it reached (every block is final once compared)."""
3009    pos, end = i * DL_CHUNK, min((i + 1) * DL_CHUNK, st.total) - 1
3010    tries = 0
3011    while pos <= end:
3012        if st.stop.is_set():
3013            return
3014        url, wait, ra = None, None, 0.0
3015        before = pos
3016        try:
3017            url = src.get()
3018            req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={pos}-{end}"})
3019            with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r:
3020                _check_ranged(r, pos, end, st.total, src.etag)
3021                while pos <= end:
3022                    if st.stop.is_set():
3023                        return
3024                    b = r.read(min(1 << 20, end + 1 - pos))
3025                    if not b:
3026                        raise IOError("the connection closed early")
3027                    try:
3028                        if _read_exact(f, pos, len(b)) != b:
3029                            _write_all(f, pos, b)
3030                            with st.lock:
3031                                stats["bytes"] += len(b)
3032                                stats["pieces"].add(i)
3033                    except OSError as e:
3034                        raise _DiskError(str(e)) from e
3035                    pos += len(b)
3036                    st.add(i, len(b))
3037            return
3038        except (_NoRange, _DiskError, _Changed):
3039            raise
3040        except urllib.error.HTTPError as e:
3041            if e.code in (401, 403, 410) and url is not None:
3042                try:
3043                    src.resolve(stale=url)
3044                    wait = 0
3045                except (_NoRange, _Changed):
3046                    raise
3047                except (OSError, http.client.HTTPException):
3048                    pass
3049            elif e.code in (429, 503):
3050                try:
3051                    ra = min(float(e.headers.get("Retry-After") or 0), 60)
3052                except (TypeError, ValueError):
3053                    pass
3054            err = e
3055        except (OSError, http.client.HTTPException) as e:
3056            err = e
3057        tries = 1 if pos > before else tries + 1
3058        if tries >= DL_CHUNK_TRIES:
3059            raise _PieceFailed(str(err))
3060        st.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
3065    each block with the disk and write only the blocks that differ.  Returns (damaged pieces, pieces), or None when the
3066    server cannot do it (no ranges, or the file there is another one); the caller checks the SHA-256 again."""
3067    if not total or path.stat().st_size != total:
3068        return None
3069    src = _Source(url, total)
3070    try:
3071        src.resolve()
3072    except (_NoRange, _Changed, OSError, http.client.HTTPException):
3073        return None
3074    st = _Pieces(total, set(), conns)
3075    stats = {"bytes": 0, "pieces": set()}
3076    todo = list(range(st.n))
3077    errors = []
3078
3079    def worker():
3080        try:
3081            with open(path, "r+b", buffering=0) as f:
3082                while not st.stop.is_set():
3083                    with st.lock:
3084                        if not todo:
3085                            return
3086                        i = todo.pop(0)
3087                    _repair_piece(src, st, f, i, stats)
3088                    st.finish(i)
3089        except (_PieceFailed, _NoRange, _DiskError, _Changed, OSError) as e:
3090            errors.append(e)
3091            st.stop.set()
3092
3093    threads = [threading.Thread(target=worker, daemon=True) for _ in range(min(conns, st.n))]
3094    for t in threads:
3095        t.start()
3096    last = 0.0
3097    try:
3098        while any(t.is_alive() for t in threads):
3099            for t in threads:
3100                t.join(0.25)
3101            if time.time() - last > 2:
3102                last = time.time()
3103                have = st.have()
3104                print(f"\r  {label}: {have / 1e9:6.2f} / {total / 1e9:.2f} GB ({100 * have / total:.0f}%)   ", end="", flush=True)
3105    except BaseException:
3106        st.stop.set()
3107        raise
3108    print()
3109    if errors:
3110        warn(f"could not compare {path.name} with the server again ({errors[0]})")
3111        return None
3112    try:
3113        with open(path, "r+b") as g:
3114            os.fsync(g.fileno())
3115    except OSError:
3116        pass
3117    return 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).
3122    A 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
3125    clock = netpolicy.StallClock()
3126    idle, before = 0, -1
3127    while True:
3128        have = part.stat().st_size if part.exists() else 0
3129        clock.progress(have)
3130        idle, before = (0 if have > before else idle + 1), have
3131        if clock.expired():
3132            fail(*clock.words(netpolicy.what_words(label), have, total))
3133        if idle >= 30:
3134            break
3135        if total and have >= total:                    # stopped after the last byte, before the rename: nothing to
3136            break                                      # ask for (a range past the end is a 416, retried 30 times)
3137        try:
3138            req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={have}-"})
3139            with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r:
3140                if have:
3141                    m = _CONTENT_RANGE.match(r.headers.get("Content-Range") or "")
3142                    if r.status != 206 or not m or int(m.group(1)) != have or (total and int(m.group(3)) != total):
3143                        if r.status != 200:              # another range: its bytes are not the file's; ask again from the start
3144                            part.unlink(missing_ok=True)
3145                            raise OSError(f"the server answered another range than bytes {have}- (HTTP {r.status})")
3146                        have = 0                         # the server ignored the range and sent the whole file: start over
3147                elif r.status not in (200, 206):
3148                    raise OSError(f"HTTP {r.status}")
3149                with open(part, "ab" if have else "wb") as f:
3150                    last = 0.0
3151                    while True:
3152                        b = r.read(8 << 20)
3153                        if not b:
3154                            break
3155                        if total and have + len(b) > total:
3156                            raise OSError("the server sent more bytes than the file has")
3157                        f.write(b)
3158                        have += len(b)
3159                        if time.time() - last > 2:
3160                            last = time.time()
3161                            size = f"{have / 1e9:6.2f} / {total / 1e9:.2f} GB ({100 * have / total:.0f}%)" if total                                 else f"{have / 1e6:7.1f} MB"
3162                            print(f"\r  {label}: {size}   ", end="", flush=True)
3163                    f.flush()
3164                    os.fsync(f.fileno())
3165            print()
3166            if not total or have >= total:
3167                break
3168        except (OSError, http.client.HTTPException) as e:
3169            print()
3170            if part.exists() and total and part.stat().st_size > total:
3171                part.unlink(missing_ok=True)             # more than the file has can only be wrong bytes
3172            warn(f"download interrupted ({e}); retrying in 10 s ...")
3173            time.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."""
3179    try:
3180        req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": "bytes=0-0"})
3181        with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r:
3182            m = re.match(r"\s*bytes 0-0/(\d+)\s*$", r.headers.get("Content-Range") or "")
3183            return int(m.group(1)) if r.status == 206 and m else 0
3184    except (OSError, http.client.HTTPException):
3185        return 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).
3190    A finished file gets a <name>.done mark, so a later run skips it without asking the server."""
3191    dst.parent.mkdir(parents=True, exist_ok=True)
3192    if dst.exists() and done(dst):
3193        ok(f"{what or dst.name} already downloaded")
3194        return
3195    pin_here = file_pin(url) if url.startswith(("http://", "https://")) else None
3196    if 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
3199        say(f"  checking {dst.name} (SHA-256) ...")
3200        if _hash_file(dst, pin_here[0]) == pin_here[1]:
3201            mark(dst, f"sha256 {pin_here[1]}")
3202            ok(f"{what or dst.name} is already here (checked)")
3203            return
3204    bad = dst.with_name(dst.name + ".bad")
3205    if 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
3207        if bad.stat().st_size == pin_here[0] and _hash_file(bad, pin_here[0]) == pin_here[1]:
3208            os.replace(bad, dst)
3209            mark(dst, f"sha256 {pin_here[1]}")
3210            ok(f"{what or dst.name} is already here (checked)")
3211            return
3212    acquisition.require(what or dst.name)
3213    if not url.startswith(("http://", "https://")):
3214        src = Path(url[7:] if url.startswith("file://") else url)
3215        if not src.exists():
3216            fail(f"not found: {src}")
3217        shutil.copyfile(src, dst)
3218        mark(dst)
3219        ok(f"{what or dst.name} copied")
3220        return
3221    ms = ms_file(url) if model_source() == "modelscope" else None
3222    if ms is not None:
3223        if reachable(ms_url(*ms), timeout=netpolicy.FIRST_CONNECT_S):
3224            url = ms_url(*ms)
3225        else:
3226            warn(f"{what or dst.name}: ModelScope does not answer; downloading it from {hf_endpoint()}")
3227            ms = None
3228    part = dst.with_name(dst.name + ".part")
3229    total = 0
3230    # the file's pinned size and SHA-256, when it has them (ModelScope's copy is checked against the same pin)
3231    pin = REPO_PINS.get(ms[0], {}).get(ms[1].rsplit("/", 1)[-1]) if ms is not None else file_pin(url)
3232    for _unpinned in range(2):                         # the size: one request under the network rule (no more 5 x 60 s in silence)
3233        try:
3234            req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"})
3235            with _open_net(req) as r:
3236                total = int(r.headers.get("Content-Length", 0) or 0)
3237            break
3238        except urllib.error.HTTPError as e:
3239            if e.code == 404 and hf_unpinned(url) != url:  # the pinned revision is gone from the repository
3240                if not allow_unpinned():
3241                    fail(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")
3243                warn(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)")
3245                url = hf_unpinned(url)
3246                pin = None
3247                continue
3248            fail(f"cannot reach {url.split('/')[2]} ({e})",
3249                 "check your internet connection and run it again" + proxy_hint() + source_hint(url))
3250        except tls.CertificateProblem as e:           # the same answer every time: no retry
3251            fail(f"cannot download from {url.split('/')[2]}: its security certificate was not accepted", str(e))
3252        except netpolicy.NetFailure as e:
3253            net_fail(e, url, what)
3254        except (OSError, http.client.HTTPException) as e:
3255            fail(f"cannot reach {url.split('/')[2]} ({e})",
3256                 "check your internet connection and run it again" + proxy_hint() + source_hint(url))
3257    if not total:
3258        total = range_total(url)
3259    meta = ms_meta(*ms) if ms is not None else None
3260    if not total:                                  # published size also governs partial-file completion
3261        total = pin[0] if pin else (meta[0] if meta else 0)
3262    if pin and total and total != pin[0]:              # not the pinned file: stop before the download, not after
3263        fail(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)")
3265    label = what or dst.name
3266    if bad.is_file() and not dst.exists() and total:
3267        try:
3268            if shutil.disk_usage(dst.parent).free < total + (1 << 30):
3269                bad.unlink()                           # no room for the new copy beside the kept one
3270                say(f"  Not enough free space for a new copy of {dst.name} beside the kept one ({bad.name}): the kept file was removed.")
3271        except OSError:
3272            pass
3273    conns = dl_connections()
3274    fixed = pin if pin else (meta if meta is not None and meta[1] else None)
3275    again = (lambda: repair_download(url, dst, total, label, conns)) if total >= DL_MIN_PARALLEL and conns > 1 else None
3276    if dst.exists() and total and dst.stat().st_size == total:    # finished by an older setup (no mark yet), or stopped before the check
3277        if fixed:                                      # a file that has a fixed hash is checked, not just marked
3278            verify_sha256(dst, *fixed, repair=again)
3279            drop_bad(dst)
3280        else:
3281            mark(dst)
3282        ok(f"{what or dst.name} already downloaded")
3283        return
3284    if not (total >= DL_MIN_PARALLEL and conns > 1 and parallel_download(url, part, total, label, conns, dst.name)):
3285        _claim_part(part, url)
3286        download_single(url, part, total, label)
3287    if total and part.stat().st_size != total:
3288        fail(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)")
3290    try:
3291        atomic.replace(part, dst)                      # waits a moment for a virus scanner or indexer that holds the file
3292    except OSError as e:
3293        fail(f"cannot finish {dst.name}: {e}", "close any program that has the file open and run setup again")
3294    for side in (".chunks", ".src"):
3295        part.with_name(part.name + side).unlink(missing_ok=True)
3296    if pin:
3297        verify_sha256(dst, *pin, repair=again)         # the fixed hash: a wrong file is repaired, else kept as .bad and setup stops
3298        drop_bad(dst)
3299    elif meta is not None and meta[1]:
3300        verify_sha256(dst, meta[0], meta[1], repair=again)   # ModelScope's published hash; kept in the finish mark
3301        drop_bad(dst)
3302    else:
3303        if ms is not None:
3304            warn(f"{what or dst.name}: ModelScope publishes no SHA-256 for it: the file is not verified")
3305        mark(dst)
3306    ok(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)."""
3311    sys.path.insert(0, str(ROOT / "tools"))
3312    from gguf_reader import GGUFFile
3313    try:
3314        g = GGUFFile(s)
3315        return s.stat().st_size >= g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors),
3316                                                     default=0)
3317    except (OSError, ValueError, struct.error):
3318        return 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
3324    A 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"
3325    made 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
3326    was 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
3327    yet), 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
3328    own 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
3329    family with no Hugging Face folder of its own (`hf` None: the NVFP4 families download a file list, not shards)."""
3330    for s in shards:
3331        if not (s.exists() and not done(s) and whole_shard(s)):
3332            continue
3333        if not own and hf is not None and file_pin(hf + s.name) is not None:
3334            continue
3335        try:
3336            mark(s, "whole (checked against its own tensor directory)")
3337        except OSError as e:                           # a read-only folder (--gguf-dir on a share): the file is still whole
3338            warn(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
3346    engine and tools/iq_pack.py do.  The published name first; else the one first shard in the folder whose name has
3347    the size in it (an upload split or named differently: -00001-of-00003, Unsloth's ...-00001-of-00004.gguf).  A
3348    missing shard is check_shards' error later, as before."""
3349    first = folder / model_file(fam, model, 1)
3350    if not first.exists():
3351        found = 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))
3353        other = 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
3354        found = [p for p in found if not other(p)]
3355        mine = [p for p in found if model.lower() in p.name.lower() or model_quant(model).lower() in p.name.lower()]
3356        pick = mine if mine else found
3357        if len(pick) == 1:
3358            first = pick[0]
3359    m = SHARD_NAME.search(first.name)
3360    total = int(m.group(2)) if m else 1
3361    if not m or total < 1:
3362        return [first]
3363    stem = first.name[:m.start()]
3364    return [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))"
3369                        r"(?=-\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."""
3380    m = GGUF_QUANT.search(name)
3381    return 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
3386    the original's sizes: the size tells them apart)."""
3387    for f, d in FAMILIES.items():
3388        if d.get("ready"):                             # ready-made packs (NVFP4): no GGUF shards to match
3389            continue
3390        for m in MODELS:
3391            if f in MODELS[m].get("families", ("qwen", "swift")) and name == model_file(d, m, 1):
3392                return f, m
3393    return 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
3398    Strata cannot run (Unsloth's UD-IQ3_XXS taken for IQ3_XXS by its name), or it is missing and the folder holds
3399    other GGUFs - then the hint names the --family/--model of the usable ones.  None otherwise (a missing shard in a
3400    folder without GGUFs stays check_shards' "missing")."""
3401    bad = gguf_unsupported(first.name) if first.exists() else None
3402    if bad:
3403        why = UNSUPPORTED_WHY.get(bad.upper())
3404        return f"{first.name} is {bad}, a GGUF Strata cannot run", SUPPORTED_GGUFS + (".\n       " + why if why else "")
3405    if first.exists():
3406        return None
3407    firsts = sorted(p.name for p in folder.glob("*.gguf")
3408                    if not p.name.lower().startswith("mmproj") and (not SHARD_NAME.search(p.name)
3409                                                                     or SHARD_NAME.search(p.name).group(1) == "00001"))
3410    usable = list(dict.fromkeys(c for c in map(gguf_choice, firsts) if c))
3411    unusable = [n for n in firsts if gguf_unsupported(n)]
3412    if not usable and not unusable:
3413        return None
3414    hint = SUPPORTED_GGUFS
3415    if unusable:
3416        hint += ".\n       Not usable here: " + ", ".join(unusable)
3417        for q in dict.fromkeys(gguf_unsupported(n) for n in unusable):
3418            if q and q.upper() in UNSUPPORTED_WHY:
3419                hint += ".\n       " + UNSUPPORTED_WHY[q.upper()]
3420    if usable:
3421        hint += ".\n       Usable here: " + ", ".join(f"--family {f} --model {m}" for f, m in usable)
3422    return f"{folder} has no {fam['title']} {model} file", hint
3423
3424
3425def _hash_file(s: Path, size: int) -> str:
3426    h = hashlib.sha256()
3427    seen, last = 0, 0.0
3428    with open(s, "rb") as f:
3429        while True:
3430            b = f.read(16 << 20)
3431            if not b:
3432                break
3433            h.update(b)
3434            seen += len(b)
3435            if time.time() - last > 2 and size >= (1 << 30):    # a figure for the app and the Terminal: hashing 60 GB takes minutes
3436                last = time.time()
3437                print(f"\r  checking {s.name}: {seen / 1e9:6.2f} / {size / 1e9:.2f} GB ({100 * seen // size}%)   ", end="", flush=True)
3438    if seen >= (1 << 30):
3439        print()
3440    return 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)."""
3445    try:
3446        from strata_control import gguf_preflight
3447        gguf_preflight.inspect_metadata(Path(path))
3448        return True
3449    except Exception:                                  # noqa: BLE001 - anything unreadable is "not whole"
3450        return 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
3455    is 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
3456    back when it now matches; a successful new download of the file, or too little free space for it, removes the .bad file (drop_bad).
3457    Returns the .bad path, or None when the file could not be renamed (it is then deleted, as before)."""
3458    bad = s.with_name(s.name + ".bad")
3459    try:
3460        bad.unlink(missing_ok=True)                    # at most one .bad per file
3461        os.replace(s, bad)
3462        return bad
3463    except OSError:
3464        s.unlink(missing_ok=True)
3465        return 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."""
3470    try:
3471        dst.with_name(dst.name + ".bad").unlink(missing_ok=True)
3472    except OSError:
3473        pass
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,
3478    so 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
3480    piece 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."""
3482    m = s.with_name(s.name + ".done")
3483    kept = mark_text(s)
3484    if kept is not None and any(f"sha256 {x}" in kept for x in (sha, *also)):
3485        return
3486    have = s.stat().st_size if s.exists() else -1
3487    if 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
3489        warn(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")
3491        return
3492    if have != size:
3493        if own:                                        # --gguf-dir: the person's own file is never deleted by setup
3494            fail(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")
3496        fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)")
3497    say(f"  checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...")
3498    digest = _hash_file(s, size)
3499    server_same = False                                # the repair read the whole file from the server and found no block that differs
3500    if digest != sha and repair is not None and not own:
3501        say(f"  Some parts of {s.name} were damaged; downloading only those parts again.")
3502        res = repair()
3503        server_same = res is not None and res[0] == 0
3504        if res is not None:
3505            say(f"  {res[0]} of {res[1]} parts were different and have been written again; checking the whole file again ...")
3506            digest = _hash_file(s, size)
3507        else:
3508            say("  The damaged parts could not be found this way.")
3509    if digest != sha and digest in also:
3510        say(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")
3511        mark(s, f"sha256 {digest}")
3512        return
3513    if digest != sha:
3514        if own and own_gguf_is_whole(s):
3515            warn(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")
3517            return
3518        if own:
3519            fail(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")
3521        keep_bad(s)                                    # kept as <name>.bad, not thrown away (see keep_bad)
3522        m.unlink(missing_ok=True)
3523        if server_same:
3524            hint = ("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")
3526        else:
3527            hint = "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"
3528        fail(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)
3529    mark(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."""
3534    repo = MODELS[model]["repo"]
3535    t = NVFP4_REPOS[repo]
3536    return [(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
3541    engine reads the prepared files only, so the ~95 GB of safetensors need not stay (or come back) on the disk."""
3542    files = ready_files(model)
3543    if MODELS[model].get("prepare") and prepared_done(model, models_dir):
3544        files = [f for f in files if not f[3].startswith("tensors/")]
3545    return 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
3550    pack folder is whole as the engine reads it)."""
3551    return 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."""
3556    return 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)."""
3561    d = prepared_dir(model, models_dir)
3562    return 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
3567    own draft layer, "mtp", and no separate embedding: the token embedding is in its dense GGUF)."""
3568    if MODELS[model].get("prepare"):
3569        d = prepared_dir(model, models_dir)
3570        return {"pack": d / "pack", "dense": d / "dense.gguf", "ple": d / "ple-nvfp4.gguf", "mtp": d / "mtp"}
3571    out = {}
3572    for f in ready_files(model):
3573        p = ready_where(models_dir, f)
3574        if f[0] == "pack" and p.name == "index.txt":
3575            out["pack"] = p.parent
3576        elif f[0] in ("dense", "ple", "embd"):
3577            out[f[0]] = p
3578    return 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)."""
3583    try:
3584        return p.is_file() and f"sha256 {sha}" in (mark_text(p) or "")
3585    except OSError:
3586        return 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
3591    ready-made pack, linked instead of downloaded (the PLE table and the embedding); or downloaded from its pinned
3592    revision and checked against its size and SHA-256 (a wrong file is deleted and setup stops)."""
3593    others = [(ready_where(models_dir, g), g[5]) for m in MODELS if MODELS[m].get("repo") for g in ready_files(m)]
3594    for f in ready_needed(model, models_dir):
3595        dst, size, sha = ready_where(models_dir, f), f[4], f[5]
3596        if ready_verified(dst, sha):
3597            ok(f"{f[3]} already downloaded")
3598            continue
3599        src = next((p for p, s in others if s == sha and p != dst and ready_verified(p, s)), None)
3600        if src is not None and not dst.exists():
3601            try:
3602                dst.parent.mkdir(parents=True, exist_ok=True)
3603                os.link(src, dst)
3604                mark(dst, f"sha256 {sha}")
3605                ok(f"{f[3]}: the same file as {src} (linked, not downloaded again)")
3606                continue
3607            except OSError:
3608                pass                                   # another drive: downloaded
3609        download(f"{hf_endpoint()}/{f[1]}/resolve/{f[2]}/{f[3]}", dst, f"{f[1].split('/')[-1]}: {f[3]}")
3610        verify_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
3615    24 for the OS, the engine and the file cache the other experts are read through, less a KV cache streamed to
3616    RAM; at most all of them, at least 8.  64 GB: 40, the measured setting (docs/UNSLOTH_Q4.md)."""
3617    gib = round(ram) - UNSLOTH_RAM_LEFT_GB - math.ceil(kv_ram_gb)
3618    return 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
3631    N), a unified-memory APU (#1715: there the budget and the GPU's cache are the same RAM, and the all-in-RAM mode was
3632    measured 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.
3634    Round 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
3635    the 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
3636    the 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)."""
3638    return asked is not None or (bool((gpu or {}).get("uma")) and not uma_holds_experts(model, ram, gpu)) or \
3639        ram < 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
3644    measured 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"):
3645    the sets measured under the budget mode (UD-IQ4_XS, UD-Q4_K_XL, ...) keep their plans."""
3646    if sys.platform == "darwin" or not MODELS.get(model, {}).get("uma_pool_auto") or not (gpu or {}).get("uma"):
3647        return False                                   # (a Mac never reaches this: metal/setup_mac.py and mac_control_setup have their own plans; the check keeps it so)
3648    shared = float((gpu or {}).get("vram_gb") or 0.0)
3649    if shared <= 0:
3650        return False
3651    from strata_control import uma_pool
3652    arena_gib = MODELS[model]["arena_gb"] / 1.073741824
3653    return (uma_pool.FIXED_GIB + arena_gib + uma_pool.MARGIN_GIB <= uma_pool.pool_gib(shared)
3654            and 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
3659    wherever the model can read them - the original Flash-Next, Swift and Coder files, Unsloth's, NVFP4 - on every make of card; which
3660    reader 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
3661    VRAM (no --vram-reserve-mib), so a small card is no exception."""
3662    return 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
3675    GPU encoder on a card of 24 GB and more and the CPU encoder below that: a picture then takes a few seconds, the text
3676    keeps the ~1 GB of VRAM for experts.  --vision gpu is always kept (with a note on a small card); --vision cpu is kept."""
3677    vram = float((gpu or {}).get("vram_gb") or 0.0)
3678    small = 0 < vram < IMAGES_GPU_ENCODER_MIN_VRAM_GB
3679    if asked == "gpu" and small:
3680        warn(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)")
3683    if asked == "yes":
3684        return "cpu" if small else "gpu"
3685    return 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
3694    budget has not taken yet: a 128 GB box with a 55 GiB budget and the desktop open was killed by the OOM killer.  So
3695    there setup writes a number, not `auto`: the RAM less UNSLOTH_RAM_LEFT_GB less the budget (and a KV cache streamed
3696    to 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."""
3698    slot_gib = MODELS[model]["arena_gb"] * 1e9 / UMA_EXPERTS * 1.1 / 2**30
3699    room = ram - UNSLOTH_RAM_LEFT_GB - budget_gib - math.ceil(kv_ram_gb)
3700    slots = min(UMA_EXPERTS, int(room / slot_gib))
3701    return 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
3706    cache 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
3707    the 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
3708    lowered to what the pool holds, and a budget the person set too is only warned about (recommend, never force)."""
3709    try:
3710        from strata_control import uma_pool
3711        args = cfg.get("args")
3712        fixed = uma_pool.fixed_cache_and_budget(args) if gpu.get("uma") and isinstance(args, list) else None
3713        if fixed is None:
3714            return
3715        cache, budget = fixed
3716        arena = MODELS[model]["arena_gb"]
3717        shared = float(gpu.get("vram_gb") or 0.0)
3718        if shared <= 0 or not uma_pool.too_much(cache, budget, arena, shared):
3719            return
3720        fit = uma_pool.safe_budget_gib(cache, arena, shared)
3721        own = "--resident-budget-gib" in user_args.flat(user_args.groups(cfg.get(user_args.USER_KEY)))
3722        if fit >= budget:
3723            return
3724        if own:
3725            warn(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 "
3726                 f"(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 "
3727                 f"of budget fits that cache; kept as you chose (--resident-budget-gib in the config's user_args)")
3728            return
3729        args[args.index("--resident-budget-gib") + 1] = f"{fit:g}"
3730        warn(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, "
3731             f"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")
3733    except Exception as e:                             # noqa: BLE001 - a recommendation, never a reason to stop setup
3734        say(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).
3739    More than the recommendation is kept, with what it risks (the owner's rule: setup recommends, it never forces)."""
3740    rec = resident_budget_gib(model, ram)
3741    if asked is None:
3742        return rec
3743    if asked > rec:
3744        warn(f"a {asked:g} GiB RAM budget is more than setup recommends for this PC ({rec} GiB: the RAM less "
3745             f"{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")
3748    return 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
3753    its own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part
3754    renamed by hand, a download finished by an older setup) otherwise passes as a model file and the engine
3755    fails much later, at the first tensor that runs past the end."""
3756    sys.path.insert(0, str(ROOT / "tools"))
3757    from gguf_reader import GGUFFile
3758    for s in shards:
3759        if not s.exists():
3760            fail(f"missing {s}")
3761        try:
3762            g = GGUFFile(s)
3763        except (ValueError, struct.error) as e:
3764            fail(f"{s.name} is not a whole GGUF shard ({e})", "delete it and run setup again")
3765        need = g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors), default=0)
3766        have = s.stat().st_size
3767        if 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
3770            need = min(need, have)
3771        if have < need:
3772            fail(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)")
3774        if 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")
3777            fail(f"{s.name} is longer than its tensor: {have:,} bytes, {need:,} expected ({have - need:,} extra)",
3778                 f"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.
3790    The 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."""
3792    own = os.environ.get("STRATA_GGUF_PY")
3793    if own and (Path(own) / "gguf").is_dir():
3794        return Path(own)
3795    return 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
3800    use llama.cpp's gguf-py instead of tools/strata_gguf.py); empty by default, so the tools use their own."""
3801    own = os.environ.get("STRATA_GGUF_PY")
3802    return {"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
3807    from third_party/strata-ggml and nothing is downloaded."""
3808    own = os.environ.get("STRATA_GGML_DIR")
3809    return 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."""
3814    return [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."""
3819    return 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."""
3824    if (gguf_py_dir() / "gguf").is_dir():
3825        ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py for the preparation tools)")
3826    return 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."""
3831    return 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")."""
3836    return 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."""
3841    lines = []
3842    for raw in (path or REQUIREMENTS).read_text(encoding="utf-8").splitlines():
3843        line = raw.split("#", 1)[0].strip()
3844        if line:
3845            lines.append(line)
3846    return 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`
3854    and `strata monitor` need them; the packaged Terminal bundles them, a source install gets them here)."""
3855    base = requirement_lines() if REQUIREMENTS.exists() else list(PY_PACKAGES)
3856    if MONITOR_REQUIREMENTS.exists():
3857        base += [r for r in requirement_lines(MONITOR_REQUIREMENTS) if r not in base]
3858    return base
3859
3860
3861def _installed(name: str) -> bool:
3862    try:
3863        import importlib.metadata as md
3864        md.distribution(name)
3865        return True
3866    except Exception:
3867        return 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)."""
3872    import importlib.util
3873    return [m for m in ("numpy", "jinja2", "regex", "yaml", "tqdm", "requests", "PIL", "psutil")
3874            if 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
3879    the stamp of the other one, which then says "already installed" about packages this Python does not have. A marker beside the stamp
3880    names the system that wrote it; an older stamp without a marker is believed only while the packages every run needs can be imported."""
3881    marker = stamp.with_name(stamp.name + ".os")
3882    try:
3883        if marker.exists():
3884            return marker.read_text(encoding="utf-8").strip() == sys.platform
3885    except OSError:
3886        return False
3887    import importlib.util
3888    return 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
3893    requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the
3894    pinned dependencies it already has count as installed."""
3895    if CONTROL:                                        # the app ships these (hash-locked); nothing is installed here
3896        missing = control_missing_packages()
3897        if missing:
3898            fail("this copy of Strata Control lacks " + ", ".join(missing), "reinstall the Strata app")
3899        ok(f"{what}: bundled with the app")
3900        return
3901    stamp = Path(sys.prefix) / ".strata-pip.json"
3902    have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() and pip_stamp_is_ours(stamp) else []
3903    bare = {p.lower() for p in have if req_name(p) == p.lower()}
3904    need = [p for p in packages if p not in have and req_name(p) not in bare
3905            and not (bare and "==" in p and _installed(req_name(p)))]
3906    if not need:
3907        ok(f"{what} already installed")
3908        return
3909    acquisition.require(what)
3910    say(f"  Installing {what} ...")
3911    run([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", *extra, *need])
3912    stamp.write_text(json.dumps(sorted(set(have) | set(need)), indent=0))
3913    stamp.with_name(stamp.name + ".os").write_text(sys.platform, encoding="utf-8")
3914    ok(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)."""
3923    try:
3924        lines = NVFP4_LOCAL_REQUIREMENTS.read_text(encoding="utf-8").splitlines()
3925    except OSError:
3926        return []
3927    return [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
3933    already there is kept.  The app does not ship them (hundreds of MB): it says so and points at the source installer."""
3934    import importlib.util
3935    missing = [m for m in NVFP4_LOCAL_MODULES if importlib.util.find_spec(m) is None]
3936    if not missing:
3937        return
3938    if CONTROL:
3939        fail("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")
3941    pkgs = nvfp4_local_packages()
3942    if not pkgs:
3943        fail("requirements-nvfp4-local.txt is missing", "update Strata, or run: python -m pip install torch transformers safetensors")
3944    say("  Converting NVIDIA's checkpoint needs PyTorch, transformers and safetensors (a few hundred MB, installed once).")
3945    pip_install(pkgs, "PyTorch, transformers and safetensors (for the FP4-Local conversion)",
3946                extra=[] if WIN else ["--extra-index-url", "https://download.pytorch.org/whl/cpu"])   # Linux: the CPU build, not 3 GB of CUDA libraries
3947    importlib.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).
3952    toolkit 12: the CUDA 12 wheels' cuBLAS and runtime, in two folders (nvidia/cublas/bin, nvidia/cuda_runtime/bin)."""
3953    if int(toolkit) == 12:
3954        patterns = ("cublas64_12.dll", "cudart64_12.dll") if WIN else ("libcublas.so.12*", "libcudart.so.12*")
3955    else:
3956        patterns = ("cublas64_13.dll",) if WIN else ("libcublas.so.13*",)
3957    dirs = []
3958    for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}:
3959        for pattern in patterns:
3960            for hit in (sp / "nvidia").rglob(pattern) if (sp / "nvidia").is_dir() else []:
3961                if hit.parent not in dirs:
3962                    dirs.append(hit.parent)
3963    return [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):
4046    return 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)."""
4051    return 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."""
4056    m = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)(?:[a-z]+(\d+))?", version)
4057    return 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."""
4062    return sorted({m for m in re.findall(r"rocm-(\d+\.\d+\.\d+(?:[a-z]+\d+)?)\.(?:tar\.gz|whl)", html or "")
4063                   if 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
4068    7.x line, else the newest of the same major (the note says so); `preferred` unchanged when the list is empty (the
4069    index could not be read: pip then reports its own error) or nothing of that major exists (the note says so)."""
4070    if not available or preferred in available:
4071        return preferred, None
4072    want = rocm_vkey(preferred)
4073    for same, what in ((lambda k: k[:2] == want[:2], "line"), (lambda k: k[0] == want[0], "major")):
4074        hits = [v for v in available if same(rocm_vkey(v))]
4075        if hits:
4076            got = max(hits, key=rocm_vkey)
4077            return got, (f"ROCm {preferred} is not on this index any more: using {got}, the newest of the same {what} "
4078                         f"(set STRATA_ROCM_VERSION to choose another)")
4079    return preferred, (f"ROCm {preferred} is not on this index and nothing of its major version is: "
4080                       f"{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
4085    page's html (None: fetched from <index>/rocm/; a failed fetch keeps the preferred version)."""
4086    if ROCM_VERSION_OVERRIDE:
4087        version, note = ROCM_VERSION_OVERRIDE, None
4088    else:
4089        preferred = ROCM_FAMILY_PINS.get(rocm_family(index), ROCM_VERSION_DEFAULT)
4090        if listing is None:
4091            try:
4092                req = urllib.request.Request(index.rstrip("/") + "/rocm/", headers={"User-Agent": "strata-setup"})
4093                with _urlopen(req, timeout=30) as r:
4094                    listing = r.read().decode("utf-8", "replace")
4095            except (OSError, ValueError):
4096                listing = ""
4097        version, note = rocm_pick(rocm_index_versions(listing), preferred)
4098    if rocm_family(index) == "gfx1151" and (rocm_vkey(version) or (9, 0))[:2] < (7, 11):
4099        note = ((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")
4102    return 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
4113                0x150E: "gfx1150",                                    # Strix Point: Radeon 880M / 890M
4114                0x1114: "gfx1152", 0x1902: "gfx1152",                 # Krackan Point (Krackan2): Radeon 840M / 860M
4115                0x15BF: "gfx1103", 0x15C8: "gfx1103", 0x164F: "gfx1103",   # Phoenix: Radeon 740M / 760M / 780M
4116                0x1900: "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-")
4123    is exactly `name`, never a prefix: gfx1150 and gfx1152 are not gfx1151 (and gfx1151 is not gfx115)."""
4124    arch = str(arch or "")
4125    return arch == name or arch.startswith(name + ":")
4126
4127
4128def is_strix_halo(g) -> bool:
4129    return 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."""
4137    return 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."""
4148    if not is_rdna2(gpu):
4149        return []
4150    return ["  " + 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
4155    the opt-in gfx1150 (Strix Point) / gfx1103 (Phoenix / Hawk Point) iGPUs.  Everything else is a discrete card."""
4156    arch = g.get("arch") if isinstance(g, dict) else None
4157    return (is_strix_halo(g)
4158            or (GFX1150_OPT_IN and gfx_arch_is(arch, "gfx1150"))
4159            or (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."""
4165    return 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
4170    maintainers' box) and the GPU also reaches shared system memory (Linux: the GTT pool, `mem_info_gtt_total`, half the
4171    RAM unless the kernel was told otherwise; Windows: "shared GPU memory", half the RAM).  The shared part IS the RAM
4172    the model's experts live in, so it is not extra room beside the RAM.  g gets: uma, dedicated_gb (the carve-out: the
4173    only 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."""
4175    if g.get("uma") or not is_uma_apu(g):
4176        return g
4177    ram = ram_gb() if ram is None else ram
4178    carve = max(0.0, float(g.get("vram_gb") or 0.0))
4179    shared = gtt_gb if gtt_gb > 0 else ram / 2
4180    shared = max(0.0, min(shared, ram - UMA_OS_LEFT_GB))
4181    g.update({"uma": True, "dedicated_gb": carve, "shared_gb": shared, "vram_gb": carve + shared})
4182    return 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
4187    carve-out only (its shared memory is the RAM itself)."""
4188    return 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."""
4193    if g.get("uma"):
4194        return (f"unified memory: {g['dedicated_gb']:.1f} GB BIOS carve-out + {g['shared_gb']:.0f} GB shared with the "
4195                f"RAM, {g['vram_gb']:.0f} GB usable by the GPU")
4196    return 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
4208    VRAM and the RAM together."""
4209    return 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:
4226    Gyro-S, or the Coder).  With less RAM than the size's own figure the low-RAM mode starts by itself and the model is
4227    slower.  A recommendation: every size stays a choice."""
4228    for floor, fam, m in MEMORY_TIERS:
4229        if ram + vram - TIER_SYSTEM_RESERVE_GB >= floor:
4230            return fam, m
4231    return 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)."""
4236    pick = tier_pick(ram, vram)
4237    if not gyro or pick != ("swift", "IQ2_XS"):
4238        return ""
4239    return ("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
4245    family has it, else the family's recommended size when this PC's RAM fits it (UD-Q4_K_XL before UD-IQ4_XS), else
4246    the largest size that fits, else the first.  Recommend, never force: every other size stays a choice."""
4247    tier = tier_pick(ram, vram)
4248    if tier and tier[1] in names and family in ("qwen", "swift"):
4249        return tier[1]
4250    for m in RECOMMENDED_SIZES.get(family, ()):
4251        if m in names and mem_have(m, ram, vram) >= MODELS[m]["ram_gb"]:
4252            return m
4253    fitting = [m for m in names if mem_have(m, ram, vram) >= MODELS[m]["ram_gb"]]
4254    if fitting:
4255        return max(fitting, key=lambda m: MODELS[m]["download_gb"])
4256    return "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:
4260    rec, have = m in RECOMMENDED_SIZES.get(family, ()), m == installed
4261    return " (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
4266    run again (SETUP.bat, --setup) pre-selects it: the 0.1.44 recommendation (IQ3_S, about 15% slower than IQ3_XXS and
4267    7 GB more RAM) is for a first install, and Enter must not move an installed model to another size."""
4268    for c in have:
4269        try:
4270            ch = choices_from_config(c)
4271        except (OSError, ValueError, KeyError, TypeError, IndexError):
4272            continue
4273        if ch.get("family") == family and ch.get("model") in names:
4274            return ch["model"]
4275    return 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.
4280    STRATA_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
4281    or 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).
4282    STRATA_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
4283    writes nothing for it.
4284    STRATA_ROUTE_TAIL_SKIP=0 where every expert is in RAM (the skip costs KL there); the RAM-budget mode keeps it.
4285    0.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."""
4288    env = {}
4289    if family != "unsloth":
4290        return env
4291    if model in ("UD-Q5_K_XL", "UD-Q6_K_XL"):
4292        env["STRATA_MMQ_KQ"] = "1"
4293    gfx12_linux = hip and not WIN and str(arch or "").lower().startswith(("gfx1200", "gfx1201"))
4294    if not in_budget and not gfx12_linux:
4295        env["STRATA_ROUTE_TAIL_SKIP"] = "0"
4296    return 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
4301    engines have no NVFP4 kernels), so on those the menu does not offer them; `--family nvfp4` still says why not."""
4302    return [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
4307    RTX cards the experts run at 8-bit precision, which measured slower than UD-IQ4_XS (docs/NVFP4.md)."""
4308    try:
4309        arch = int((gpu or {}).get("arch") or 0)
4310    except (TypeError, ValueError):
4311        arch = 0
4312    if arch >= 120:
4313        return "native FP4 on this card"
4314    return "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
4319    on AVX-512 rows when the CPU has them, else on AVX2 rows (bit-equal to ggml's AVX2 dot).  Measured (docs/NVFP4.md):
4320    per core the AVX2 rows are ~10% slower, and on a whole pool that reads DRAM the two are the same speed up to two
4321    tokens a window (Ryzen 7 255: 58.9 vs 58.7 GB/s) and ~12% apart at four.  A note only: nothing is refused."""
4322    if avx512 or not avx2:
4323        return ""                                      # no AVX2 at all: the older-CPU build's own warning says it
4324    return ("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."""
4330    if family == "nvfp4":
4331        d = MODELS["NVFP4"]
4332        cpu = nvfp4_cpu_note(avx2, avx512)
4333        return (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 "") + "]")
4335    if family == "unsloth" and hip:
4336        return "   [UD-IQ4_XS is the 4-bit choice on AMD and Intel cards; NVFP4 runs on NVIDIA only]"
4337    if family == "gyro":
4338        return ("   [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 "") + "]")
4340    return ""
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)
4345    holds it - the model docs/STRIX_HALO.md measures.  A recommendation only: the menus still list every size."""
4346    return 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).
4351    None when they are, else a sentence for the user.  A missing /dev/kfd is not this problem (no driver / no ROCm)."""
4352    kfd = os.path.join(dev, "kfd")
4353    if not os.path.exists(kfd):
4354        return None
4355    bad = [kfd] if not access(kfd, os.R_OK | os.W_OK) else []
4356    bad += [n for n in sorted(listing(os.path.join(dev, "dri", "renderD*"))) if not access(n, os.R_OK | os.W_OK)]
4357    if not bad:
4358        return None
4359    return (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
4366    the Strix Halo text, which is about another chip (gfx1151).  Opt-in only (STRATA_EXPERIMENTAL_GFX1103=1)."""
4367    notes = [f"  Radeon 780M / 760M class (gfx1103, Ryzen 7040 / 8040): the CPU and the GPU share one memory pool ({ram:.0f} GB "
4368             f"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."]
4370    notes.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.")
4374    if not WIN and gpu.get("shared_gb", 0) < 0.75 * ram - 1:
4375        notes.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")
4378    return 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
4383    the Strix Halo text, which is about another chip (gfx1151).  Opt-in only (STRATA_EXPERIMENTAL_GFX1150=1)."""
4384    notes = [f"  Radeon 890M / 880M class (gfx1150, Strix Point): the CPU and the GPU share one memory pool ({ram:.0f} GB "
4385             f"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."]
4387    notes.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).")
4391    if not WIN and gpu.get("shared_gb", 0) < 0.75 * ram - 1:
4392        notes.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")
4395    return 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."""
4400    if is_strix_halo(gpu):
4401        return strix_halo_notes(gpu, ram)
4402    if GFX1150_OPT_IN and gfx_arch_is(gpu.get("arch"), "gfx1150"):
4403        return gfx1150_notes(gpu, ram)
4404    if gfx_arch_is(gpu.get("arch"), "gfx1103"):
4405        return gfx1103_notes(gpu, ram)
4406    return []
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
4411    the 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."""
4412    out = []
4413    used = {g["index"] for g in chosen}
4414    for g in amd:
4415        if g.get("uma") and g["index"] not in used and g.get("dedicated_gb", 0.0) > 16:
4416            out.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 "
4417                       f"{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")
4419    return 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
4424    memory settings that give the GPU room.  Nothing is changed or refused: recommend, never force."""
4425    notes = [f"  Strix Halo (gfx1151, Ryzen AI Max): the CPU and the GPU share one memory pool ({ram:.0f} GB seen by the "
4426             f"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."]
4428    notes.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.")
4431    if not WIN and gpu.get("shared_gb", 0) < 0.75 * ram - 1:
4432        notes.append(f"!the GPU can reach {gpu.get('shared_gb', 0):.0f} GB of shared memory (the GTT pool; the kernel's "
4433                     f"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")
4436    if gpu.get("dedicated_gb", 0.0) > 16:
4437        notes.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")
4440    if strix_halo_recommends(gpu, ram):
4441        notes.append(f"  Recommended model: {STRIX_HALO_MODEL} (the one docs/STRIX_HALO.md measures); the menus list the "
4442                     "others.")
4443    return 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
4448    shared LPDDR5X), then the most memory.  A Strix Halo beside a Radeon RX / PRO card is therefore left to --gpu N."""
4449    return (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
4455    same without ROCm; this one only names a card the topology does not list (a kernel without /dev/kfd)."""
4456    found = []
4457    base = Path(sysfs) / "class/drm"
4458    if not base.is_dir():
4459        return found
4460    for card in sorted(base.glob("card[0-9]*")):
4461        if not card.name[4:].isdigit():
4462            continue
4463        try:
4464            dev = card / "device"
4465            if int((dev / "vendor").read_text().strip(), 16) != 0x1002:
4466                continue
4467            did = int((dev / "device").read_text().strip(), 16)
4468        except (OSError, ValueError):
4469            continue
4470        row = {"pci_id": did, "arch": AMD_IGPU_PCI.get(did, ""), "vram_gb": 0.0, "gtt_gb": 0.0}
4471        for key, f in (("vram_gb", "mem_info_vram_total"), ("gtt_gb", "mem_info_gtt_total")):
4472            try:
4473                row[key] = int((dev / f).read_text()) / 2 ** 30
4474            except (OSError, ValueError):
4475                pass
4476        found.append(row)
4477    return 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:
4482    the GPU nodes in order, the CPU nodes skipped.  Integrated GPUs are listed too (not supported).
4483    sysfs: the tree to read (tools/test_setup_amd.py passes a mocked one).  Windows: amd_gpus_win."""
4484    if WIN:
4485        return amd_gpus_win()
4486    base = Path(sysfs) / "class/kfd/kfd/topology/nodes"
4487    found = []
4488    if not base.is_dir():
4489        return found
4490    for node in sorted((p for p in base.iterdir() if p.name.isdigit()), key=lambda p: int(p.name)):
4491        try:
4492            props = {}
4493            for line in (node / "properties").read_text().splitlines():
4494                k, _, v = line.partition(" ")
4495                props[k] = v.strip()
4496            ver = int(props.get("gfx_target_version") or 0)
4497            if ver == 0 or int(props.get("simd_count") or 0) == 0:
4498                continue
4499        except (OSError, ValueError):
4500            continue
4501        arch = f"gfx{ver // 10000}{(ver // 100) % 100:x}{ver % 100:x}"
4502        dev = Path(sysfs) / f"class/drm/renderD{props.get('drm_render_minor', '')}/device"
4503        try:
4504            vram = int((dev / "mem_info_vram_total").read_text()) / 2 ** 30
4505        except (OSError, ValueError):
4506            vram = 0.0
4507        try:
4508            name = (dev / "product_name").read_text().strip() or f"AMD Radeon ({arch})"
4509        except OSError:
4510            name = f"AMD Radeon ({arch})"
4511        if name == f"AMD Radeon ({arch})" and arch in AMD_NAMES:
4512            name = AMD_NAMES[arch]
4513            if gfx_arch_is(arch, STRIX_HALO_ARCH) and int(props.get("simd_count") or 0) in STRIX_HALO_BY_SIMDS:
4514                name = (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
4516        try:
4517            gtt = int((dev / "mem_info_gtt_total").read_text()) / 2 ** 30
4518        except (OSError, ValueError):
4519            gtt = 0.0
4520        g = {"index": len(found), "name": name, "vram_gb": vram, "arch": arch, "driver": "amdgpu", "vendor": "amd"}
4521        try:
4522            g["pci_id"] = int((dev / "device").read_text().strip(), 16)
4523        except (OSError, ValueError):
4524            pass
4525        found.append(amd_apply_uma(g, gtt))            # Strix Halo: unified memory (carve-out + shared)
4526    return found
4527
4528
4529def amd_problem(g):
4530    if g["arch"] not in AMD_ARCHS:
4531        return (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 ""))
4533    if g.get("cannot_run"):                            # Windows: the installed engine's own check (--list-devices)
4534        return g["cannot_run"]
4535    return 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
4540    the display-adapter order (amd_gpus_windows)."""
4541    hip = hip_devices()
4542    if not hip:
4543        return amd_gpus_windows()
4544    halo = [g for g in hip if is_uma_apu(g)]
4545    if halo:                                           # an APU: the HIP runtime's figure is not the BIOS carve-out
4546        reg = [r for r in amd_gpus_windows() if is_uma_apu(r)]
4547        for k, g in enumerate(halo):
4548            reported = g["vram_gb"]
4549            g["vram_gb"] = reg[k]["dedicated_gb"] if k < len(reg) else 0.0
4550            amd_apply_uma(g)
4551            g["vram_gb"] = max(g["vram_gb"], reported)
4552    return 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
4557    most VRAM first).  Every chosen card must be one Strata supports (AMD_ARCHS; they may be of different
4558    architectures: the engine is compiled for each).  Returns the cards, the main one first."""
4559    usable = [g for g in amd if amd_problem(g) is None]
4560    if 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.
4563        own = [g for g in usable if not g.get("uma")]
4564        sel = [g["index"] for g in sorted(own if len(own) >= 2 else usable, key=amd_rank)]
4565        left = [g for g in usable if g["index"] not in sel]
4566        if left and len(own) >= 2:
4567            say("  --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")
4569    else:
4570        try:
4571            sel = [int(x) for x in str(text).split(",") if x.strip()]
4572        except ValueError:
4573            fail(f"--gpus takes AMD GPU numbers as setup lists them, e.g. --gpus 1,0 (or --gpus all), not {text!r}")
4574    if len(sel) < 2 or len(set(sel)) != len(sel):
4575        fail("--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 "")))
4578    byid = {g["index"]: g for g in amd}
4579    for i in sel:
4580        g = byid.get(i)
4581        p = "not found on this PC" if g is None else amd_problem(g)
4582        if p is not None:
4583            fail(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}")
4586    return [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
4601                0x747E: "gfx1101",                                                  # RX 7800 XT / 7700 XT
4602                0x7480: "gfx1102",                                                  # RX 7600 / 7600 XT
4603                0x7590: "gfx1200",                                                  # RX 9060 XT
4604                0x7550: "gfx1201", 0x7551: "gfx1201",                               # RX 9070 / 9070 XT, AI PRO R9700
4605                0x73BF: "gfx1030", 0x73AF: "gfx1030", 0x73A5: "gfx1030",            # RX 6800 / 6800 XT / 6900 XT / 6950 XT
4606                0x73DF: "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."""
4623    ps = ("[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 }")
4626    text = out(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps])
4627    found = []
4628    for line in (text or "").splitlines():
4629        parts = line.strip().split("|")
4630        if len(parts) >= 2 and parts[1]:
4631            ram = parts[2] if len(parts) > 2 else ""
4632            found.append({"name": parts[0].strip(), "pnp": parts[1].strip(),
4633                          "ram": int(ram) if ram.strip().isdigit() else 0})
4634    return 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
4639    at 4 GB), from the display-class registry key - readable without admin."""
4640    found = []
4641    try:
4642        import winreg
4643        cls = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _DISPLAY_CLASS)
4644    except (ImportError, OSError):
4645        return found
4646    i = 0
4647    while True:
4648        try:
4649            sub = winreg.EnumKey(cls, i)
4650        except OSError:
4651            break
4652        i += 1
4653        if not sub.isdigit():
4654            continue
4655        try:
4656            key = winreg.OpenKey(cls, sub)
4657        except OSError:
4658            continue
4659        vals = {}
4660        for name in ("DriverDesc", "MatchingDeviceId", "HardwareInformation.qwMemorySize", "DriverVersion"):
4661            try:
4662                vals[name] = winreg.QueryValueEx(key, name)[0]
4663            except OSError:
4664                pass
4665        found.append(vals)
4666    return found
4667
4668
4669def _pci_device_id(text: str) -> int | None:
4670    m = re.search(r"VEN_1002&DEV_([0-9A-F]{4})", str(text or ""), re.I)
4671    return 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)."""
4677    if device_id in _WIN_AMD_DID:
4678        return _WIN_AMD_DID[device_id]
4679    return 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
4684    installed), with the arch Strata would run them as ("" = unknown: listed, not supported).  adapters / registry:
4685    tools/test_setup_amd.py passes mocked ones."""
4686    adapters = _win_display_adapters() if adapters is None else adapters
4687    registry = _win_display_registry() if registry is None else registry
4688    if not adapters:                                   # no WMI answer: the registry alone (it can list removed cards)
4689        adapters = [{"name": r.get("DriverDesc", ""), "pnp": r.get("MatchingDeviceId", ""), "ram": 0} for r in registry]
4690    used = set()
4691    found = []
4692    for ad in adapters:
4693        did = _pci_device_id(ad.get("pnp"))
4694        if did is None:
4695            continue                                   # not an AMD (VEN_1002) PCI device
4696        vram, driver = 0.0, ""
4697        for k, r in enumerate(registry):               # the same card's driver instance: its 64-bit VRAM size
4698            if k in used or _pci_device_id(r.get("MatchingDeviceId")) != did:
4699                continue
4700            if (r.get("DriverDesc") and ad.get("name") and "\ufffd" not in ad["name"]
4701                    and r["DriverDesc"].strip() != ad["name"].strip()):
4702                continue
4703            used.add(k)
4704            mem = r.get("HardwareInformation.qwMemorySize")
4705            if isinstance(mem, bytes):
4706                mem = int.from_bytes(mem[:8], "little")
4707            vram = int(mem) / 2 ** 30 if isinstance(mem, int) and mem > 0 else 0.0
4708            driver = str(r.get("DriverVersion") or "")
4709            break
4710        if vram == 0.0 and ad.get("ram", 0) > 0:
4711            vram = ad["ram"] / 2 ** 30                 # WMI's 32-bit figure (at most 4 GB)
4712        arch = win_amd_arch(did, ad.get("name", ""))
4713        name = ad.get("name") or AMD_NAMES.get(arch, f"AMD Radeon (device {did:04X})")
4714        g = {"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}
4716        found.append(amd_apply_uma(g))                 # Strix Halo: the registry's figure is the BIOS carve-out only
4717    return 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 -
4723    on Windows that is PATH, where the ready-made HIP engine keeps hipblas.dll / libhipblaslt.dll in its rocm/bin and the
4724    loader finds them only through PATH (#2372: a launch without it shows a "not found" dialog per DLL and prints
4725    nothing); on Linux and elsewhere it is LD_LIBRARY_PATH, where a probe without it exits 127 on libhipblas.so.3 and
4726    prints nothing."""
4727    env = dict(os.environ)
4728    dirs = [str(d) for d in hip_lib_dirs(eng)]
4729    if dirs:
4730        var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
4731        env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else []))
4732    return 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
4737    component folder (the app and `strata update` keep it there, #3418: with only engine/ looked at, the app numbered the cards in
4738    display-adapter order and an iGPU on HIP ordinal 0 made "GPU 0" the wrong card)."""
4739    name = "strata-device.exe" if WIN else "strata-device"
4740    own = ROOT / "engine" / name
4741    if own.exists():
4742        return own
4743    try:
4744        from strata_control import engine_component as EC
4745        found = EC.resolve(backend="hip", full=False)
4746        return Path(found.root) / name
4747    except Exception:                                  # noqa: BLE001 - no component, a damaged one: the old answer
4748        return 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)."""
4755    if text is None:
4756        probe = probe or hip_probe_path()
4757        hip_engine = False
4758        for record in ("BUILD.json", "engine-component.json"):     # a checkout's build record, or a component's manifest
4759            try:
4760                hip_engine = json.loads((probe.parent / record).read_text(encoding="utf-8-sig")).get("backend") == "hip"
4761            except (OSError, ValueError, AttributeError):
4762                continue
4763            if hip_engine:
4764                break
4765        if not probe.exists() or not hip_engine:
4766            return None
4767        try:
4768            hip_runtime_beside_exe(probe.parent)       # #468 #461: not the driver's System32 copy
4769            r = subprocess.run([str(probe), "--list-devices"], capture_output=True, text=True, errors="replace", timeout=120,
4770                               cwd=str(probe.parent), env=engine_env(probe.parent))
4771        except (OSError, subprocess.TimeoutExpired):
4772            return None
4773        if r.returncode != 0:
4774            return None
4775        text = r.stdout
4776    found = []
4777    for line in text.splitlines():
4778        m = re.match(r"device\s+(\d+):\s*(.*)$", line.strip())
4779        if m:
4780            found.append({"index": int(m.group(1)), "name": m.group(2).strip(), "vram_gb": 0.0, "arch": "",
4781                          "driver": "hip", "vendor": "amd"})
4782            continue
4783        if not found:
4784            continue
4785        a = re.match(r"arch\s+(gfx[0-9a-f]+)\s*,\s*([\d.]+)\s*GiB", line.strip())
4786        if a and not found[-1]["arch"]:
4787            found[-1]["arch"], found[-1]["vram_gb"] = a.group(1), float(a.group(2))
4788        elif line.strip().startswith("cannot run:"):
4789            found[-1]["cannot_run"] = line.strip()[len("cannot run:"):].strip()
4790    for g in found:
4791        if not g["arch"]:
4792            g["arch"] = "unknown"
4793        if g["arch"] in AMD_NAMES and g["name"] in ("", "AMD Radeon Graphics"):
4794            g["name"] = AMD_NAMES[g["arch"]]
4795    return 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/)."""
4800    try:
4801        rel = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("lib_dirs") or []
4802    except (OSError, ValueError):
4803        rel = []
4804    return [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
4817    their PE import tables and followed recursively (tools/hip/dll_closure.py).  #461: amdhip64_7.dll imports
4818    rocm_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
4820    hipErrorInvalidDeviceFunction.  Falls back to the names above when the helper cannot be read."""
4821    roots = sorted({p.name for pat in HIP_RUNTIME_DLLS for p in d.glob(pat)})
4822    try:
4823        sys.path.insert(0, str(ROOT / "tools" / "hip"))
4824        from dll_closure import dll_closure
4825        return dll_closure(d, roots)
4826    except Exception:                                  # noqa: BLE001 - a missing helper must not stop setup
4827        return roots
4828    finally:
4829        if str(ROOT / "tools" / "hip") in sys.path:
4830            sys.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
4835    missing or different (a 0.1.34 install, whose zip had them in rocm/bin only, is fixed on its next start; a
4836    0.1.40.2 install, which got only the two runtime DLLs, gets rocm_kpack.dll and the C++ runtime now, #461)."""
4837    for d in hip_lib_dirs(eng):
4838        for name in hip_runtime_closure(d):
4839            src = d / name
4840            dst = eng / src.name
4841            try:
4842                if dst.exists() and dst.stat().st_size == src.stat().st_size and \
4843                        dst.stat().st_mtime >= src.stat().st_mtime:
4844                    continue
4845                shutil.copy2(src, dst)
4846            except OSError as e:                   # e.g. the engine is running and holds the old copy
4847                warn(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
4853    architecture, k = the card's rank among the listed cards of that architecture.  None when HIP has no such card."""
4854    same = [g["index"] for g in listed if g["arch"] == card["arch"]]
4855    k = same.index(card["index"]) if card["index"] in same else 0
4856    cand = [g for g in hip if g["arch"] == card["arch"]]
4857    return 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
4862    engine itself before the model download: an integrated Radeon is HIP's device 0 (#325), and a PC without a
4863    working AMD driver stops here with what to install."""
4864    hip = hip_devices(eng / "strata-device.exe")
4865    hint = (f"install or update the AMD driver (AMD Software: Adrenalin Edition) from {WIN_AMD_DRIVER}, restart the "
4866            f"PC and run this again; {eng / 'strata-device.exe'} --list-devices shows what the HIP runtime sees")
4867    if not hip:
4868        fail("the AMD HIP runtime finds no GPU (the ready-made engine's device check)", hint)
4869    m = hip_match(gpu, listed, hip) if gpu.get("driver") != "hip" else \
4870        next((x for x in hip if x["index"] == gpu["index"]), None)
4871    if m is None:
4872        fail(f"the HIP runtime does not list your {gpu['name']} ({gpu['arch']})", hint)
4873    if amd_problem(m):
4874        fail(f"HIP device {m['index']} ({m['name']}) cannot be used: {amd_problem(m)}")
4875    if gpu.get("driver") != "hip" and m["index"] != gpu["index"]:
4876        ok(f"HIP numbers this card {m['index']} (an integrated GPU comes first): the engine is pointed at it")
4877    vram = gpu["vram_gb"] if gpu.get("uma") else (m["vram_gb"] or gpu["vram_gb"])   # an APU: not the runtime's figure
4878    return {**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
4883    per 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
4885    zip's do.  None when it cannot be had (no internet, nothing for this card): the caller goes on as before."""
4886    acquisition.require("the ready-made engine")
4887    from strata_control import engine_component as ec
4888    store = home() / "engine-feed"
4889    env = dict(os.environ)
4890    env.pop("STRATA_NO_ACQUIRE", None)
4891    env["STRATA_COMPONENTS_DIR"] = str(store)
4892    say("  Fetching the ready-made engine from the signed update feed ...")
4893    try:
4894        run = subprocess.run([sys.executable, str(ROOT / "strata.py"), "update", "--no-control", "--output", "json"],
4895                             env=env, cwd=str(ROOT), capture_output=True, text=True, errors="replace", timeout=3600)
4896    except (OSError, subprocess.SubprocessError) as e:
4897        warn(f"the update feed could not be run ({e})")
4898        return None
4899    if run.returncode != 0:
4900        why = (run.stderr or run.stdout or "").strip().splitlines()[-1:] or [f"exit {run.returncode}"]
4901        warn(f"no engine from the update feed: {why[0][:200]}")
4902        return None
4903    try:
4904        component = ec.resolve(store, full=True)
4905    except ec.ComponentProblem as e:
4906        warn(f"the engine from the update feed is not usable: {e}")
4907        return None
4908    eng.mkdir(exist_ok=True)
4909    tmp = eng / "_unpack"
4910    shutil.rmtree(tmp, ignore_errors=True)
4911    shutil.copytree(component.root, tmp)
4912    try:
4913        meta = json.loads((tmp / "BUILD.json").read_text(encoding="utf-8"))
4914    except (OSError, ValueError):
4915        meta = {}
4916    if meta.get("source") != "prebuilt":                # the setup's own books: a ready-made engine, not one compiled here
4917        meta["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
4920    install_unpacked(tmp, eng)
4921    shutil.rmtree(tmp, ignore_errors=True)
4922    if not (eng / EXE).exists():
4923        fail("the engine package from the update feed has no " + EXE)
4924    if not WIN:
4925        for x in (EXE, VEXE):
4926            if (eng / x).exists():
4927                (eng / x).chmod(0o755)
4928    ok(f"ready-made engine {meta.get('version', '')} from the update feed ({component.root.name})")
4929    return 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."""
4935    acquisition.require("the ready-made AMD engine")
4936    eng = ROOT / "engine"
4937    info = eng / "BUILD.json"
4938    if info.exists() and (eng / EXE).exists():
4939        try:
4940            meta = json.loads(info.read_text(encoding="utf-8"))
4941        except ValueError:
4942            meta = {}
4943        ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())
4944        if meta.get("backend") == "hip" and meta.get("source") == "prebuilt" and ver >= WIN_HIP_MIN_ENGINE and \
4945                gpu["arch"] in arch_names(meta.get("archs")) and not updating:
4946            ok("ready-made AMD engine already installed")
4947            return eng
4948    if not url_base:
4949        return None
4950    eng.mkdir(exist_ok=True)
4951    z = eng / WIN_HIP_ASSET
4952    bases = prebuilt_bases(url_base)
4953    for i, base in enumerate(bases):
4954        if not base.startswith(("http://", "https://")):
4955            break
4956        try:
4957            req = urllib.request.Request(base + WIN_HIP_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"})
4958            _urlopen(req, timeout=60).close()
4959            break
4960        except OSError as e:
4961            if i + 1 < len(bases):
4962                say(f"  No ready-made AMD engine for v{source_version()} ({e}): the latest release instead")
4963                continue
4964            warn(f"no ready-made AMD engine at {base} ({e})")
4965            return engine_from_feed(eng, updating)
4966    say("  Downloading the ready-made Strata engine for AMD GPUs (with the ROCm libraries it uses) ...")
4967    download(base + WIN_HIP_ASSET, z, "Strata AMD engine")
4968    try:
4969        verify_engine_archive(z, WIN_HIP_ASSET, base)
4970    except UnverifiedEngine as e:
4971        engine_refused(WIN_HIP_ASSET, e, updating)
4972        return None
4973    tmp = eng / "_unpack"
4974    shutil.rmtree(tmp, ignore_errors=True)
4975    with zipfile.ZipFile(z) as f:
4976        f.extractall(tmp)
4977    try:
4978        meta = json.loads((tmp / "BUILD.json").read_text(encoding="utf-8"))
4979    except (OSError, ValueError):
4980        meta = {}
4981    ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())
4982    why = None
4983    if meta.get("backend") != "hip" or not (tmp / EXE).exists():
4984        why = "it is not a HIP engine"
4985    elif ver < WIN_HIP_MIN_ENGINE:
4986        why = f"it is version {meta.get('version')}; this setup needs {'.'.join(map(str, WIN_HIP_MIN_ENGINE))}"
4987    elif gpu["arch"] not in arch_names(meta.get("archs")):
4988        why = (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
4990        if is_strix_halo(gpu):                         # never a zip without gfx1151 code: say so, and what to do
4991            why = (f"it is built for {', '.join(arch_names(meta.get('archs'))) or 'other GPUs'} and has no gfx1151 code: your "
4992                   f"{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>")
4996    if why:
4997        warn(f"the ready-made AMD engine at {base} cannot be used: {why}")
4998        shutil.rmtree(tmp, ignore_errors=True)
4999        drop_archive(z)
5000        return None
5001    install_unpacked(tmp, eng)
5002    shutil.rmtree(tmp, ignore_errors=True)
5003    drop_archive(z)
5004    hip_runtime_beside_exe(eng)                        # #468 #461
5005    ok(f"ready-made AMD engine {meta.get('version', '')} for {', '.join(arch_names(meta.get('archs')))} "
5006       f"(ROCm {meta.get('rocm', '?')})")
5007    return eng
5008
5009
5010def rocm_version(root):
5011    """(major, minor) of a ROCm install, from rocm-core's header; None when it has none."""
5012    try:
5013        text = (Path(root) / "include" / "rocm-core" / "rocm_version.h").read_text(encoding="utf-8")
5014        return tuple(int(re.search(rf"#define\s+ROCM_VERSION_{k}\s+(\d+)", text).group(1)) for k in ("MAJOR", "MINOR"))
5015    except (OSError, AttributeError, ValueError):
5016        return 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
5021    hipcc and libhipblas but not these, and cmake's enable_language(HIP) then fails on the hip-lang package)."""
5022    lang = "cmake/hip-lang/hip-lang-config.cmake"     # where CMake's HIP support looks for it
5023    need = {"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"]}
5025    return [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
5031    TheRock wheels (rocm_wanted: a version per card family, from the family's index) installed into .venv."""
5032    archs = [archs] if isinstance(archs, str) else list(archs)
5033    sysroot = Path(os.environ.get("ROCM_PATH") or "/opt/rocm")
5034    if (sysroot / "bin" / "hipcc").exists() and list((sysroot / "lib").glob("libhipblas.so*")):
5035        ver = rocm_version(sysroot)
5036        missing = rocm_dev_missing(sysroot)
5037        if (ver is None or ver >= ROCM_SYSTEM_MIN) and not missing:
5038            return sysroot, [str(sysroot / "lib")]
5039        if ver is not None and ver < ROCM_SYSTEM_MIN:
5040            warn(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")
5042        else:                                          # #446: a runtime-only ROCm (no -dev packages): cmake would fail
5043            warn(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)")
5045    indexes = list(dict.fromkeys(rocm_index(a) for a in archs))
5046    if len(indexes) > 1:                               # TheRock's wheels hold one GPU family's libraries
5047        fail(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)")
5049    index = indexes[0]
5050    stamp = Path(sys.prefix) / ".strata-rocm.json"
5051    have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {}
5052    wheel = None
5053    if have.get("index") == index and have.get("version") and not ROCM_VERSION_OVERRIDE \
5054            and (Path(sys.executable).parent / "rocm-sdk").exists() and have["version"] == ROCM_FAMILY_PINS.get(rocm_family(index), ROCM_VERSION_DEFAULT):
5055        wheel = have["version"]                         # the family's pin is installed: no lookup
5056    if wheel is None:
5057        wheel, note = rocm_wanted(index)
5058        if note:
5059            warn(note)
5060    if have.get("version") != wheel or have.get("index") != index:
5061        say(f"  Installing ROCm {wheel} for AMD GPUs into .venv (AMD's TheRock wheels, ~10 GB, no sudo) ...")
5062        pip = [sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--index-url", index]
5063        if have.get("version") == wheel:               # the same version for another GPU family: its own libraries
5064            run(pip + ["--force-reinstall", "--no-deps", f"rocm=={wheel}"])
5065        run(pip + [f"rocm[libraries,devel]=={wheel}"])
5066        stamp.write_text(json.dumps({"version": wheel, "index": index}))
5067    sdk = Path(sys.executable).parent / "rocm-sdk"
5068    root = Path(out([str(sdk), "path", "--root"]).strip())
5069    if not (root / "llvm" / "bin" / "clang++").exists():
5070        fail(f"ROCm was installed but its compiler is missing ({root})",
5071             f"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
5074    family = "_rocm_sdk_libraries_" + index.rstrip("/").rsplit("/", 1)[-1].replace("-", "_")
5075    dirs = [str(root / "lib")]
5076    for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}:
5077        libs = sorted(sp.glob("_rocm_sdk_libraries_*"))
5078        libs = [d for d in libs if d.name.lower() == family.lower()] or libs
5079        dirs += [str(d / "lib") for d in libs if (d / "lib").is_dir()]
5080    ok(f"ROCm: {root}")
5081    return 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
5086    header of the ROCm whose libraries the engine loads; None when not found."""
5087    for d in lib_dirs:
5088        try:
5089            text = (Path(d).parent / "include" / "hipblaslt" / "hipblaslt-version.h").read_text(encoding="utf-8")
5090            v = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", text).group(1))
5091                 for k in ("MAJOR", "MINOR", "PATCH")]
5092        except (OSError, AttributeError, ValueError):
5093            continue
5094        return v[0] * 100000 + v[1] * 100 + v[2]
5095    return 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
5100    ids are valid only for that pair (the engine refuses any other table and uses plain hipBLAS).  ver: the
5101    hipBLASLt version the ready-made engine ships (its BUILD.json), else read from the installed headers.  extra_dirs: the
5102    engine folder's own tuning/ first (a ready-made engine carries its tables), then tools/hip of this checkout.
5103    STRATA_HIPBLASLT_TABLE=off: none (strata_control/hipblaslt_tuning.py)."""
5104    from strata_control import hipblaslt_tuning as HT
5105    if HT.switched_off():
5106        say(f"  hipBLASLt tuning table: off ({HT.SWITCH}=off); the prompt's dense matrix products use plain hipBLAS")
5107        return None
5108    ver = ver or hipblaslt_version(lib_dirs)
5109    for folder in (*extra_dirs, ROOT / "tools" / "hip"):
5110        table = Path(folder) / HT.table_name(arch, ver or 0)
5111        if ver is not None and table.exists() and HT.header_ok(table, arch, ver):
5112            ok(f"hipBLASLt tuning table: {table.name} (faster prompts)")
5113            return table
5114    have = sorted(p.name for p in (ROOT / "tools" / "hip").glob(f"{arch}-hipblaslt-*.txt"))
5115    warn(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)")
5119    return 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`).
5124    gpu["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)."""
5126    acquisition.require("an engine build")
5127    eng = ROOT / "engine"
5128    eng.mkdir(exist_ok=True)
5129    stamp = eng / "BUILD.json"
5130    meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {}
5131    src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES)
5132    archs = sorted(set(gpu.get("archs") or [gpu["arch"]]))
5133    has_archs = set(archs) <= set(arch_names(meta.get("archs")))
5134    floor = cpu_floor(cpu_info()[1])                     # "" on an AVX2 CPU: the normal engine
5135    engine_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)
5137    vision_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"))))))
5139    if engine_ok and vision_ok:
5140        ok("engine already built for this PC")
5141        return eng
5142    if engine_ok:
5143        return build_vision_hip(eng, stamp, meta, llama, vsrc, archs, vision)
5144    if not (shutil.which("c++") or shutil.which("g++")) or not shutil.which("git"):
5145        fail("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")
5147    root, dirs = rocm_root(archs)
5148    libs = [str(Path(d).parent) for d in dirs[1:]]
5149    bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()),
5150                   root / "amdgcn" / "bitcode")
5151    os.environ.update({"HIP_PLATFORM": "amd", "HIP_COMPILER": "clang", "HIP_RUNTIME": "rocclr", "ROCM_PATH": str(root),
5152                       "HIP_PATH": str(root)})
5153    os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep)
5154    os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(root / "llvm" / "bin"), os.environ.get("PATH", "")])
5155    say("  The engine's source changed: compiling it again (only what changed, a few minutes) ..."
5156        if meta.get("backend") == "hip" and (eng / EXE).exists() and has_archs
5157        else f"  Compiling the Strata engine for your AMD GPU{'s' if len(archs) > 1 else ''} ({', '.join(archs)}; "
5158             "10-20 minutes, once) ...")
5159    cmake_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)
5163                 f"-DCMAKE_HIP_COMPILER={root / 'llvm' / 'bin' / 'clang++'}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}",
5164                 "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]),
5165                 f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}",
5166                 *ggml_defs(llama), *isa_floor_defs(floor, ROOT / "build-hip", meta)], None, "")
5167    if stale_binary(ROOT / "build-hip" / EXE):            # #2054: no stamp for a binary of another version
5168        fail(f"the engine build finished without a new engine ({EXE} is version "
5169             f"{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")
5171    shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE)
5172    meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none",
5173            "lib_dirs": dirs, "src": src, **({"isa_floor": floor} if floor else {})}
5174    if vision != "none":
5175        return build_vision_hip(eng, stamp, meta, llama, vsrc, archs, vision)
5176    stamp.write_text(json.dumps(meta, indent=1))
5177    ok(f"engine compiled: {eng / EXE}")
5178    return 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
5183    default of strata_control/vision_reader.py for this card - the CPU reader under 24 GB, the GPU reader from 24 GB (owner decision
5184    2026-10-18, every make of card); "gpu" / "cpu" as asked (#304), "none" for no.  "gpu" is a wish: hip_reader() settles it against
5185    what the engine folder carries (the HIP reader, else the CPU one) once the engine is known."""
5186    from strata_control import vision_reader as VR
5187    return 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),
5192    else the component manifest's archs; [] when neither says (the reader then checks the card itself when it starts)."""
5193    for name, keys in (("BUILD.json", ("vision_archs", "archs")), ("engine-component.json", ("archs",))):
5194        try:
5195            data = json.loads((eng / name).read_text(encoding="utf-8-sig"))
5196        except (OSError, ValueError):
5197            continue
5198        for key in keys:
5199            if isinstance(data, dict) and arch_names(data.get(key)):
5200                return arch_names(data.get(key))
5201    return []
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
5206    reader with the CPU reader to fall back on, else the CPU reader.  Returns (vision, Reader); a Reader of mode "none" means
5207    the 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."""
5208    from strata_control import vision_reader as VR
5209    r = VR.choose(eng, vision, windows=WIN, gpu_arch=str(gpu.get("arch") or ""), archs=reader_archs(eng))
5210    if r.note:
5211        warn(r.note)
5212    return 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
5218    sets; a build that fails leaves the CPU reader and says so (pictures still work, on the CPU)."""
5219    if vision == "gpu" and not (shutil.which("hipconfig") or os.environ.get("ROCM_PATH")):
5220        root, dirs = rocm_root(archs)                    # the engine was built earlier: set the same environment again
5221        os.environ.update({"HIP_PLATFORM": "amd", "HIP_COMPILER": "clang", "HIP_RUNTIME": "rocclr", "ROCM_PATH": str(root),
5222                           "HIP_PATH": str(root)})
5223        os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep)
5224        os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(root / "llvm" / "bin"), os.environ.get("PATH", "")])
5225    build_vision_cpu(eng, stamp, meta, llama, vsrc)
5226    meta = json.loads(stamp.read_text(encoding="utf-8"))
5227    if vision != "gpu":
5228        return eng
5229    root, dirs = rocm_root(archs)
5230    libs = [str(Path(d).parent) for d in dirs[1:]]
5231    bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()),
5232                   root / "amdgcn" / "bitcode")
5233    say("  Compiling the picture reader for your AMD GPU (a few minutes, once) ...")
5234    try:
5235        cmake_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++'}",
5238                     f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]),
5239                     f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}"], None, "")
5240        shutil.copy2(ROOT / "build-vision-hip" / "bin" / HVEXE, eng / HVEXE)
5241    except SystemExit:
5242        raise
5243    except Exception as e:                               # noqa: BLE001 - the CPU reader is there; pictures work without the GPU one
5244        warn(f"the GPU picture reader did not compile ({e}): pictures are read on the CPU")
5245        return eng
5246    stamp.write_text(json.dumps({**meta, "vision": "gpu", "vision_archs": archs, "vision_gpu": HVEXE, "vision_cpu": VEXE}, indent=1))
5247    ok(f"picture reader (GPU): {eng / HVEXE}, (CPU fallback): {eng / VEXE}")
5248    return 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."""
5253    if not ((eng / VEXE).exists() and meta.get("vision_src") == vsrc):
5254        say("  Compiling the image encoder (for the CPU) ...")
5255        cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision", "strata-vision",
5256                    [f"-DLLAMA_DIR={vision_llama(llama)}", "-DSTRATA_VISION_CUDA=OFF", "-DSTRATA_PORTABLE=OFF"],
5257                    find_vcvars() if WIN else None,
5258                    "build-vision-cpu.bat" if WIN else "")   # #881: MSVC's environment on Windows, as the CUDA path has
5259        shutil.copy2(ROOT / "build-vision" / "bin" / VEXE, eng / VEXE)
5260    stamp.write_text(json.dumps({**meta, "vision": "cpu", "vision_src": vsrc}, indent=1))
5261    ok(f"engine: {eng / EXE}, image encoder (CPU): {eng / VEXE}")
5262    return 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():
5270    if str(ROOT / "tools" / "image") not in sys.path:
5271        sys.path.insert(0, str(ROOT / "tools" / "image"))
5272    import qimage
5273    return 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."""
5278    QI = _qimage()
5279    src = ROOT / "third_party" / "stable-diffusion.cpp"
5280    if QI.source_ok(src):
5281        return src
5282    z1 = ROOT / "third_party" / f"stable-diffusion.cpp-{QI.SD_CPP_COMMIT[:7]}.zip"
5283    z2 = ROOT / "third_party" / f"sd-ggml-{QI.SD_GGML_COMMIT[:7]}.zip"
5284    download(QI.SD_CPP_ZIP, z1, "stable-diffusion.cpp source")
5285    download(QI.SD_GGML_ZIP, z2, "stable-diffusion.cpp's ggml source")
5286    try:
5287        src = QI.unpack_source(ROOT / "third_party", z1, z2)
5288    except zipfile.BadZipFile:
5289        for z in (z1, z2):
5290            drop_archive(z)
5291        raise
5292    for z in (z1, z2):
5293        z.unlink(missing_ok=True)
5294        z.with_name(z.name + ".done").unlink(missing_ok=True)
5295    return 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,
5300    else (Linux) the LunarG SDK unpacked into third_party (no sudo, ~370 MB).  Returns the SDK folder it put on PATH,
5301    None when the system's files are used."""
5302    QI = _qimage()
5303    have = os.environ.get("VULKAN_SDK")
5304    if have and Path(have).is_dir():
5305        return None
5306    if not WIN and shutil.which("glslc") and Path("/usr/include/vulkan/vulkan.h").exists():
5307        return None
5308    if WIN:
5309        fail("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)")
5312    base = ROOT / "third_party" / "vulkan-sdk"
5313    sdk = base / QI.VULKAN_SDK_VERSION / "x86_64"
5314    if not (sdk / "bin" / "glslc").exists():
5315        import tarfile
5316        tar = ROOT / "third_party" / f"vulkansdk-{QI.VULKAN_SDK_VERSION}.tar.xz"
5317        download(QI.VULKAN_SDK_URL, tar, f"the Vulkan SDK {QI.VULKAN_SDK_VERSION} (LunarG, for compiling only)")
5318        verify_sha256(tar, QI.VULKAN_SDK_SIZE, QI.VULKAN_SDK_SHA256)
5319        shutil.rmtree(base, ignore_errors=True)
5320        base.mkdir(parents=True)
5321        with tarfile.open(tar) as t:
5322            t.extractall(base, **({"filter": "data"} if hasattr(tarfile, "data_filter") else {}))
5323        tar.unlink(missing_ok=True)
5324        tar.with_name(tar.name + ".done").unlink(missing_ok=True)
5325    os.environ["VULKAN_SDK"] = str(sdk)
5326    os.environ["PATH"] = os.pathsep.join([str(sdk / "bin"), os.environ.get("PATH", "")])
5327    os.environ["LD_LIBRARY_PATH"] = os.pathsep.join([str(sdk / "lib" / "VulkanLoader" / "lib"),
5328                                                     os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep)
5329    ok(f"Vulkan SDK: {sdk}")
5330    return 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)."""
5335    import importlib.util
5336    QI = _qimage()
5337    spec = importlib.util.spec_from_file_location("strata_sdcpp_native_apply", QI.NATIVE_DIR / "apply.py")
5338    mod = importlib.util.module_from_spec(spec)
5339    spec.loader.exec_module(mod)
5340    mod.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
5345    backend; sd-cli uses it only with --model-args strata_noise=1)."""
5346    import importlib.util
5347    QI = _qimage()
5348    spec = importlib.util.spec_from_file_location("strata_sdcpp_noise_apply", QI.NOISE_DIR / "apply.py")
5349    mod = importlib.util.module_from_spec(spec)
5350    spec.loader.exec_module(mod)
5351    mod.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
5356    source (idempotent; CUDA / HIP builds; sd-cli uses it only with --model-args strata_vae=1)."""
5357    import importlib.util
5358    QI = _qimage()
5359    spec = importlib.util.spec_from_file_location("strata_sdcpp_vae_apply", QI.VAE_DIR / "apply.py")
5360    mod = importlib.util.module_from_spec(spec)
5361    spec.loader.exec_module(mod)
5362    mod.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
5368    generator is patched in (images "noise": "strata"); off, the build and its stamp are what they always were."""
5369    QI = _qimage()
5370    IMAGE_ENGINE.mkdir(exist_ok=True)
5371    exe, stamp = IMAGE_ENGINE / QI.SD_EXE, IMAGE_ENGINE / "BUILD.json"
5372    arch = gpu.get("arch") if backend in ("cuda", "hip") else None
5373    vae = vae and backend in QI.VAE_BACKENDS
5374    want = QI.build_stamp(backend, arch, noise, vae)
5375    meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {}
5376    lib_dirs = [d for d in meta.get("lib_dirs") or [] if Path(d).is_dir()]
5377    if exe.exists() and {k: meta.get(k) for k in want} == want:
5378        ok(f"image generator already built ({backend})")
5379        return exe, lib_dirs
5380    src = get_sd_cpp()
5381    if backend in QI.NATIVE_BACKENDS:                 # Strata's DiT runner (inert unless the config asks for it)
5382        apply_native_runner(src)
5383    if noise:                                          # Strata's noise generator (inert unless the config asks for it)
5384        apply_noise_generator(src)
5385    if vae:                                            # Strata's VAE decoder (inert unless the config asks for it)
5386        apply_vae_decoder(src)
5387    vcvars, lib_dirs = None, []
5388    if backend == "cuda":
5389        nvcc, cuda_v = find_nvcc()
5390        if nvcc is None:
5391            fail("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)")
5394        root = Path(nvcc).resolve().parent.parent
5395        defs = QI.cmake_defs("cuda", arch=arch, cuda_root=root) + [f"-DCMAKE_CUDA_COMPILER={nvcc}"] + \
5396            host_compiler_defs(True)
5397        vcvars = find_vcvars(cuda_v) if WIN else None
5398        lib_dirs = [str(root / "bin")] if WIN else [str(d) for d in (root / "lib64", root / "lib") if d.is_dir()]
5399    elif backend == "hip":
5400        root, dirs = rocm_root([arch])
5401        os.environ.update({"HIP_PLATFORM": "amd", "ROCM_PATH": str(root), "HIP_PATH": str(root)})
5402        os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep)
5403        defs = QI.cmake_defs("hip", arch=arch, rocm=root)
5404        lib_dirs = list(dirs)
5405    elif backend == "vulkan":
5406        sdk = vulkan_sdk()
5407        defs = QI.cmake_defs("vulkan")
5408        vcvars = find_vcvars() if WIN else None
5409        if sdk is not None:                          # the SDK's loader (lib/VulkanLoader): CMake does not look there
5410            loader = sdk / "lib" / "VulkanLoader" / "lib"
5411            defs += [f"-DVulkan_LIBRARY={loader / 'libvulkan.so'}", f"-DVulkan_INCLUDE_DIR={sdk / 'include'}",
5412                     f"-DVulkan_GLSLC_EXECUTABLE={sdk / 'bin' / 'glslc'}"]
5413            import ctypes.util
5414            if not ctypes.util.find_library("vulkan"):
5415                lib_dirs = [str(loader)]             # no system Vulkan loader to run with: the SDK's
5416    else:
5417        defs = QI.cmake_defs("cpu")
5418        vcvars = find_vcvars() if WIN else None
5419    say(f"  Compiling the image generator (stable-diffusion.cpp {QI.SD_CPP_COMMIT[:7]}, {backend}; 5-20 minutes, "
5420        "once) ...")
5421    bdir = ROOT / f"build-image-{backend}"
5422    cmake_build(src, bdir, "sd-cli", defs, vcvars, f"build-image-{backend}.bat" if WIN else "")
5423    built = bdir / "bin" / QI.SD_EXE
5424    if not built.exists():
5425        fail(f"the image generator's build finished without {built}", f"delete the folder {bdir.name} and run again")
5426    shutil.copy2(built, exe)
5427    stamp.write_text(json.dumps({**want, "lib_dirs": lib_dirs}, indent=1))
5428    ok(f"image generator compiled: {exe}")
5429    return 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
5434    recommendation is kept, with a warning (recommend, never force)."""
5435    QI = _qimage()
5436    vendor = "amd" if hip else ((gpu or {}).get("vendor") or "nvidia")
5437    backend = a.image_backend or QI.pick_backend({**gpu, "vendor": vendor} if gpu else None, WIN)
5438    gb = float((gpu or {}).get("vram_gb") or 0.0) if backend != "cpu" else 0.0
5439    rec = QI.pick_quant(gb) if backend != "cpu" else "Q4_K_M"
5440    quant = a.image_quant or rec
5441    if QI.QUANTS.index(quant) > QI.QUANTS.index(rec):
5442        warn(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)")
5444    return 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"
5449    section (serve/images.py); None for --images no, or when not wanted after all."""
5450    if not a.images or a.images == "no":
5451        return None
5452    QI = _qimage()
5453    backend, quant, _ = image_backend_choice(a, gpu, hip)
5454    say(f"  Image generation: Qwen-Image-2.1-Turbo {quant} on {backend} (8 steps, CFG 1; POST /v1/images/generations)")
5455    say("  " + QI.LICENSE_NOTE)
5456    need = sum(QI.FILES[k][2] for k in (quant, "vae", "llm")) / 1e9
5457    if ask(f"Download the image model ({need:.1f} GB) and set up image generation?", ["y", "n"], "y", a.yes) != "y":
5458        return None
5459    models_dir.mkdir(parents=True, exist_ok=True)
5460    if free_gb(models_dir) < need + 5:
5461        warn(f"less than {need + 5:.0f} GB free for the image model: the download may run out of disk space")
5462    noise = getattr(a, "image_noise", None) == "on"
5463    vae = getattr(a, "image_vae", None) == "on"
5464    if vae and backend not in QI.VAE_BACKENDS:         # the owner's wording, 11-11
5465        warn(f"Strata's own picture decoder runs with CUDA or ROCm only; image generation on {backend} keeps "
5466             "stable-diffusion.cpp's decoder")
5467        vae = False
5468    exe, lib_dirs = build_image_engine(backend, gpu or {}, noise, vae)
5469    for name in (quant, "vae", "llm"):
5470        repo, path, size, sha = QI.FILES[name]
5471        dst = QI.local_path(models_dir, name)
5472        download(QI.file_url(name, hf_endpoint()), dst, f"image model: {Path(path).name}")
5473        verify_sha256(dst, size, sha)
5474    cfg = QI.image_config(backend, quant, exe, models_dir, uma=QI.is_apu(gpu), lib_dirs=lib_dirs,
5475                          policy=a.image_gpu_policy or "auto", native=getattr(a, "image_native", None) == "on",
5476                          noise=noise, vae=vae)
5477    ok(f"image generation: {quant} on {backend}, GPU policy {cfg['gpu_policy']}")
5478    return cfg
5479
5480
5481# ------------------------------------------------------------------------------------------------ the engine
5482def driver_major(gpu):
5483    try:
5484        return int(gpu["driver"].split(".")[0])
5485    except (ValueError, KeyError):
5486        return 0
5487
5488
5489class UnverifiedEngine(Exception):
5490    """The engine archive could not be verified, with the reason.
5491
5492    Raised 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
5495    kills the start instead.  Measured on this change before the fix - a wrong hash, a wrong size and a
5496    missing 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
5504    tag), the `releases/latest/download/` URL, or something else entirely - a local folder, a plain mirror.
5505    That last case matters: it has no published digest, so treating it as "latest" would check the file
5506    against a release the user did not ask for, over the network, which is wrong twice over.
5507
5508    The repository comes out of the URL when it names one, so a fork's own releases are checked against
5509    the fork rather than against Niko1221/Strata (which never has the fork's tags, so the check would
5510    always fail).
5511    """
5512    m = re.search(r"https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/releases/(?:download/v([^/]+)|latest)/",
5513                  base)
5514    if not m:
5515        return None
5516    return 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
5522    A local folder is the user's own file on their own disk, the same trust decision as `--gguf-dir`, and
5523    there is no published digest for it to be checked against.  It is treated differently from a remote
5524    mirror on purpose: nothing is between the file and setup, whereas a remote mirror has a network in the
5525    middle and still no release to check it against.
5526    """
5527    b = base.strip()
5528    if b.lower().startswith("file://"):
5529        return True
5530    return 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
5536    The size and hash come from the releases API - a different origin from the download, which is the
5537    whole point: a mirrored, substituted or TLS-intercepted download does not come with a matching digest,
5538    while a compromised release does (see `verify_engine_archive` for what that leaves uncovered).
5539
5540    GitHub 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
5542    release that does not publish one - and the caller warns and installs anyway (never refuses).
5543    """
5544    where = release_of(base)
5545    if where is None:                  # a local folder or a plain mirror: nothing published to check against
5546        return None
5547    releases, tag = where
5548    url = f"{releases}/tags/v{tag}" if tag else f"{releases}/latest"
5549    try:
5550        req = urllib.request.Request(url, headers={"User-Agent": "strata-setup",
5551                                                   "Accept": "application/vnd.github+json"})
5552        with _urlopen(req, timeout=60) as r:
5553            rel = json.loads(r.read().decode("utf-8"))
5554    except Exception:
5555        return None                     # offline, rate-limited, or the release is not there
5556    for a in rel.get("assets") or []:
5557        if a.get("name") == asset and a.get("digest") and str(a.get("digest")).startswith("sha256:"):
5558            return int(a.get("size") or 0), str(a["digest"]).split(":", 1)[1]
5559    return 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."""
5564    z.unlink(missing_ok=True)
5565    z.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
5571    Without this, a ready-made engine is installed on nothing more than the byte count matching the
5572    server's Content-Length - and a substituted file of the same length passes that.  It runs before the
5573    archive is opened, so a wrong engine never reaches `_unpack`, let alone the engine directory.
5574
5575    Raises UnverifiedEngine on a refusal; the caller decides whether that stops setup (a first install,
5576    with nothing to fall back to) or keeps the engine that is already there (an update).
5577
5578    Where 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
5581      from is the one checked rather than "latest" (setup tries the checkout's own release first, #214),
5582      and 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
5584      ahead - it is the user's own file, the same trust decision as `--gguf-dir`, and there is nothing an
5585      API could say about it;
5586    - any other remote mirror: nothing published to check against either, but a network is in the middle,
5587      so it warns and installs anyway (no digest is never a reason to refuse).
5588
5589    What a digest from the API does NOT cover, stated plainly: it proves the bytes are the ones GitHub
5590    published for that asset, so it catches a corrupted transfer, a mirror or proxy that substituted the
5591    file, and a hostile network.  It does not make a malicious RELEASE safe - if whoever can publish a
5592    release publishes a hostile engine, the digest matches it.  Only a hash pinned in this file closes
5593    that, at the cost of a commit per release; a dict of tag -> sha next to `engine_digest` is where one
5594    would go.
5595
5596    The size and the hashing below are spelled out rather than delegated to `verify_sha256`, for two
5597    reasons, both measured here.  That function ends in `fail()`, and a refusal has to be an Exception so
5598    the update paths can fall back.  And it keeps a `.done` mark so 111 GB of Unsloth shards is hashed
5599    once; the engine archive is 190 MB, which hashes in 0.79 s at 242 MB/s on this machine, against 3.0 s
5600    to download the same file.  A mark that saves 0.8 s is not worth a class of hole - anything that
5601    changes the file after it was verified, at any length - so there is no mark here.
5602    """
5603    if os.environ.get("STRATA_SKIP_SHA256") == "1":
5604        warn(f"STRATA_SKIP_SHA256=1: NOT checking {asset} against its SHA-256. If the file is corrupt or "
5605             f"tampered with, it will be installed anyway. Unset it to get the check back.")
5606        return
5607    want = engine_digest(asset, base)          # one API call: this is a rate-limited API
5608    if not want:
5609        # no published digest (offline, rate limit, a mirror or folder): install anyway, never refuse
5610        warn(f"could not get a SHA-256 for {asset} from GitHub (offline, rate limited, or not a release "
5611             f"URL), so it was NOT verified. Installing it as it is.")
5612        return
5613    size, sha = want
5614    have = z.stat().st_size if z.exists() else -1
5615    if have != size:
5616        drop_download(z)
5617        raise UnverifiedEngine(f"{z.name} is {have:,} bytes, not the published {size:,}")
5618    h = hashlib.sha256()
5619    with open(z, "rb") as f:
5620        while True:
5621            b = f.read(16 << 20)
5622            if not b:
5623                break
5624            h.update(b)
5625    if h.hexdigest() != sha:
5626        got = h.hexdigest()
5627        drop_download(z)
5628        raise UnverifiedEngine(f"{z.name} has the wrong SHA-256 ({got}, expected {sha})")
5629    ok(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
5635    A first install has nothing to fall back to, so it stops.  An update does: the engine already in
5636    place is untouched by a refusal (nothing has been unpacked), it works, and stopping the model from
5637    starting over a hash is worse than keeping what is there - which is the whole reason that call site
5638    catches what the download can throw.
5639    """
5640    if not updating:
5641        fail(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")
5644        return
5645    warn(f"keeping the engine that is installed: {e}")
5646    say("       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
5651    checkout's version first, then the latest (#214); an explicit --prebuilt / STRATA_PREBUILT_URL: only that."""
5652    base = url_base if url_base.endswith(("/", "\\")) else url_base + "/"
5653    if base != PREBUILT_URL:
5654        return [base]
5655    version = source_version()
5656    if version == "0":                                  # no source tree to name a release by (the packaged Terminal): the latest release
5657        return [base]
5658    return [PREBUILT_TAG_URL.format(version=version), base]
5659
5660
5661PREVIOUS_ENGINE = ".previous"
5662
5663
5664def engine_version_of(folder: Path) -> str:
5665    try:
5666        return str(json.loads((folder / "BUILD.json").read_text(encoding="utf-8")).get("version", "?"))
5667    except (OSError, ValueError):
5668        return "?"
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
5673    eng/.previous (about 210 MiB): a new engine that turns out bad has a way back (`setup.py --rollback-engine`).  The
5674    swap is all or nothing: a failure part-way puts the old files back instead of leaving a mix of old and new."""
5675    prev = eng / PREVIOUS_ENGINE
5676    new = list(tmp.iterdir())
5677    old = [eng / p.name for p in new if p.name != PREVIOUS_ENGINE and (eng / p.name).exists()]
5678    if (eng / KQ_LIB).exists() and all(p.name != KQ_LIB for p in new):   # a zip without strata_kq: an older one of
5679        old.append(eng / KQ_LIB)                       # another build would only be refused (kept in .previous too)
5680    shutil.rmtree(prev, ignore_errors=True)
5681    moved, placed = [], []
5682    try:
5683        if old:
5684            prev.mkdir()
5685        for dst in old:
5686            shutil.move(str(dst), str(prev / dst.name))
5687            moved.append(dst)
5688        for p in new:
5689            p.replace(eng / p.name)
5690            placed.append(eng / p.name)
5691    except OSError:
5692        for dst in placed:                             # back to the old engine, whole
5693            shutil.rmtree(dst) if dst.is_dir() else dst.unlink(missing_ok=True)
5694        for dst in moved:
5695            shutil.move(str(prev / dst.name), str(dst))
5696        shutil.rmtree(prev, ignore_errors=True)
5697        raise
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 "?"
5700    kept = eng / "BUILD.json.prev"
5701    if kept.exists():
5702        try:
5703            if moved and not (prev / "BUILD.json").exists():
5704                shutil.move(str(kept), str(prev / "BUILD.json"))
5705            else:
5706                kept.unlink()
5707        except OSError:
5708            pass
5709    if moved:
5710        ok(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
5716    one it replaces is kept in its place (run it again to go forward)."""
5717    eng = engine_dir(toolkit)
5718    prev = eng / PREVIOUS_ENGINE
5719    if not prev.is_dir() or not any(prev.iterdir()):
5720        warn(f"no earlier engine is kept in {prev} (one is kept when an update replaces the engine)")
5721        return 1
5722    swap = eng / ".swap"
5723    shutil.rmtree(swap, ignore_errors=True)
5724    swap.mkdir()
5725    was = engine_version_of(eng)
5726    for p in list(prev.iterdir()):                     # what the earlier engine has: the current copy goes aside
5727        cur = eng / p.name
5728        if cur.exists():
5729            shutil.move(str(cur), str(swap / p.name))
5730        shutil.move(str(p), str(cur))
5731    for p in list(swap.iterdir()):
5732        shutil.move(str(p), str(prev / p.name))
5733    shutil.rmtree(swap, ignore_errors=True)
5734    ok(f"engine {engine_version_of(eng)} is installed again (it replaced {was}, which is kept in {prev})")
5735    return 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.
5740    updating: called to replace an installed engine, which starts instead when this fails (no compile).
5741    toolkit 12: the experimental CUDA 12 engine (CUDA12_ASSET) in engine-cuda12/."""
5742    acquisition.require("the ready-made engine")
5743    eng = engine_dir(toolkit)
5744    asset = CUDA12_ASSET if int(toolkit) == 12 else PREBUILT_ASSET
5745    info = eng / "BUILD.json"
5746    if info.exists() and (eng / EXE).exists() and json.loads(info.read_text(encoding="utf-8")).get("backend") != "hip":
5747        meta = json.loads(info.read_text(encoding="utf-8"))
5748        ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())
5749        if meta.get("source") == "local":              # compiled here: build_engine checks its source and cards
5750            return None
5751        have = arch_numbers(meta.get("archs"))
5752        miss = [int(x) for x in gpu.get("archs", [gpu["arch"]])
5753                if have and int(x) not in have and not (meta.get("ptx") and int(x) > max(have))]
5754        if miss:                                       # a card it has no code for (#128): compiled here instead
5755            warn(f"the installed engine is built for {', '.join(str(a) for a in have)}; your GPU is "
5756                 f"{', '.join(str(x) for x in miss)}: compiling instead")
5757            return None
5758        if ver >= MIN_ENGINE:
5759            ok("ready-made engine already installed")
5760            return eng
5761        say(f"  Updating the ready-made engine ({meta.get('version')} -> {'.'.join(map(str, MIN_ENGINE))} or newer) ...")
5762        info.replace(eng / "BUILD.json.prev")   # kept for the .previous copy
5763    if 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)
5766        got = engine_from_feed(eng, updating) if int(toolkit) != 12 else None
5767        if got is None:
5768            warn(f"no ready-made engine for {sysinfo.machine()} in the update feed" + ("" if updating else ": compiling it here, once"))
5769        return got
5770    if not url_base:
5771        return None
5772    eng.mkdir(exist_ok=True)
5773    z = eng / asset
5774    bases = prebuilt_bases(url_base)
5775    for i, base in enumerate(bases):
5776        if not base.startswith(("http://", "https://")):
5777            break
5778        try:                                           # not published (yet), or no internet: compile instead
5779            req = urllib.request.Request(base + asset, method="HEAD", headers={"User-Agent": "strata-setup"})
5780            _urlopen(req, timeout=60).close()
5781            break
5782        except OSError as e:
5783            if i + 1 < len(bases):                     # #214: this checkout's release is not published (yet)
5784                say(f"  No ready-made engine for v{source_version()} ({e}): the latest release instead")
5785                continue
5786            if int(toolkit) != 12:                     # 0.2 releases: the signed feed has it (#3469)
5787                got = engine_from_feed(eng, updating)
5788                if got is not None:
5789                    return got
5790            warn(f"no ready-made engine at {base} ({e})" + ("" if updating else ": compiling instead"))
5791            return None
5792    say("  Downloading the ready-made Strata engine" + (" (CUDA 12, experimental)" if int(toolkit) == 12 else "") + " ...")
5793    download(base + asset, z, "Strata engine")
5794    try:
5795        verify_engine_archive(z, asset, base)
5796    except UnverifiedEngine as e:
5797        engine_refused(asset, e, updating)
5798        return None
5799    tmp = eng / "_unpack"
5800    shutil.rmtree(tmp, ignore_errors=True)
5801    try:
5802        with zipfile.ZipFile(z) as f:
5803            f.extractall(tmp)
5804    except zipfile.BadZipFile:                         # not a zip, or a damaged one: a kept .done mark would make
5805        drop_archive(z)                                # every later run fail on it instead of downloading it again
5806        raise
5807    meta = json.loads((tmp / "BUILD.json").read_text(encoding="utf-8"))
5808    if tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) < MIN_ENGINE:
5809        need = ".".join(map(str, MIN_ENGINE))
5810        if updating:                                   # these files are newer than the published release (#58)
5811            warn(f"engine {need} is not published yet (the release may still be uploading): run this again "
5812                 f"in a few minutes to update it")
5813        else:
5814            warn(f"the ready-made engine at {base} is version {meta.get('version')}; this setup needs "
5815                 f"{need}: compiling instead")
5816        shutil.rmtree(tmp, ignore_errors=True)
5817        drop_archive(z)
5818        return None
5819    archs = arch_numbers(meta.get("archs"))
5820    miss = [int(x) for x in gpu.get("archs", [gpu["arch"]])
5821            if int(x) not in archs and not (meta.get("ptx") and int(x) > max(archs))]
5822    if miss:
5823        warn(f"the ready-made engine is built for {', '.join(str(a) for a in archs)}; your GPU is "
5824             f"{', '.join(str(x) for x in miss)}" + ("" if updating else ": compiling instead"))
5825        shutil.rmtree(tmp, ignore_errors=True)
5826        drop_archive(z)
5827        return None
5828    install_unpacked(tmp, eng)
5829    shutil.rmtree(tmp, ignore_errors=True)
5830    drop_archive(z)
5831    if not (eng / EXE).exists():
5832        fail("the ready-made engine archive has no " + EXE)
5833    if not WIN:
5834        for x in (EXE, VEXE):
5835            if (eng / x).exists():
5836                (eng / x).chmod(0o755)
5837    ok(f"ready-made engine {meta.get('version', '')} for {', '.join('sm_' + str(a) for a in archs)} (CUDA "
5838       f"{meta.get('cuda', '?')})")
5839    return 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
5844    RTX 4090s was taken, and CUDA 13 cannot compile for it.  The cards the installed models are set up for come
5845    first (their "gpu"); for the CUDA 13 engine a card it cannot compile for is left out when another can.  An
5846    explicit --gpu (GPU_PICK) still wins.  None when there is no NVIDIA GPU."""
5847    if GPU_PICK is not None:
5848        return gpu_info()
5849    found = gpus()
5850    if not found:
5851        return None
5852    named = set()
5853    for c in installed_configs():
5854        try:
5855            g = json.loads(c.read_text(encoding="utf-8-sig")).get("gpu")
5856        except (OSError, ValueError):
5857            continue
5858        named.update(i for i in (g if isinstance(g, list) else [g]) if isinstance(i, int) and not isinstance(i, bool))
5859    pool = [g for g in found if g["index"] in named] or found
5860    if int(toolkit) != 12:
5861        pool = [g for g in pool if int(g["arch"]) >= CUDA13_MIN_ARCH] or pool
5862    g = max(pool, key=lambda x: (round(x["vram_gb"]), -x["index"]))
5863    return {**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
5868    no network (the engine that is installed starts as it is).  update_installed_engine, below, is what UPDATE.bat /
5869    update.sh and a setup run do."""
5870    for toolkit in (13, 12):
5871        eng = engine_dir(toolkit)
5872        info = eng / "BUILD.json"
5873        if not info.exists() or not (eng / EXE).exists():
5874            continue
5875        try:
5876            meta = json.loads(info.read_text(encoding="utf-8"))
5877        except (OSError, ValueError):
5878            continue
5879        ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())
5880        need = WIN_HIP_MIN_ENGINE if (meta.get("backend") == "hip" and WIN) else MIN_ENGINE
5881        if meta.get("source") == "local":
5882            old = meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE)
5883        elif meta.get("backend") == "hip" and not WIN:
5884            old = meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE)
5885        else:
5886            old = ver < need
5887        if old:
5888            warn(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
5895    START-HERE.bat on an existing install picks up a new release.  If that cannot happen (no internet, the model
5896    still running, no ready-made engine for this GPU) the installed engine is kept and starts as before.
5897    toolkit None: engine/, then the experimental CUDA 12 engine in engine-cuda12/ when one is installed."""
5898    if toolkit is None:
5899        update_installed_engine(url_base, 13)
5900        if (engine_dir(12) / "BUILD.json").exists():
5901            update_installed_engine(url_base, 12)
5902        return
5903    eng = engine_dir(toolkit)
5904    info = eng / "BUILD.json"
5905    if not info.exists() or not (eng / EXE).exists():
5906        return
5907    meta_text = info.read_text(encoding="utf-8")
5908    meta = json.loads(meta_text)
5909    if meta.get("backend") == "hip" and WIN:           # AMD on Windows: the ready-made HIP engine, when older
5910        ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())
5911        if meta.get("source") == "prebuilt" and ver < WIN_HIP_MIN_ENGINE:
5912            try:
5913                g = next((x for x in amd_gpus() if amd_problem(x) is None), None)
5914                if g is None:
5915                    raise RuntimeError("no supported AMD GPU found")
5916                say(f"  Updating the ready-made AMD engine ({meta.get('version')} -> "
5917                    f"{'.'.join(map(str, WIN_HIP_MIN_ENGINE))} or newer) ...")
5918                if get_prebuilt_hip(url_base, g, updating=True) is None:
5919                    raise RuntimeError("not published yet")
5920            except (Exception, SystemExit) as e:
5921                warn(f"could not update the AMD engine{'' if isinstance(e, SystemExit) else f' ({e})'}: "
5922                     "starting the installed one")
5923        return
5924    if meta.get("backend") == "hip":                   # AMD: compiled here, again when its source changed
5925        if meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE):
5926            try:
5927                usable = [x for x in amd_gpus() if amd_problem(x) is None]
5928                g = next((x for x in usable if x["arch"] in arch_names(meta.get("archs"))), usable[0] if usable else None)
5929                if g is None:
5930                    raise RuntimeError("no supported AMD GPU found")
5931                # every architecture it was built for (a layer split across two families keeps both)
5932                build_engine_hip({**g, "archs": [x for x in arch_names(meta.get("archs")) if x in AMD_ARCHS] or [g["arch"]]},
5933                                 llama_override(), meta.get("vision") or "none")
5934            except (Exception, SystemExit) as e:
5935                warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: "
5936                     "starting the installed one")
5937        return
5938    ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())
5939    local = meta.get("source") == "local"
5940    vision = meta.get("vision") or "none"
5941    if local:                                          # compiled here: is it older than the source (a git pull)?
5942        if 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)):
5944            return
5945    elif ver >= MIN_ENGINE:
5946        return
5947    try:                                               # a running engine cannot be replaced (Windows keeps it locked)
5948        for x in (EXE, VEXE):
5949            if (eng / x).exists():
5950                with open(eng / x, "r+b"):
5951                    pass
5952    except OSError:
5953        warn(f"engine {meta.get('version') or ''} is in use: close the model window and run this again to update it")
5954        return
5955    gpu = update_engine_gpu(toolkit)
5956    if local:
5957        try:                                           # a failed compile must not stop the model from starting
5958            if gpu is None:
5959                raise RuntimeError("no NVIDIA GPU found")
5960            gpu = {**gpu, "archs": sorted({int(gpu["arch"]), *arch_numbers(meta.get("archs"))})}
5961            if int(toolkit) == 12:                     # the cards it was compiled for (the main GPU may be newer)
5962                gpu["archs"] = sorted(arch_numbers(meta.get("archs"))) or gpu["archs"]
5963            build_engine(gpu, vision, False, llama_override(), toolkit=toolkit)
5964        except (Exception, SystemExit) as e:
5965            warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the installed one")
5966        return
5967    new = None
5968    if gpu is not None:
5969        try:
5970            if int(toolkit) == 12:                     # the cards the CUDA 12 engine serves, not the newest one
5971                gpu = {**gpu, "archs": [x for x in arch_numbers(meta.get("archs")) if x < CUDA13_MIN_ARCH]
5972                       or [int(gpu["arch"])]}
5973            new = get_prebuilt(url_base, gpu, "gpu", updating=True, toolkit=toolkit)
5974        except Exception as e:                         # a failed download must not stop the model from starting
5975            warn(f"updating the engine failed ({e})")
5976    if new is None:
5977        if not info.exists():
5978            info.write_text(meta_text)                 # get_prebuilt drops it before downloading: put it back
5979        warn(f"could not update the engine: starting the installed {meta.get('version')}")
5980        return
5981    pip_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."""
5986    acquisition.require("NVIDIA's CUDA libraries (pip)")
5987    if int(toolkit) == 12:
5988        pip_install(CUDA12_WHEELS, "NVIDIA CUDA 12 libraries for the experimental engine (cuBLAS, CUDA runtime; ~0.7 GB)")
5989    else:
5990        pip_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."""
6000    m = re.search(r"\bV\d+\.\d+\.(\d+)", out([nvcc, "--version"]) if nvcc else "")
6001    return 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
6006    when one is installed and the user did not name a compiler (STRATA_NVCC), else the one found, with a warning that says
6007    what to do.  CUDA 13.2.2 (build 86 or newer) is fine.  Recommends, never forces: a user who picked 13.2 keeps it."""
6008    if not nvcc or cuda_v != CUDA_SM120_SUSPECT or max(archs) < 120:
6009        return nvcc, cuda_v
6010    build = nvcc_build(nvcc)
6011    if build is not None and build >= CUDA_SM120_FIXED_BUILD:
6012        return nvcc, cuda_v
6013    if not os.environ.get("STRATA_NVCC"):
6014        alt, alt_v = find_nvcc(below=CUDA_SM120_SUSPECT)
6015        if alt and alt_v and alt_v >= (13, 0):
6016            ok(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")
6018            return alt, alt_v
6019    warn("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")
6023    return 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
6028    not one setup adds the CUDA keyring for.  Both families publish cuda-keyring and CUDA 13.x."""
6029    ver = osr.get("VERSION_ID", "").strip('"').replace(".", "")
6030    repo = {"ubuntu": "ubuntu", "debian": "debian"}.get(osr.get("ID", ""), "") + ver
6031    return 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)."""
6036    acquisition.require("the compiler and CUDA toolkit")
6037    archs = [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)
6040    old = int(gpu.get("toolkit") or (12 if min(archs) < CUDA13_MIN_ARCH else 13)) == 12
6041    need12 = (12, 8) if max(archs) >= 120 else (12, 0)     # sm_120 needs CUDA 12.8 or newer
6042    if old and max(archs) >= 120:
6043        warn("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")
6045    nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc()
6046    if old and (nvcc is None or cuda_v < need12):
6047        fail("the experimental CUDA 12 engine (Pascal / Volta, or --cuda 12) is compiled here with the NVIDIA CUDA "
6048             f"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)
6053    need_cuda = need12 if old else (13, 0) if max(archs) >= 120 else (12, 0)
6054    vcvars = find_vcvars(cuda_v) if WIN else None
6055    have_cc = vcvars is not None if WIN else shutil.which("g++") is not None
6056    missing = []
6057    if not have_cc:
6058        missing.append("Visual Studio 2022 Build Tools (C++)" if WIN else "the C++ compiler (build-essential)")
6059    if nvcc is None or cuda_v < need_cuda:
6060        missing.append("the NVIDIA CUDA Toolkit 13.0")
6061    if not missing:
6062        nvcc, cuda_v = sm120_nvcc(nvcc, cuda_v, archs)
6063        ok(f"build tools present (CUDA {cuda_v[0]}.{cuda_v[1]})")
6064        return nvcc, vcvars
6065    say("  The engine has to be compiled for your PC, which needs: " + " and ".join(missing) + ".")
6066    say("  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") + ").")
6068    if ask("  Install them now?", ["y", "n"], "y", yes) != "y":
6069        fail("the build tools are needed", "install them yourself (see README.md) and run it again")
6070    if WIN:
6071        if shutil.which("winget") is None:
6072            fail("winget (Windows package manager) is not available",
6073                 "install 'App Installer' from the Microsoft Store, or install the tools by hand (README.md)")
6074        wg = ["winget", "install", "-e", "--source", "winget", "--accept-package-agreements",
6075              "--accept-source-agreements", "--disable-interactivity"]
6076        if not have_cc:
6077            run([*wg, "--id", "Microsoft.VisualStudio.2022.BuildTools", "--override",
6078                 "--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"],
6079                check=False)
6080        if nvcc is None or cuda_v < need_cuda:
6081            run([*wg, "--id", "Nvidia.CUDA", "--version", "13.0"], check=False)
6082        vcvars = find_vcvars(cuda_v)
6083    else:
6084        apt = shutil.which("apt-get")
6085        if apt is None:
6086            fail("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")
6089        if not have_cc:
6090            run(["sudo", "apt-get", "install", "-y", "build-essential"])
6091        if nvcc is None or cuda_v < need_cuda:
6092            osr = dict(line.split("=", 1) for line in open("/etc/os-release").read().splitlines() if "=" in line)
6093            repo = cuda_apt_repo(osr)
6094            if repo is None:
6095                fail("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")
6097            deb = Path("/tmp/cuda-keyring.deb")
6098            # NVIDIA's arm64 server repository is "sbsa" (a DGX Spark; DGX OS normally has the toolkit already)
6099            download(f"https://developer.download.nvidia.com/compute/cuda/repos/{repo}/"
6100                     f"{'sbsa' if is_arm64() else 'x86_64'}/cuda-keyring_1.1-1_all.deb", deb, "CUDA repository key")
6101            run(["sudo", "dpkg", "-i", str(deb)])
6102            run(["sudo", "apt-get", "update"])
6103            if repo.startswith("ubuntu"):                  # as before: 13.0, and a failed install stops setup here
6104                run(["sudo", "apt-get", "install", "-y", "cuda-toolkit-13-0"])
6105            else:
6106                # Debian 13's CUDA repo carries no 13.0 package: take the oldest 13.x minor it has
6107                for minor in range(10):
6108                    if run(["sudo", "apt-get", "install", "-y", f"cuda-toolkit-13-{minor}"], check=False).returncode == 0:
6109                        break
6110                else:
6111                    fail(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")
6113    nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc()
6114    if (WIN and find_vcvars(cuda_v) is None) or (not WIN and shutil.which("g++") is None):
6115        fail("the C++ build tools did not install", "install them by hand (README.md) and run it again")
6116    if nvcc is None or cuda_v < need_cuda:
6117        fail("the CUDA Toolkit did not install", "install it from https://developer.nvidia.com/cuda-downloads, then run it again")
6118    nvcc, cuda_v = sm120_nvcc(nvcc, cuda_v, archs)
6119    ok(f"build tools installed (CUDA {cuda_v[0]}.{cuda_v[1]})")
6120    return 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."""
6125    found = find_tool(name)
6126    if found is None:
6127        return False
6128    if name == "cmake":
6129        runs, version = _tool_version(found, name)
6130        return runs and (not version or version[:2] >= CMAKE_MIN)
6131    return 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
6136    compiles 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.
6139    build_packages = requirement_lines(BUILD_REQUIREMENTS) if BUILD_REQUIREMENTS.exists() else BUILD_PACKAGES
6140    missing = [package for package in build_packages if not tool_usable(req_name(package))]
6141    if missing:
6142        pip_install(missing, "CMake and Ninja build tools")
6143    cmake, ninja = find_tool("cmake"), find_tool("ninja")
6144    if cmake is None or ninja is None:
6145        fail("cmake / ninja not found after installing them", "run: .venv python -m pip install -r requirements-build.txt")
6146    return 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."""
6151    try:
6152        for line in (Path(bdir) / "CMakeCache.txt").read_text(encoding="utf-8", errors="replace").splitlines():
6153            if line.startswith("CMAKE_GENERATOR:"):
6154                return line.split("=", 1)[1].strip()
6155    except OSError:
6156        pass
6157    return 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
6162    previously"). The manual build in docs/INSTALL.md uses CMake's default, Unix Makefiles on Linux, in the same build/ folder (#4038).
6163    Such a folder is configured afresh: its cache is removed (the compiled objects of the other generator are not reused anyway), with one
6164    plain line. True when it did."""
6165    had = configured_generator(bdir)
6166    if had is None or had == generator:
6167        return False
6168    say(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)
6170    shutil.rmtree(Path(bdir) / "CMakeFiles", ignore_errors=True)
6171    return 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."""
6176    out = {}
6177    try:
6178        text = (Path(bdir) / "CMakeCache.txt").read_text(encoding="utf-8", errors="replace")
6179    except OSError:
6180        return out
6181    for line in text.splitlines():
6182        if line and not line.startswith(("#", "//")) and "=" in line:
6183            key, value = line.split("=", 1)
6184            out[key.split(":", 1)[0].strip()] = value.strip()
6185    return 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
6193    and about 60 more); a new -DCUDAToolkit_ROOT does not search them again, so after a CUDA update that removed the old
6194    toolkit, ninja stopped on the old libcudart.so.  When the toolkit changed - another CUDAToolkit_ROOT than the cached one,
6195    or a cached CUDA path that is gone - the configure drops those entries (-U, before the new -D) and CMake detects the CUDA
6196    compiler again; the compiled objects stay, so only what changed is rebuilt.  [] for an unchanged or a new folder."""
6197    cache = cmake_cache_entries(bdir)
6198    if not cache:
6199        return []
6200    want = next((str(d).split("=", 1)[1] for d in defs if str(d).startswith("-DCUDAToolkit_ROOT=")), None)
6201    had = cache.get("CUDAToolkit_ROOT")
6202    moved = bool(want and had) and Path(had) != Path(want)
6203    gone = any(not Path(part).exists()
6204               for name, value in cache.items() if name.startswith(("CUDA_", "CUDAToolkit_"))
6205               for part in value.split(";")
6206               if part and not part.endswith("-NOTFOUND") and Path(part).is_absolute())
6207    if not (moved or gone):
6208        return []
6209    for f in (Path(bdir) / "CMakeFiles").glob("*/CMakeCUDACompiler.cmake"):
6210        f.unlink(missing_ok=True)
6211    return [f"-U{g}" for g in CUDA_CACHE_GLOBS]
6212
6213
6214def cmake_build(src, bdir, target, defs, vcvars, bat_name):
6215    acquisition.require("a compile (cmake)")
6216    cmake, ninja = ensure_build_tools()
6217    fresh_if_other_generator(bdir)
6218    conf = [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]
6220    build = [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.
6223    if WIN:
6224        if vcvars is None:                             # #881: the build needs MSVC's environment
6225            fail("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")
6228        bat = ROOT / bat_name
6229        q = lambda c: " ".join(f'"{x}"' if " " in str(x) else str(x) for x in c)  # noqa: E731
6230        bat.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'
6231                       f'echo   (the build stopped - trying it once more)\r\n{q(build)} || exit /b 1\r\n',
6232                       encoding="utf-8")
6233        run(["cmd", "/c", str(bat)])
6234    else:
6235        run(conf)
6236        if run(build, check=False).returncode != 0:
6237            say("  (the build stopped - trying it once more)")
6238            run(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`
6247    changes them, the engine is compiled again (issue #31)."""
6248    h = hashlib.sha256(LLAMA_CPP_COMMIT.encode())
6249    for part in parts:
6250        base = ROOT / part
6251        for f in [base] if base.is_file() else sorted(x for x in base.rglob("*") if x.is_file()):
6252            h.update(f.relative_to(ROOT).as_posix().encode() + b"\0" + f.read_bytes().replace(b"\r\n", b"\n"))
6253    return 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
6258    build.  A build folder configured for another floor is configured afresh: ggml's CPU options are cached there."""
6259    if (meta.get("isa_floor") or "") != floor and (bdir / "CMakeCache.txt").exists():
6260        (bdir / "CMakeCache.txt").unlink()
6261    return [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
6266    takes them too (the environment reaches CMake only on a folder's first configure, which is why CXX=g++-14 alone
6267    could die at the last step, #1645).  CUDAHOSTCXX is nvcc's host compiler (-ccbin); it defaults to CXX, as
6268    CMake's does.  `cuda`: the project compiles CUDA (the host-compiler definition means nothing to a C++-only
6269    one)."""
6270    cc = os.environ.get("CC", "").strip()
6271    cxx = os.environ.get("CXX", "").strip()
6272    hostcxx = os.environ.get("CUDAHOSTCXX", "").strip() or cxx
6273    return ([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
6280    another toolkit: with STRATA_NVCC=/opt/cuda-13.0/bin/nvcc on Ubuntu 24.04 that also has the distribution's CUDA
6281    12.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."""
6283    root = Path(nvcc).resolve().parent.parent
6284    return [] 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
6289    for every CUDA 12 engine (the same build as the ready-made CUDA 12 one: it admits the older cards)."""
6290    return ["-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
6295    than the engine (0.1.30/0.1.31: no RTX 20 code, #331): such a card gets the CPU encoder - the same program - instead
6296    of compiling one, which fails on most Windows PCs (no Visual Studio / CUDA toolkit); --build compiles it."""
6297    if vision != "gpu":
6298        return vision
6299    va = arch_numbers(meta.get("vision_archs", meta.get("archs")))
6300    if va and int(gpu["arch"]) not in va and not (meta.get("ptx") and int(gpu["arch"]) > max(va)):
6301        warn(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)")
6303        return "cpu"
6304    return 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.
6309    A 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
6310    layer-split run on both cards then launched kernels the sm_75 build holds only a trap for: "unspecified launch failure" on every long prompt.
6311    One more architecture is a few more minutes of compile, once; a card Strata cannot use (older than sm_75) is left out."""
6312    try:
6313        present = {int(g["arch"]) for g in found or [] if gpu_problem(g) is None}
6314    except (KeyError, TypeError, ValueError):
6315        present = set()
6316    return 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
6321    engine whose source files changed since (a `git pull`) is compiled again: only the changed files, a few minutes.
6322    toolkit 12 (default: 12 for a card older than CUDA 13 supports): the experimental CUDA 12 engine, in
6323    engine-cuda12/ with its own build folders."""
6324    acquisition.require("an engine build")
6325    if toolkit is None:
6326        toolkit = 12 if min(int(x) for x in gpu.get("archs", [gpu["arch"]])) < CUDA13_MIN_ARCH else 13
6327    t12 = int(toolkit) == 12
6328    eng = engine_dir(toolkit)
6329    eng.mkdir(exist_ok=True)
6330    stamp = eng / "BUILD.json"
6331    meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {}
6332    want_vision = vision != "none"
6333    local = meta.get("source") == "local"
6334    src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES)
6335    archs = sorted({int(x) for x in gpu.get("archs", [gpu["arch"]])})    # every card the model runs on
6336    archs = local_build_archs(archs, gpus())                             # #4662: and every other card in the PC
6337    built = 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
6340    new_arch = local and not set(archs) <= built
6341    floor = cpu_floor(cpu_info()[1])                     # "" on an AVX2 CPU: the normal engine
6342    engine_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)
6344    vision_ok = not want_vision or ((eng / VEXE).exists() and (not local or meta.get("vision_src") == vsrc))
6345    if engine_ok and vision_ok:
6346        ok("engine already built for this PC")
6347        return eng
6348    if local:
6349        archs = sorted(built | set(archs))
6350    nvcc, vcvars = install_build_tools({**gpu, "archs": archs, "toolkit": toolkit}, yes)
6351    cuda_archs = ";".join(str(x) for x in archs)
6352    bdir, vdir = (ROOT / "build-cuda12", ROOT / "build-vision-cuda12") if t12 else (ROOT / "build", ROOT / "build-vision")
6353    if not engine_ok:
6354        say("  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) ..."
6357            if local and (eng / EXE).exists() else "  Compiling the Strata engine for your GPU (10-20 minutes, once) ...")
6358        cmake_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"),
6363                     f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}",
6364                     f"-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)],
6367                    vcvars, "build-strata-cuda12.bat" if t12 else "build-strata.bat")
6368        if stale_binary(bdir / EXE):                      # #2054: the stamp below is written only for a binary of this source
6369            fail(f"the engine build finished without a new engine ({EXE} is version {binary_engine_version(bdir / EXE)}, "
6370                 f"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")
6372        shutil.copy2(bdir / EXE, eng / EXE)
6373        if (bdir / KQ_LIB).exists():                      # built with it (Phase 1): it goes next to the engine
6374            shutil.copy2(bdir / KQ_LIB, eng / KQ_LIB)
6375        elif (eng / KQ_LIB).exists():                     # an older one of another build would only be refused
6376            (eng / KQ_LIB).unlink()
6377    if not vision_ok:
6378        say("  Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ..."))
6379        defs = [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
6381        if vision == "gpu":
6382            defs += [f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", f"-DCMAKE_CUDA_COMPILER={nvcc}",
6383                     *toolkit_root_defs(nvcc)]
6384        cmake_build(ROOT / "tools" / "vision", vdir, "strata-vision", defs, vcvars,
6385                    "build-vision-cuda12.bat" if t12 else "build-vision.bat")
6386        shutil.copy2(vdir / "bin" / VEXE, eng / VEXE)
6387    bindir = Path(nvcc).parent                            # the toolkit's own libraries (bin, bin/x64, lib64)
6388    dirs = [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()]
6389    stamp.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))
6393    ok(f"engine compiled: {eng / EXE}")
6394    return 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
6412    holds the most-used experts of its own layers, and the RAM copy leaves out what any card holds.  Before it, a
6413    resident config on several GPUs read those experts through the OS file cache (#364 #384)."""
6414    return 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
6419    experts.bin instead of copied into RAM (the low-RAM mode)."""
6420    return 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
6425    bytes, as MODELS gives it) plus the headroom (GiB): both sides counted in GiB."""
6426    return 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,
6436    buffers and a 32K context's KV cache, minus the KV cache of a longer context (in VRAM in the low-RAM mode: its RAM
6437    has no room for KV streaming), minus ~1 GB for the draft layer (MTP) when it is on."""
6438    kv_tok = 13 * KV_CELL_BYTES.get(kv, 1056)           # bytes per context token: 12 QSA layers + the draft layer
6439    longer = max(0, ctx - 32768) * kv_tok / 1e9
6440    return 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."""
6445    return 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
6450    copied 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)."""
6452    rest = MODELS[model]["arena_gb"] - low_ram_gpu_gb(model, vram_gb, ctx, kv, mtp)
6453    return 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)."""
6458    arena = MODELS[model]["arena_gb"]
6459    return 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`,
6464    the Terminal's "Needs (RAM + VRAM)" column)."""
6465    from strata_control import fit_label
6466    d = MODELS[model]
6467    return 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
6472    together.  An integrated chip counts only its carve-out (`low_ram_vram`: its shared memory is the RAM)."""
6473    from strata_control import fit_label
6474    return 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
6479    beside them (`low_ram_needed`), or the user asked for it.  Unsloth's 4-bit file is not the low-RAM mode at all:
6480    it always reads part of its experts from the files, through its RAM budget.  Step 5 applies exactly this answer,
6481    and the launcher's preset diff asks it too - so a preset that says "auto" is compared with what auto decides,
6482    not with the word."""
6483    if MODELS[model].get("budget"):
6484        return False
6485    return 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
6490    K8V4, 7.5 KB with 4-bit - 12 QSA layers + the draft layer."""
6491    return 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):
6496    the smaller of two numbers.  (1) The model's all-in-RAM need (`ram_gb`) + the KV cache + 1 GB: the experts all fit
6497    and 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
6499    rest, and the KV's RAM then comes out of that copy (or out of the OS file cache when the arena does not fit),
6500    not 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
6501    for the engine (Linux mimic): streaming gave 756 -> 1,267 expert slots and a 32K prompt in 12-17 s instead of
6502    21-34 s, with the RAM the engine used unchanged (RAM budget 31 -> 29 GiB); on the owner's RTX 5070 (R5070's
6503    run) 924 -> 1,585 slots, a 32K prompt 130 -> 79 s, the RAM copy 30.8 -> 28.9 GiB, no paging.  Rule (1) alone
6504    asked 64.8 GB of a PC that reads 63.1 and left the KV in VRAM."""
6505    kv_gb = kv_streaming_ram_gb(ctx, kv)
6506    m = MODELS[model]
6507    return 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
6512    model's experts (`kv_streaming_need_gb`); `--kv-streaming on|off` overrides the RAM test (the owner's rule), and
6513    WSL never streams.  Step 7 writes `--kv-resident` on exactly this answer, and the launcher's preset diff asks it
6514    too: a config's `--kv-resident` and a preset's "auto" are the same setting when this says yes."""
6515    if is_wsl() or choice == "off":
6516        return False
6517    return 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
6522    all of them (sel: the cards, for the --gpus example)."""
6523    arena, need = MODELS[model]["arena_gb"], MODELS[model]["arena_gb"] + LOW_RAM_HEADROOM_GB
6524    if choice == "auto":
6525        why = [f"Why: {model}'s experts are {arena:.0f} GB and must fit in RAM with ~{LOW_RAM_HEADROOM_GB} GB beside "
6526               f"them for the OS and the rest: {arena:.0f} + {LOW_RAM_HEADROOM_GB} = {need:.0f} GB, and this PC has "
6527               f"{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."]
6530    else:
6531        why = [f"Why: you chose the low-RAM mode (--low-ram {choice}); without it {model} needs {arena:.0f} + "
6532               f"{LOW_RAM_HEADROOM_GB} = {need:.0f} GB of RAM, this PC has {ram:.0f} GB."]
6533    return 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.",
6535                  f"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 "
6537                  f"#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
6543    experts the GPU does not hold in RAM (steady RAM use) and has no layer split.  All the GPUs together read those
6544    experts through the OS file cache instead (--mmap-experts) - 1.3-1.6x faster in those reports, but RAM can fill
6545    up to 0 free during long prompts.  An explicit --gpus (or an earlier install's cards) is kept; otherwise asked,
6546    one GPU by default (--yes: one GPU, as before).  True: all of them."""
6547    sel = [g["index"] for g in chosen]
6548    names = " + ".join(gpu_name(g) for g in chosen)
6549    if a.gpus:
6550        warn(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")
6553        say(f"       One GPU keeps them in RAM (steady RAM use, recommended): --gpu {gpu['index']}")
6554        if a.low_ram == "resident":
6555            warn("--low-ram resident has no layer split yet: the experts are read through the OS file cache instead")
6556        return True
6557    if a.low_ram != "resident" and not a.yes:
6558        say()
6559        for line in low_ram_one_gpu_why(model, ram, a.low_ram, sel):
6560            say("  " + line)
6561        say(f"  1) {gpu_name(gpu)} only: the experts it does not hold kept in RAM where they fit   (recommended: "
6562            "steady RAM use)")
6563        say(f"  2) {names} together: the experts the GPUs do not hold read through the OS file cache - faster")
6564        say("     in two reports (1.3-1.6x, #364 #384), but RAM can fill up to 0 free during long prompts")
6565        if ask("Low-RAM mode: which GPUs?", ["1", "2"], "1", a.yes) == "2":
6566            ok(f"the low-RAM mode on {names}: the experts read through the OS file cache, as you chose")
6567            return True
6568        warn("the low-RAM mode: using " + gpu_name(gpu) + " only")
6569        return False
6570    warn("the low-RAM mode: using " + gpu_name(gpu) + " only (recommended)")
6571    for line in low_ram_one_gpu_why(model, ram, a.low_ram, sel):
6572        say("       " + line)
6573    return 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
6578    split runs without it: all its experts loaded into RAM from the GGUFs at start, as with the 2-3-bit models - only
6579    where the RAM holds the GGUF files and 24 GB more (unsloth_split_need_gb; 165 GiB, 2x RTX 3090: 31 -> 64-78
6580    tok/s).  An explicit --gpus is honoured there; otherwise asked, one GPU by default (--yes: one GPU, as before); an
6581    explicit --resident-budget-gib keeps one GPU.  #642: the engines from RESIDENT_SPLIT_ENGINE keep the budget on a
6582    split (the experts no card holds, the hottest by the whole profile), so there the cards go together with it, at
6583    any RAM: --gpus, or "2" when asked; one GPU stays the recommendation (--yes alone: one GPU, as before).  True: all
6584    of them."""
6585    names = " + ".join(gpu_name(g) for g in chosen)
6586    if resident_split():
6587        note = "with its RAM budget (each card caches its own layers' experts, the RAM the hottest of the rest; #642)"
6588        if a.gpus:
6589            ok(f"{model} on {names}, as you chose (--gpus), {note}")
6590            return True
6591        if not a.yes:
6592            say()
6593            say(f"  {model} runs with a RAM budget of its experts, on one GPU or on {names} together:")
6594            say(f"  1) {gpu_name(gpu)} only   (recommended: the tested setup)")
6595            say(f"  2) {names} together: each card caches the experts of its own layers (#642)")
6596            if ask(f"{model}: which GPUs?", ["1", "2"], "1", a.yes) == "2":
6597                ok(f"{model} on {names}, {note}")
6598                return True
6599        warn(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)")
6601        return False
6602    need = unsloth_split_need_gb(model)
6603    if ram < need:
6604        note = (f"{model} on several GPUs has no RAM budget and needs ~{need:.0f} GB of RAM (its GGUF files and "
6605                f"{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)")
6607        if a.gpus and a.resident_budget_gib is None:    # #737: asked for by name: a question, not a refusal
6608            confirm_risk(note + ", but it may page or stall here", True, a.yes,
6609                         f"{model} on several GPUs needs ~{need:.0f} GB of RAM; this PC has {ram:.0f} GB",
6610                         f"start it on one GPU: --gpus {gpu['index']}", "  Use them together anyway?")
6611            ok(f"{model} on {names}, as you chose (--gpus), with {ram:.0f} GB of RAM")
6612            return True
6613        warn(f"{note} - using {gpu_name(gpu)} only (--gpus " + ",".join(str(g["index"]) for g in chosen) +
6614             " uses them together anyway)")
6615        return False
6616    if a.resident_budget_gib is not None:
6617        warn(f"--resident-budget-gib has no layer split: {model} runs on one GPU with it - using {gpu_name(gpu)} only "
6618             f"(leave the budget out to use {names} together)")
6619        return False
6620    note = (f"no RAM budget - all of its experts (~{MODELS[model]['arena_gb']:.0f} GB) are loaded into RAM from the "
6621            f"model files at start, and the files pass through the OS file cache (needs ~{need:.0f} GB of RAM, this "
6622            f"PC has {ram:.0f})")
6623    if a.gpus:
6624        ok(f"{model} on {names}, as you chose (--gpus): {note}")
6625        return True
6626    if not a.yes:
6627        say()
6628        say(f"  {model} can run on one GPU with a RAM budget of its experts, or on {names} together without one:")
6629        say(f"  1) {gpu_name(gpu)} only: the most-used experts kept in RAM, the rest read from the SSD   (recommended: "
6630            "the tested setup)")
6631        say(f"  2) {names} together: {note};")
6632        say("     about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s)")
6633        if ask(f"{model}: which GPUs?", ["1", "2"], "1", a.yes) == "2":
6634            ok(f"{model} on {names}: {note}")
6635            return True
6636    warn(f"{model} runs on one GPU: using {gpu_name(gpu)} only (--gpus " + ",".join(str(g["index"]) for g in chosen) +
6637         f" shares it across {names} without the RAM budget: this PC's RAM holds it)")
6638    return 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
6643    plainly (msg), then asked (default n; `default` keeps an older question's own default), or with --yes taken as
6644    consent 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."""
6646    warn(msg)
6647    if yes and explicit:
6648        return
6649    if ask(question, ["y", "n"], default, yes) != "y":
6650        fail(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
6655    a stop - the user may accept paging.  Asked "no" by default, so an unattended --yes install stops here, unless
6656    the low-RAM mode was turned off explicitly (--low-ram off, #250) or the size was (--model): that is the choice
6657    already made."""
6658    need_gb, arena = MODELS[model]["ram_gb"], MODELS[model]["arena_gb"]
6659    off = choice == "off"
6660    confirm_risk(f"{model} needs about {need_gb} GB of RAM and this PC has {ram:.0f} GB: its experts alone are "
6661                 f"{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,
6664                 f"{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")
6668    warn(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
6674    8-bit KV cache + 24 GB of room for everything else (the 0.1.29 arithmetic, counted).  None where the context does
6675    not count against RAM by this rule: the other sizes, and the low-RAM mode (its KV cache stays in VRAM)."""
6676    if model not in ("IQ3_XXS", "IQ3_S") or low_ram:
6677        return None
6678    return 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
6683    is part of the recommended default (the smaller of it and the GPU's rule); a longer choice is kept, with a note.
6684    The 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
6686    return 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
6691    one an older command-line Strata uses, so an old install is never adopted or moved."""
6692    raw = os.environ.get("STRATA_SETTINGS_FILE")
6693    return Path(raw) if raw else None
6694
6695
6696def settings_path() -> Path:
6697    own = app_settings_file()
6698    if own is not None:
6699        return own
6700    if WIN:
6701        return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Strata" / "settings.json"
6702    return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "settings.json"
6703
6704
6705def load_settings() -> dict:
6706    try:
6707        return json.loads(settings_path().read_text(encoding="utf-8"))
6708    except (OSError, ValueError):
6709        return {}
6710
6711
6712def save_settings(s: dict) -> None:
6713    if s.get("data_dir") and s.get("data_dir") != load_settings().get("data_dir"):
6714        s = {**s, "data_dir_at": time.time()}           # when the models folder was chosen: the app and the Terminal keep the newer choice
6715    try:
6716        settings_path().parent.mkdir(parents=True, exist_ok=True)
6717        settings_path().write_text(json.dumps(s, indent=1), encoding="utf-8")
6718    except OSError as e:
6719        warn(f"could not save {settings_path()} ({e})")
6720
6721
6722def has_data(folder: Path) -> bool:
6723    for d in DATA_ITEMS:
6724        try:
6725            if (folder / d).is_dir() and any((folder / d).iterdir()):
6726                return True
6727        except OSError:
6728            pass
6729    return 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
6734    next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`)."""
6735    cands = [Path(p) for p in settings.get("installs", []) if not in_trash(p)]
6736    for base in dict.fromkeys(() if app_settings_file() else (home().parent, home().parent.parent)):
6737        try:
6738            for d in base.iterdir():
6739                if d.is_dir() and d.name.lower().startswith("strata"):
6740                    cands.append(d)
6741                    cands += [c for c in d.iterdir() if c.is_dir() and c.name.lower().startswith("strata")]
6742        except OSError:
6743            pass
6744    found = []
6745    for d in cands:
6746        try:
6747            d = d.resolve()
6748            if d != home() and d not in found and (d / "setup.py").is_file():
6749                found.append(d)
6750        except OSError:
6751            pass
6752    return found
6753
6754
6755def same_drive(a: Path, b: Path) -> bool:
6756    try:
6757        return os.stat(a).st_dev == os.stat(b).st_dev
6758    except OSError:
6759        return 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
6764    destination has.  Whatever cannot be moved (a file in use) stays where it is."""
6765    if not dst.exists():
6766        try:
6767            dst.parent.mkdir(parents=True, exist_ok=True)
6768            atomic.replace(src, dst)
6769            return
6770        except OSError:
6771            if not src.is_dir():
6772                return
6773            dst.mkdir(parents=True, exist_ok=True)
6774    if src.is_dir() and dst.is_dir():
6775        for c in list(src.iterdir()):
6776            move_into(c, dst / c.name)
6777        try:
6778            src.rmdir()
6779        except OSError:
6780            pass
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
6785    now there and no longer at the old place)."""
6786    try:
6787        cfg = json.loads(cfg_file.read_text(encoding="utf-8-sig"))
6788    except (OSError, ValueError):
6789        return
6790
6791    def fix(v):
6792        if isinstance(v, list):
6793            return [fix(x) for x in v]
6794        if isinstance(v, dict):
6795            return {k: fix(x) for k, x in v.items()}
6796        if isinstance(v, str):
6797            for d in DATA_ITEMS:
6798                o = str(old / d)
6799                nv, no = os.path.normcase(v), os.path.normcase(o)   # Windows: C:\ and c:\ are the same place
6800                if nv == no or nv.startswith(no + os.sep):
6801                    n = str(new / d) + v[len(o):]
6802                    if Path(n).exists() and not Path(v).exists():
6803                        return n
6804        return v
6805
6806    new_cfg = fix(cfg)
6807    if new_cfg != cfg:
6808        write_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."""
6813    total = 0
6814    for d in DATA_ITEMS:
6815        for root, _dirs, files in os.walk(folder / d):
6816            for f in files:
6817                try:
6818                    total += os.path.getsize(os.path.join(root, f))
6819                except OSError:
6820                    pass
6821    return 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)."""
6826    try:
6827        return os.path.samefile(a, b)
6828    except OSError:
6829        return 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
6835    A --data-dir that names a NEW folder never moves anything by itself.  When model files already exist elsewhere,
6836    the person is asked: keep them where they are and use the new folder for new downloads (the answer with --yes
6837    or 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
6840    remembered data folder and their configs point there (that is the data folder's own job)."""
6841    settings = load_settings()
6842    remembered = Path(settings["data_dir"]) if settings.get("data_dir") else home().parent / "Strata-data"
6843    dest = Path(requested).expanduser().resolve() if requested else remembered
6844    from strata_control import folders
6845    bad = folders.problem(dest)
6846    if bad and requested:
6847        fail(folders.without_nothing_changed(bad)[:400], "Nothing was downloaded or changed, and the folder was not saved as your data folder.")
6848    if bad and settings.get("data_dir"):                # an unusable folder saved earlier: go back to the default and say so; never keep it
6849        warn(f"The data folder saved before cannot be used ({bad[0]}) Using {home().parent / 'Strata-data'} instead.")
6850        remembered = dest = home().parent / "Strata-data"
6851        settings = {k: v for k, v in settings.items() if k != "data_dir"}
6852    try:
6853        dest.mkdir(parents=True, exist_ok=True)
6854    except OSError as e:                                # e.g. no write access next to the Strata folder
6855        warn(f"cannot use {dest} for the model files ({e}): keeping them in {home()}")
6856        dest = home()
6857    elsewhere = []
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)
6860    sources = [home(), *other_installs(settings)]
6861    if settings.get("data_dir") and not same_folder(Path(settings["data_dir"]), dest):
6862        sources.append(Path(settings["data_dir"]))
6863    sources += [f / "Strata-data" for f in list(sources) if not same_folder(f / "Strata-data", dest)]
6864    if requested and not same_folder(dest, remembered):
6865        sources.append(remembered)
6866        # a different folder than the one in use: nothing is moved unless the person says so
6867        held = []
6868        for folder in dict.fromkeys(sources):
6869            if not same_folder(folder, dest) and has_data(folder) and not any(same_folder(folder, h) for h in held):
6870                held.append(folder)
6871        movable = [f for f in held if same_drive(f, dest)]
6872        if movable and not move and not yes:
6873            gb = sum(library_size_gb(f) for f in movable)
6874            say()
6875            size = f"{gb:.0f} GB" if gb >= 10 else f"{gb:.1f} GB"
6876            say(f"  Your models are in {', '.join(str(f) for f in movable)} ({size}).")
6877            say(f"  keep) leave them there and use {dest} only for new downloads")
6878            say(f"  move) move your {size} of models to {dest}")
6879            move = 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"
6881        if held and not move:
6882            for folder in held:
6883                say(f"  Models you already have in {folder} stay there; new downloads go to {dest}.")
6884            if set_default:
6885                save_settings({**settings, "data_dir": str(dest)})
6886            return dest, held
6887        if not held:
6888            move = True                                 # nothing to lose track of: the new folder becomes the default
6889    seen = set()
6890    for folder in sources:
6891        key = os.path.normcase(str(folder))
6892        if key in seen:
6893            continue
6894        seen.add(key)
6895        if same_folder(folder, dest) or not has_data(folder):
6896            continue
6897        if not same_drive(folder, dest):
6898            elsewhere.append(folder)                    # another drive: used where it is (no 70 GB copy)
6899            continue
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
6902        if (folder / "models").is_dir():
6903            move_into(folder / "models", dest / "models")
6904        for item in [*((folder / "packs").glob("*") if (folder / "packs").is_dir() else []), folder / "mtp"]:
6905            rel = item.relative_to(folder)
6906            if item.exists() and not (dest / rel).exists():
6907                move_into(item, dest / rel)
6908        for d in ("packs",):
6909            try:
6910                (folder / d).rmdir()                    # empty now
6911            except OSError:
6912                pass
6913        for c in model_config_files(folder):
6914            repoint_config(c, folder, dest)
6915        if has_data(folder):
6916            elsewhere.append(folder)                    # in use, or a copy the data folder already has
6917            warn(f"some model files are still in {folder} (in use, or already in {dest})")
6918        else:
6919            ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)")
6920    installs = [str(home())] + [p for p in settings.get("installs", [])
6921                                if p != str(home()) and Path(p).is_dir() and not in_trash(p)]
6922    save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]})
6923    return 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)."""
6928    return data_folder(getattr(a, "data_dir", None), getattr(a, "move_data", False), bool(getattr(a, "yes", True)),
6929                       getattr(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
6934    the settings and nothing else: no folder is created, nothing is moved or copied, no setting is saved.  The run
6935    configs name their model files, so an install made by an earlier Strata starts from where it is."""
6936    settings = load_settings()
6937    dest = Path(settings["data_dir"]) if settings.get("data_dir") else home().parent / "Strata-data"
6938    from strata_control import folders
6939    if settings.get("data_dir") and folders.problem(dest):      # a folder saved earlier that cannot be used: the default, and it is not kept
6940        dest = home().parent / "Strata-data"
6941    return 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
6946    a setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind."""
6947    tmp = path.with_name(path.name + ".tmp")
6948    tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
6949    atomic.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
6969    not write (`SETUP_KEYS`), the "env" entries setup does not write, and in "vision" the keys setup does not write
6970    plus an mmproj of their own (a Q8_0 one, #625) that still exists.  `cfg` (the new config) is updated in place;
6971    the names of what was kept are returned.  Engine options added by hand to "args" are not merged (setup chooses
6972    those): `args_dropped` names them.  `explicit`: engine options given on this run's command line (they win and are
6973    kept from now on, see carry_user_args)."""
6974    kept = []
6975    for k, v in old.items():
6976        if k not in SETUP_KEYS and k not in cfg:
6977            cfg[k] = v
6978            kept.append(k)
6979    mine = SETUP_ENV if "-unsloth-" in str(cfg.get("model_name") or "") else SETUP_ENV - SETUP_ENV_UNSLOTH
6980    env = {k: v for k, v in (old.get("env") or {}).items() if k not in mine and k not in (cfg.get("env") or {})} \
6981        if isinstance(old.get("env"), dict) else {}
6982    if env:
6983        cfg["env"] = {**(cfg.get("env") or {}), **env}
6984        kept += [f"env {k}" for k in env]
6985    ov, nv = old.get("vision"), cfg.get("vision")
6986    if isinstance(ov, dict) and isinstance(nv, dict):
6987        for k, v in ov.items():
6988            if k not in SETUP_VISION and k not in nv:
6989                nv[k] = v
6990                kept.append(f"vision {k}")
6991        mm = ov.get("mmproj")                          # a file of the user's own: not the one setup downloads
6992        if isinstance(mm, str) and Path(mm).name != Path(str(nv.get("mmproj"))).name and Path(mm).is_file():
6993            nv["mmproj"] = mm
6994            kept.append("vision mmproj")
6995    kept += carry_profile_args(old, cfg)
6996    kept += carry_user_args(old, cfg, explicit)
6997    off = draft_layer.apply(cfg)                       # "mtp": false was the user's (a key setup does not write): the new args honour it
6998    if off:
6999        kept.append("mtp off (" + " ".join(off) + " left out of args)")
7000    return 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
7010    that has no `args_written` (written by an earlier Strata): an option in its args that is not in this set was added by hand."""
7011    global _SETUP_FLAGS
7012    if _SETUP_FLAGS is None:
7013        try:
7014            text = Path(__file__).read_text(encoding="utf-8")
7015            _SETUP_FLAGS = frozenset(re.findall(r'"(--[a-z][a-z0-9-]+)"', text))
7016        except OSError:
7017            _SETUP_FLAGS = frozenset()
7018    return _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."""
7026    n = getattr(a, "vram_reserve_mib", None)
7027    return ["--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
7032    generated 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"
7034    the options its args had and the new ones do not (control vectors, --spec, ...) and an explicit --vram-reserve-mib of
7035    the earlier file.  `explicit`: options given on this run's command line, which win.  The names kept are returned."""
7036    nargs = cfg.get("args")
7037    if not isinstance(nargs, list):
7038        return []
7039    mine = user_args.capture(old, SETUP_CHOICE_FLAGS)
7040    oargs = old.get("args")
7041    if user_args.WRITTEN_KEY not in old and isinstance(oargs, list):
7042        have = {user_args.flag_of(g) for g in user_args.groups(mine)}
7043        mine += user_args.flat([g for g in user_args.groups(user_args.dropped_by_setup(oargs, nargs, setup_flags(), SETUP_CHOICE_FLAGS))
7044                                if user_args.flag_of(g) not in have])
7045        reserve = flag_value(oargs, "--vram-reserve-mib")   # an old file: the reserve it names, unless it is the vision default or the app's own
7046        vis = isinstance(old.get("vision"), dict)
7047        if 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:
7048            mine += ["--vram-reserve-mib", reserve]
7049    for g in user_args.groups(explicit or []):
7050        mine = user_args.merge(mine, g)
7051    if not mine:
7052        user_args.stamp(cfg, [])
7053        return []
7054    cfg["args"] = user_args.merge(nargs, mine)
7055    user_args.stamp(cfg, mine)
7056    return ["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."""
7061    for i, a in enumerate(args[:-1]):
7062        if a == flag:
7063            return str(args[i + 1])
7064    return 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
7070    256K on a 16 GB card in the report).  Their --expert-profile replaces the shipped one only when it is another file
7071    that still exists; --expert-profile-save is kept when the new config has none.  The names kept are returned."""
7072    oargs, nargs = old.get("args"), cfg.get("args")
7073    if not isinstance(oargs, list) or not isinstance(nargs, list):
7074        return []
7075    kept = []
7076    mine, shipped = flag_value(oargs, "--expert-profile"), flag_value(nargs, "--expert-profile")
7077    if mine and shipped and Path(mine).name != Path(shipped).name and Path(mine).is_file():
7078        nargs[nargs.index("--expert-profile") + 1] = mine
7079        kept.append("args --expert-profile")
7080    save = flag_value(oargs, "--expert-profile-save")
7081    if save and flag_value(nargs, "--expert-profile-save") is None:
7082        nargs += ["--expert-profile-save", save]
7083        kept.append("args --expert-profile-save")
7084    return 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
7089    by hand, which a setup run does not carry over - the start of the line that names them."""
7090    def flags(c):
7091        a = c.get("args") if isinstance(c.get("args"), list) else []
7092        return [str(x) for x in a if str(x).startswith("--")]
7093    new = set(flags(cfg))
7094    return 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."""
7102    if SHAPE_ENGINE.get("shape"):
7103        from strata_control import shape_engine
7104        return shape_engine.reference(SHAPE_ENGINE["shape"])
7105    return "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
7110    to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as
7111    strata-<model>.json.bak when it changes.  `source`: an earlier install's config to carry the keys over from when
7112    this folder has none yet (a copy set up like the last one).  A line says what was kept, one what was not."""
7113    if SHAPE_ENGINE.get("title") and SHAPE_ENGINE.get("shape") and cfg.get("exe") == engine_component.REFERENCE_PREFIX + "strata-" + SHAPE_ENGINE["shape"].replace("_", "-"):
7114        cfg["shape_title"] = SHAPE_ENGINE["title"]                  # the engine's refusal at a start names the model, not the geometry (strata_control/shape_engine.py)
7115    old_path = cfg_path if cfg_path.is_file() else source
7116    old = None
7117    if old_path is not None and old_path.is_file():
7118        try:
7119            old = json.loads(old_path.read_text(encoding="utf-8-sig"))
7120        except (OSError, ValueError):
7121            pass
7122        if not isinstance(old, dict):
7123            old = None
7124    kept = carry_over(old, cfg, explicit) if old is not None else []
7125    if old is None:
7126        carry_user_args({}, cfg, explicit)              # a first install: only what this run's command line sets (nothing to report as kept)
7127    if after_carry is not None:                        # a check of the finished argument list (the person's own options are in it now)
7128        after_carry(cfg)
7129    user_args.stamp(cfg)                               # args_written: what setup wrote, for the next hand-edit check
7130    if "images" in cfg and cfg["images"] is None:      # --images no (or not downloaded): no image section
7131        cfg.pop("images")
7132    bak = None
7133    if cfg_path.is_file() and old != cfg:
7134        bak = cfg_path.with_name(cfg_path.name + ".bak")
7135        try:
7136            shutil.copyfile(cfg_path, bak)
7137        except OSError as e:
7138            warn(f"could not keep a copy of the earlier {cfg_path.name} ({e.strerror or e})")
7139            bak = None
7140    write_config(cfg_path, cfg)
7141    if kept:
7142        ok(f"kept from your earlier {old_path.name}: " + ", ".join(kept))
7143    if bak is not None:
7144        dropped = args_dropped(old, cfg) if old is not None else []
7145        say(f"  the earlier run config is kept as {bak.name}" + (
7146            f"; engine options it had that this one has not (setup chooses those): {' '.join(dropped)}"
7147            if 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."""
7152    text = None
7153    try:
7154        text = path.read_text(encoding="utf-8-sig")
7155        if isinstance(json.loads(text), dict):
7156            return True
7157        why = "not a JSON object"
7158    except OSError as e:
7159        why = e.strerror or str(e)
7160    except ValueError:                                 # JSONDecodeError, or bytes that are not UTF-8
7161        why = "the file is empty" if text is not None and not text.strip() else "not valid JSON"
7162    warn(f"skipped the earlier config {path} ({why}): setting this copy up without it")
7163    return 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
7168    next to it as strata-<model>.shared-settings.json: it matches the pattern but is no config (no exe, no args)."""
7169    return [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
7174    that does not parse (an empty or cut-off file, #459) is skipped with a warning: the newest readable one is used,
7175    and with none this copy is set up as a fresh install."""
7176    cands = []
7177    for folder in [*elsewhere_first, *other_installs(settings)]:
7178        cands += model_config_files(folder)
7179    from strata_control import retired
7180    cands = [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
7181    return 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."""
7186    return 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)."""
7191    cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))
7192    tag = cfg_path.stem[len("strata-"):]
7193    own = next((f for f, d in OWN_PATH_FAMILIES.items() if tag.startswith(d["tag"])), None)
7194    if own is not None:                                # Qwen3.6: its own sizes; no KV / images / projection settings
7195        d = OWN_PATH_FAMILIES[own]
7196        size = next((m for m in d["models"] if m.lower() == tag[len(d["tag"]):].lower()), None)
7197        a = cfg.get("args", [])
7198        ctx = a[a.index("--max-context") + 1] if "--max-context" in a and a.index("--max-context") + 1 < len(a) else None
7199        vis = cfg.get("vision")
7200        return {"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}
7204    family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen")
7205    model = (tag[len(FAMILIES[family]["tag"]):] if tag.startswith(FAMILIES[family]["tag"]) else tag).upper()
7206    model = next((m for m in MODELS if m.upper() == model), model)       # (the catalog's spelling: UD-IQ4_XS-v31 has a lower-case v)
7207    if model not in MODELS:                            # (sizes have no dash except UD-Q4_K_XL: the old rule)
7208        model = tag.split("-")[-1].upper()
7209    a = cfg.get("args", [])
7210    val = lambda k: a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None   # noqa: E731
7211    vis = cfg.get("vision")
7212    esp = val("--control-vector-scaled")
7213    esp_path = esp.rsplit(":", 1)[0] if esp else None
7214    return {"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 (
7223                vis 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."""
7228    if not (model or family):
7229        return [c for c in have if choices_from_config(c)["family"] not in OWN_PATH_FAMILIES]
7230    out = []
7231    for c in have:
7232        ch = choices_from_config(c)
7233        if ch["family"] in OWN_PATH_FAMILIES:            # the tuning measures Flash-Next's engine settings
7234            continue
7235        if (not model or ch["model"] == model) and (not family or ch["family"] == family):
7236            out.append(c)
7237    return out
7238
7239
7240def find_in(roots: list, rel: str):
7241    """The first of roots/rel that exists."""
7242    for r in roots:
7243        if (r / rel).exists():
7244            return r / rel
7245    return 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
7250    folder's models/ (a Strata data folder's layout: models/<size>/ shards, models/<picture file>; pictures.places() looks there too).  The two outer places are
7251    taken only at the pinned size (`size`), so a half-copied file is fetched again and not used.  None when there is none."""
7252    if not gguf_dir:
7253        return None
7254    base = Path(gguf_dir)
7255    own = base / name
7256    if own.is_file():
7257        return own
7258    for r in (base.parent, base.parent / "models"):
7259        f = r / name
7260        try:
7261            if f.is_file() and (size is None or f.stat().st_size == size):
7262                return f
7263        except OSError:
7264            continue
7265    return 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
7278    models/, and a person's own GGUF folder: beside the shards, the folder above and that folder's models/)."""
7279    alt = ALT_READERS.get(pinned)
7280    if alt is None:
7281        return []
7282    places = [Path(models_dir) / alt[0]] + [Path(r) / "models" / alt[0] for r in roots or []]
7283    if gguf_dir:
7284        base = Path(gguf_dir)
7285        places += [base / alt[0], base.parent / alt[0], base.parent / "models" / alt[0]]
7286    return 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
7291    else 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
7292    marks/ 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
7294    the setup run (says what it does, writes the mark); start=False is the plan (the same answer, says nothing, writes nothing)."""
7295    alt = ALT_READERS.get(pinned)
7296    if alt is None:
7297        return None
7298    name, size, sha = alt
7299    for p in places:
7300        p = Path(p)
7301        try:
7302            if p.name != name or not p.is_file() or p.stat().st_size != size:
7303                continue                                   # absent, another name or another size: ignored exactly as before
7304        except OSError:
7305            continue
7306        digest = None
7307        kept = _alt_reader_mark(p)
7308        try:
7309            found = _ALT_MARK.match(kept.read_text(encoding="utf-8", errors="replace")) if kept is not None and kept.exists() else None
7310            digest = found.group(1) if found else None
7311        except OSError:
7312            digest = None
7313        if digest is None:
7314            if start:
7315                say(f"  checking {p.name} (SHA-256, {size / 1e9:.1f} GB) ...")
7316            digest = _hash_file(p, size)
7317            if start and kept is not None:
7318                try:
7319                    kept.parent.mkdir(parents=True, exist_ok=True)
7320                    kept.write_text(f"alt-reader sha256 {digest}\n", encoding="utf-8")
7321                except OSError:
7322                    pass                                   # (not remembered: the next run hashes again; nothing else changes)
7323        if digest == sha:
7324            return p
7325        if start:
7326            say(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).")
7328    return 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
7333    install'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
7334    person's own folder (mmproj_beside); "alt": a verified Unsloth mmproj-F16.gguf the person already has (only when no pinned file is anywhere)."""
7335    if mmproj.exists():
7336        return "fetch", mmproj
7337    near = mmproj_beside(gguf_dir, pinned, size)
7338    if near is not None:
7339        return "near", near
7340    alt = accepted_alt_reader(pinned, alt_reader_places(pinned, models_dir, roots, gguf_dir), start=True)
7341    if alt is not None:
7342        return "alt", alt
7343    return "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
7348    available 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
7349    any file put there by hand.  True when `dst` is there."""
7350    if dst.exists():
7351        return True
7352    try:
7353        sibs = sorted(p for p in parent.glob("*/" + name) if p.is_file() and p != dst and p.stat().st_size == size)
7354    except OSError:
7355        return False
7356    for src in sibs:
7357        try:
7358            dst.parent.mkdir(parents=True, exist_ok=True)
7359            try:
7360                os.link(src, dst)
7361            except OSError:
7362                tmp = dst.with_name(dst.name + ".copying")
7363                shutil.copyfile(src, tmp)
7364                os.replace(tmp, dst)
7365            return True
7366        except OSError:
7367            continue
7368    return 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
7374    file of the user's own, a cut-off one) is skipped with a warning naming it instead of stopping setup."""
7375    try:
7376        cfg = json.loads(path.read_text(encoding="utf-8-sig"))
7377        if isinstance(cfg, dict) and cfg.get("exe") and isinstance(cfg.get("args"), list):
7378            return True
7379        why = 'no "exe" or "args"'
7380    except OSError as e:
7381        why = e.strerror or str(e)
7382    except ValueError:
7383        why = "not valid JSON"
7384    warn(f"skipped {path.name} ({why}): it is not a Strata model config")
7385    return 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:
7390    retired_configs, strata_control/retired.py)."""
7391    from strata_control import retired
7392    return [p for p in sorted(model_config_files(home()), key=lambda p: p.stat().st_mtime, reverse=True)
7393            if 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."""
7398    from strata_control import retired
7399    return [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
7404    Terminal carries no CMakeLists.txt (it ships VERSION and BUNDLE.json), and a missing file was a FileNotFoundError out of
7405    prebuilt_bases() that ended the whole setup (#4188)."""
7406    try:
7407        m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8"))
7408    except (OSError, UnicodeDecodeError):
7409        return "0"
7410    return 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
7415    it), read from the file without running it.  None: unreadable, or a binary without it."""
7416    try:
7417        m = re.search(rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n", Path(exe).read_bytes())
7418    except OSError:
7419        return None
7420    return 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
7425    source's hash and version cannot be trusted alone: a build that stopped (a host compiler the toolkit rejects) can
7426    leave the old binary beside a stamp of the new source, and nothing would ever compile it again."""
7427    v, source = binary_engine_version(exe), source_version()
7428    return 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
7433    engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept
7434    (issue #49)."""
7435    try:
7436        meta = json.loads((Path(exe).parent / "BUILD.json").read_text(encoding="utf-8"))
7437    except (OSError, ValueError):
7438        meta = {}
7439    v = str(meta.get("version") or "")
7440    if not v:                                          # the version compiled into the binary: 0.1.13 and newer
7441        try:                                           # carry it, so a binary without it is older
7442            m = re.search(rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n", Path(exe).read_bytes())
7443            v = m.group(1).decode() if m else "0.1.12"
7444        except OSError:
7445            v = "0"
7446    return tuple(int(x) for x in v.split(".")[:4] if x.isdigit())
7447
7448
7449def is_wsl() -> bool:
7450    return 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
7455    WSL pins little), so only there."""
7456    return 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."""
7461    if WIN:
7462        return None
7463    try:
7464        st = os.stat(path)
7465        p = Path(f"/sys/dev/block/{os.major(st.st_dev)}:{os.minor(st.st_dev)}").resolve()
7466        for q in (p, p.parent):                        # a partition has its disk's queue
7467            f = q / "queue" / "rotational"
7468            if f.exists():
7469                return q.name if f.read_text().strip() == "1" else None
7470    except (OSError, ValueError, AttributeError):
7471        pass
7472    return 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
7477    lists them; no "gpu": the supported card with the most VRAM, as setup picks it.  Each card's name carries its
7478    architecture (an RX 7900 XTX and an RX 7900 XT are both gfx1100; a card without a product name in sysfs is known
7479    by its arch only).  A card that is not found is {} (the key then says "?")."""
7480    amd = amd_gpus()
7481    if sel is None:
7482        usable = [g for g in amd if amd_problem(g) is None]
7483        sel = min(usable, key=amd_rank)["index"] if usable else None
7484    byid = {g["index"]: g for g in amd}
7485    cards = []
7486    for i in (sel if isinstance(sel, list) else [sel]):
7487        g = byid.get(i)
7488        if g is None:
7489            cards.append({})
7490            continue
7491        arch = g.get("arch") or ""
7492        name = g.get("name") or "?"
7493        cards.append({**g, "name": name if not arch or arch in name else f"{name} ({arch})"})
7494    return 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
7499    the same way).  [] when it names none.  Without this, a string "0,1" reached gpu_info() whole and
7500    calibrate died with "there is no GPU 0,1" on a dual-GPU config."""
7501    if value is None or value == "":
7502        return []
7503    items = value if isinstance(value, (list, tuple)) else str(value).split(",")
7504    sel = []
7505    for x in items:
7506        x = str(x).strip()
7507        if x == "":
7508            continue
7509        sel.append(int(x) if x.isdigit() else x)
7510    return 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
7516    AMD's (hip_config_cards) - nvidia-smi's list named them "?" (or another card with that number) before."""
7517    sel = cfg.get("gpu")
7518    if isinstance(sel, str):
7519        sel = gpu_sel(sel)
7520    if cfg.get("backend") == "hip":
7521        gl = hip_config_cards(sel)
7522    else:
7523        gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}]
7524    g = {"name": " + ".join(x.get("name", "?") for x in gl), "vram_gb": sum(x.get("vram_gb", 0) for x in gl)}
7525    a = cfg.get("args", [])
7526    ctx = a[a.index("--max-context") + 1] if "--max-context" in a else "?"
7527    return "|".join([g.get("name", "?"), f"{g.get('vram_gb', 0):.0f}GB", cpu_info()[0], f"{ram_gb():.0f}GB",
7528                     cfg.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
7533    config and remember them per PC and model in the settings file, so an update or a reinstall keeps them."""
7534    sys.path.insert(0, str(ROOT / "tools"))
7535    import calibrate as CAL
7536    cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))
7537    say()
7538    say("  Tuning Strata for this PC: the output speed is measured with a few engine settings (the PCIe share, the")
7539    say("  draft depth, the CPU threads, the expert cache; on two or more cards also the prompt chunks). It takes")
7540    say("  roughly 15-30 minutes (3 rounds of each value); the PC is busy meanwhile.")
7541    try:
7542        since = os.path.getsize(cfg["log"]) if cfg.get("log") and os.path.isfile(cfg["log"]) else 0
7543    except OSError:
7544        since = 0
7545    try:
7546        res = CAL.run(cfg, say=say)
7547    except Exception as e:                             # never stops an install: the defaults stay
7548        warn(f"the tuning did not finish ({e}): the default settings stay")
7549        why = CAL.engine_error(cfg.get("log"), since)  # #447: the engine's own reason, not only "see the log"
7550        if why:
7551            say(f"       the engine said: {why}")
7552        return False
7553    cfg["args"] = CAL.apply(cfg["args"], res["settings"])
7554    if "env" in res:                                   # HIP: the engine variables it measured (STRATA_SH_STREAM)
7555        cfg["env"] = CAL.apply_env(cfg.get("env"), res["env"])
7556    write_config(cfg_path, cfg)
7557    st = load_settings()
7558    st.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")}
7561    save_settings(st)
7562    chosen = {**res["settings"], **(res.get("env") or {})}
7563    if chosen:
7564        ok("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 ""))
7566    else:
7567        ok("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 ""))
7569    return True
7570
7571
7572def saved_calibration(cfg: dict) -> dict | None:
7573    """The settings an earlier calibration found for this PC and model, if any."""
7574    return (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
7579    HIP too - hardware_key now names the AMD cards, so a `./setup.sh --calibrate` run is matched to its card and
7580    model.  Windows HIP keeps the defaults for now (not tried there).  Setup still offers the tuning itself on NVIDIA
7581    only: each control is verified on HIP first."""
7582    if hip and WIN:
7583        return None
7584    return 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
7589    itself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts).  Under WSL,
7590    KV streaming is dropped: its RAM copy must be pinned, and the driver pins only about 1 GB there."""
7591    a = cfg.get("args", [])
7592    changed = False
7593    ver = engine_version(cfg["exe"]) if "--prefill" in a else (0, 0, 0)
7594    if "--prefill" in a and a[a.index("--prefill") + 1] == "2048" and ver >= (0, 1, 13):
7595        a[a.index("--prefill") + 1] = "auto"
7596        changed = True
7597        ok("prompt reading: the engine now picks its chunk size (--prefill auto)")
7598    elif "--prefill" in a and a[a.index("--prefill") + 1] == "auto" and (0, 0, 0) < ver < (0, 1, 13):
7599        a[a.index("--prefill") + 1] = "2048"           # an older engine kept after a failed update (issue #49)
7600        changed = True
7601        warn(f"the installed engine is {'.'.join(map(str, ver))}: prompts are read in 2048-token chunks until it is updated")
7602    if is_wsl() and "--kv-resident" in a:
7603        i = a.index("--kv-resident")
7604        del a[i:i + 2]
7605        changed = True
7606        ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM")
7607    if changed:
7608        write_config(cfg_path, cfg)
7609    return 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
7614    an install before it starts the model, without starting it - the Python packages, the ready-made engine when this
7615    setup needs a newer one (MIN_ENGINE; a compiled engine when its source changed), each installed model's config
7616    upgrades and its draft subset.  No question is asked and the model files are not touched; a model still running
7617    keeps its engine (update_installed_engine says to close it and run this again)."""
7618    have = [p for p in have if model_config(p)]        # #549: a strata-*.json that is no model config is skipped
7619    if not have:
7620        say("  No model is installed in this Strata folder yet: run START-HERE.bat (Linux: ./setup.sh) to set it up -")
7621        say("  it finds an earlier install's model files next to it and reuses them.")
7622        return 0
7623    pip_install(runtime_packages(),
7624                "numpy, jinja2, regex, pyyaml, tqdm, requests, pillow, psutil, textual (the screens)")
7625    if not a.build:
7626        update_installed_engine(a.prebuilt)
7627    mtp_done: set = set()
7628    for cfg_path in have:
7629        cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig")))
7630        if not own_path_config(cfg):
7631            refresh_shared_draft_vocab(cfg, mtp_done)
7632        if cfg.get("backend") == "hip" and WIN:
7633            hip_runtime_beside_exe(Path(cfg["exe"]).parent)   # #468 #461
7634        ok(f"{cfg.get('model_name', cfg_path.stem)}: up to date")
7635    ver = engine_version(Path(json.loads(have[0].read_text(encoding="utf-8-sig"))["exe"]))
7636    say()
7637    start = "START-HERE.bat" if WIN else "./setup.sh"
7638    if any(ver) and tuple(ver) < MIN_ENGINE:             # #3653: the engine step failed above; "updated" would be untrue
7639        warn(f"Strata's files are updated, but the engine was NOT: it is still {'.'.join(map(str, ver))} and this Strata wants "
7640             f"{'.'.join(map(str, MIN_ENGINE))} or newer. The model still starts with the old engine.")
7641        say(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.")
7643        return 0
7644    ok("Strata is updated" + (f" (engine {'.'.join(map(str, ver))})" if any(ver) else "") +
7645       f". Start the model with {start} when you want it.")
7646    return 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)
7651    and the server's own fields, so a change made by hand to strata-<model>.json can be checked without the log."""
7652    a, out, i = [str(x) for x in cfg.get("args") or []], [], 0
7653    while i < len(a):
7654        flag = a[i]
7655        val = a[i + 1] if i + 1 < len(a) and not a[i + 1].startswith("--") else None
7656        i += 1 if val is None else 2
7657        if not flag.startswith("--"):
7658            continue                                   # a positional: the model file
7659        if val is not None and ("/" in val or "\\" in val or val.lower().endswith((".gguf", ".bin"))):
7660            continue                                   # a path: --native, --mtp, --profile ...
7661        out.append(flag if val is None else f"{flag} {val}")
7662    srv = [f"{cfg.get('host', '127.0.0.1')}:{port or cfg.get('port', 8080)}"]
7663    if cfg.get("api_key"):
7664        srv.append("api key set")
7665    if cfg.get("open_browser") is False:               # #609
7666        srv.append("no browser")
7667    for k in ("gpu", "layer_split", "draft_vocab", "fit_max_tokens", "reasoning_budget_tokens", "anthropic_thinking"):
7668        if cfg.get(k) is not None:
7669            v = cfg[k]
7670            srv.append(f"{k} {','.join(map(str, v)) if isinstance(v, list) else str(v).lower() if isinstance(v, bool) else v}")
7671    return " ".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,
7675          layer_split=None, keep=None) -> int:
7676    """Start the model.  Nothing is installed, downloaded or compiled while it starts (strata_control/acquisition.py):
7677    what is missing is named with the command that installs it (SETUP / UPDATE / strata install)."""
7678    with acquisition.forbidden():
7679        return _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,
7683           layer_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)."""
7686    cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig")))
7687    component = engine_component.is_reference(cfg["exe"])
7688    # The server resolves and verifies component engines; the reference itself is not a file.
7689    files = ([] if component else [cfg["exe"]]) + [a for a in cfg["args"] if a.endswith(".gguf")]
7690    missing = [p for p in files if not Path(p).exists()]
7691    if missing:
7692        fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair")
7693    keep = {k: v for k, v in (keep or {}).items() if v is not None}
7694    reserve = keep.pop("vram_reserve_mib", None)       # #493: an engine argument, kept in the config's args
7695    if reserve is not None:
7696        args = cfg["args"]
7697        if "--vram-reserve-mib" in args[:-1]:
7698            args[args.index("--vram-reserve-mib") + 1] = str(reserve)
7699        else:
7700            args += ["--vram-reserve-mib", str(reserve)]
7701        cfg[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
7702        if user_args.WRITTEN_KEY in cfg:
7703            cfg[user_args.WRITTEN_KEY] = list(cfg["args"])
7704        write_config(cfg_path, cfg)
7705        ok(f"saved for this model: {reserve} MiB of VRAM kept free for other programs (--vram-reserve-mib)")
7706    if keep and any(cfg.get(k) != v for k, v in keep.items()):   # #179: a --host/--api-key on a start was ignored
7707        cfg.update(keep)
7708        write_config(cfg_path, cfg)
7709        ok("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"
7711            else f"{k.replace('_', ' ')} {v}" for k, v in keep.items()))
7712    cfg_path.touch()                                     # the most recently used model
7713    if "--mtp" in cfg["args"][:-1] and not own_path_config(cfg):
7714        refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk"))
7715        from strata_control import drafting
7716        refresh_dflash2_vocab(drafting.data_dir_of(cfg["args"]), cfg.get("draft_vocab", "cjk"))
7717    cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
7718           "--port", str(port or cfg.get("port", 8080))]
7719    if cfg.get("backend") == "hip":                    # AMD, numbered as HIP numbers them (setup's KFD order)
7720        if WIN and not component:
7721            hip_runtime_beside_exe(Path(cfg["exe"]).parent)   # #468 #461: also fixes a 0.1.34 install
7722        amd = amd_gpus()
7723        if isinstance(gpu, list):                      # --gpus: saved, this model runs on these cards from now on
7724            cards = amd_parse_gpus(",".join(str(i) for i in gpu), amd)
7725            built = [] if component else (engine_archs_hip() or [])
7726            miss = [x for x in cards if built and x["arch"] not in built]
7727            if miss:
7728                fail("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)))
7730            cfg["gpu"], cfg["gpus_asked"], cfg["gpus_by"] = gpu, True, "person"
7731            cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto"
7732            split_budget(cfg, yes, True)               # #498: before it is saved (asks when the RAM is short, #737)
7733            write_config(cfg_path, cfg)
7734            gpu = None
7735        elif gpu is not None:
7736            cmd += ["--gpu", str(gpu)]
7737        found = []
7738        use = gpu if gpu is not None else cfg.get("gpu")
7739        if isinstance(use, list):
7740            byid = {x["index"]: x for x in amd}
7741            ok("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'})")
7743        else:
7744            g = next((x for x in amd if x["index"] == (use if use is not None else x["index"])
7745                      and amd_problem(x) is None), None)
7746            if g is not None:
7747                ok(f"GPU: {g['name']} ({g['vram_gb']:.0f} GB, AMD)")
7748    else:
7749        found = gpus()
7750        global OLD_GPUS                                # Pascal / Volta: named on this start, or this model's CUDA 12 engine
7751        OLD_GPUS = OLD_GPUS or old_gpus_opt_in(found, gpu if isinstance(gpu, list) else [gpu] if gpu is not None else
7752                                               cfg.get("gpu") if isinstance(cfg.get("gpu"), list) else [cfg.get("gpu")],
7753                                               12 if config_toolkit(cfg) == 12 else None)
7754    if cfg.get("backend") == "hip":
7755        pass
7756    elif isinstance(gpu, list):                        # --gpus: saved, this model runs on these cards from now on
7757        check_gpus(gpu, found, yes=yes, named=True)
7758        cfg["gpu"], cfg["gpus_asked"] = gpu, True
7759        cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto"
7760        split_budget(cfg, yes, True)                   # #498: before it is saved (asks when the RAM is short, #737)
7761        recommend_remote_expert_opt(cfg)
7762        write_config(cfg_path, cfg)
7763        gpu = None
7764    elif gpu is not None:                              # --gpu N: this start only, on that card
7765        check_gpus([gpu], found)
7766        cmd += ["--gpu", str(gpu)]
7767    else:
7768        cfg = offer_together(cfg_path, cfg, yes)
7769    use = 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)
7771    if isinstance(use, list) and (split_mmap(cfg) | split_budget(cfg)):
7772        write_config(cfg_path, cfg)
7773    if cfg.get("backend") == "hip":
7774        pass
7775    elif isinstance(use, list):
7776        check_gpus(use, found, "(chosen for this model) ", yes=True, named=True)
7777        byid = {g["index"]: g for g in found}
7778        cfg = ensure_engine_for([byid[i] for i in use], cfg_path, cfg, yes)
7779        ok("GPUs: " + " + ".join(gpu_name(byid[i]) for i in use) + f" together (layers split {cfg.get('layer_split') or 'auto'})")
7780    elif found:
7781        g = next((x for x in found if x["index"] == use), None) if use is not None else max(
7782            found, key=lambda x: (round(x["vram_gb"]), -x["index"]))
7783        if g is not None:
7784            cfg = ensure_engine_for([g], cfg_path, cfg, yes)
7785            ok("GPU: " + gpu_name(g))
7786    browser = open_browser and cfg.get("open_browser") is not False   # #609: "open_browser": false, --no-browser
7787    if browser:
7788        cmd.append("--open")
7789    gb = 0.0
7790    if "--native" in cfg["args"]:
7791        try:
7792            gb = Path(cfg["args"][cfg["args"].index("--native") + 1]).stat().st_size / 1e9
7793        except (OSError, IndexError):
7794            pass
7795    say()
7796    say("  " + "-" * 100)
7797    size = f'about {gb:.0f} GB' if gb >= 1 else '34-55 GB'
7798    a_ = cfg["args"]
7799    if "--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)
7801        say(f"  Starting {cfg.get('model_name', 'the model')}: it maps {size} of experts from the model files (the OS "
7802            "file cache reads them).")
7803    else:
7804        say(f"  Starting {cfg.get('model_name', 'the model')}: it loads {size} into RAM and locks part of it for the "
7805            "GPU.")
7806    say("  While it does, YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES (longer the first time after a")
7807    say("  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."))
7809    say("  Later, closing this window stops the model.")
7810    say("  " + "-" * 100)
7811    for n, line in enumerate(textwrap.wrap(f"Settings ({cfg_path.name}): {settings_summary(cfg, port)}", 100,
7812                                           break_on_hyphens=False)):   # #564: what this start uses
7813        say(("  " if n == 0 else "    ") + line)
7814    if 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.
7818        os.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
7820    return 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
7833    rewrites the config, and would otherwise put the default subset back."""
7834    try:
7835        v = json.loads(cfg_path.read_text(encoding="utf-8-sig")).get("draft_vocab")
7836    except (OSError, ValueError, AttributeError):
7837        return None
7838    return 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
7843    earlier config of this model chose for the same encoder device (a setup run again keeps it), else the device's
7844    default (VISION).  More is allowed with a note on the time it takes: setup recommends, it does not cap."""
7845    default = VISION[vision]["max_tokens"]
7846    if asked is None and earlier is not None:
7847        try:
7848            v = json.loads(earlier.read_text(encoding="utf-8-sig")).get("vision")
7849        except (OSError, ValueError, AttributeError):
7850            v = None
7851        mt = v.get("max_tokens") if isinstance(v, dict) and bool(v.get("gpu")) == (vision == "gpu") else None
7852        if isinstance(mt, int) and mt > 0 and mt != default:
7853            asked = mt
7854    if asked is None:
7855        return default
7856    note = ""
7857    if vision == "cpu" and asked > default:
7858        note = (" - on the CPU a picture takes longer to encode the more tokens it gets (several seconds more at "
7859                "1,024 than at 300)")
7860    elif asked > VISION["gpu"]["max_tokens"]:
7861        note = " - more than the encoder's default needs more VRAM and context per picture"
7862    ok(f"images: up to {asked} image tokens per picture (--vision-tokens; default {default}){note}")
7863    return 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
7872    start ("the draft head does not fit"), and the engine's expert cache gets what a smaller one leaves.  Setup
7873    RECOMMENDS 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."""
7875    if chosen or not 0 < vram_gb < SMALL_DRAFT_VRAM_GB:
7876        return []
7877    start = "START-HERE.bat" if WIN else "./setup.sh"
7878    return [f"Tip for a {vram_gb:.0f} GB card: the draft layer's default token subset (with Chinese, Japanese and "
7879            f"Korean) needs up to ~{DRAFT_VOCAB_MIB['cjk']} MiB of VRAM.",
7880            f"  For English and code answers, {start} --draft-vocab en needs up to ~{DRAFT_VOCAB_MIB['en']} MiB "
7881            f"(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
7891    draft layer stays: the server needs it.)"""
7892    start = "START-HERE.bat --setup" if WIN else "./setup.sh"
7893    tips = []
7894    if ctx > 8192:
7895        tips.append("an 8K context (a smaller KV cache)")
7896    if draft_vocab != "en":
7897        tips.append(f"--draft-vocab en (a draft head of ~{DRAFT_VOCAB_MIB['en']} MiB instead of "
7898                    f"~{DRAFT_VOCAB_MIB[draft_vocab or 'cjk']})")
7899    lines = ["If the start stops with \"no VRAM is left for the expert cache\" (the engine's log says how much is "
7900             "short):"]
7901    if tips:
7902        lines.append(f"  run {start} again with " + " and ".join(tips) + ", or close other programs that use the GPU.")
7903    else:
7904        lines.append("  close other programs that use the GPU.")
7905    return 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:
7926    return 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,
7930                           runtime_mib: int = 0) -> float:
7931    """MiB left for the expert cache by setup's estimate (negative: the engine would refuse to start)."""
7932    session = ctx * 13 * UD_FIT_KV_BYTES.get(kv, 1056) / 2 ** 20
7933    return 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,
7937                            runtime_mib: int = 0):
7938    """(ctx, kv, mtp, slack_mib) of the least harmful start that the estimate says fits, or None when none does.
7939    Order of harm: the KV in 4 bits, then a smaller context (down to 4608), then no draft layer on the GPU (decode
7940    up to 2x slower, but 0.8 GB for the cache); a value the user chose (--context, --kv) is not changed."""
7941    reserve = UD_FIT_ENGINE_RESERVE_MIB if reserve_mib is None else reserve_mib
7942    ctxs = [ctx] if ctx_fixed else [ctx] + [c for c in UD_FIT_CTX_STEPS if c < ctx]
7943    kvs = [kv] if kv_fixed or kv == "q4_0" else [kv, "q4_0"]
7944    for mtp in (True, False):
7945        for c in ctxs:
7946            for k in kvs:
7947                slack = unsloth_vram_slack_mib(vram_gb, c, k, reserve, mtp, runtime_mib)
7948                if slack >= UD_FIT_MIN_SLACK_MIB:
7949                    return c, k, mtp, slack
7950    return 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
7955    would have stopped, that and what setup changed instead.  Recommend, never force."""
7956    lines = [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."]
7960    if not start_ok and plan is None:
7961        lines.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\".")
7964    return 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
7976    positions the attention reads stay in VRAM) and the DeltaNet state (~0.17 GB).  Measured: 0.56 GiB at 32K int8."""
7977    kv_tok = 12 * (576 if kv == "q4_0" else 1056)
7978    return (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
7983    mostly fit in VRAM - the expert cache (each card's VRAM less ~5 GB, every card of a layer split) still holds
7984    PARALLEL_HELD of the model's experts beside the slots' sessions, which take at most PARALLEL_SHARE of it, up to 4.
7985    Where the experts mostly run on the CPU a batch reads about as many experts as the requests one by one and every
7986    slot'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
7987    slots, 4 requests together 63 tok/s against 71 one after the other (docs/BATCHING.md)."""
7988    if isinstance(vram_gbs, (int, float)):
7989        vram_gbs = [vram_gbs]
7990    cache_gb = sum(max(0.0, v - 5) for v in vram_gbs)
7991    slot = parallel_slot_gb(ctx, kv, streaming)
7992    best = 0
7993    for n in (2, 3, 4):
7994        if n * slot <= PARALLEL_SHARE * cache_gb and (cache_gb - n * slot) >= PARALLEL_HELD * arena_gb:
7995            best = n
7996    return 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
8001    one), or how the asked count compares with it (kept as asked: recommend, never force)."""
8002    rec = parallel_recommend(vram_gbs, arena_gb, ctx, kv, streaming)
8003    slot = parallel_slot_gb(ctx, kv, streaming)
8004    if asked is None or asked <= 1:
8005        if not rec:
8006            return [f"Several requests at once: left at one at a time - {PARALLEL_COST_NOTE} (docs/BATCHING.md)."]
8007        return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together instead of one "
8008                f"after the other (each takes ~{slot:.1f} GB of VRAM from the expert cache; docs/BATCHING.md)."]
8009    lines = [f"parallel requests: {asked} at once (each takes ~{slot:.1f} GB of VRAM from the expert cache, "
8010             f"{asked * slot:.1f} GB in all)"]
8011    if asked > PARALLEL_MAX:
8012        lines.append(f"the engine runs at most {PARALLEL_MAX} at once; it will use {PARALLEL_MAX}")
8013    if not rec:
8014        lines.append(f"recommended for this card: one at a time - {PARALLEL_COST_NOTE}; kept as you chose")
8015    elif asked > rec:
8016        lines.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")
8018    return 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."""
8031    return 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
8036    7.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
8037    or 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
8038    runs 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)."""
8039    arch = str((gpu or {}).get("arch", ""))
8040    if not arch.isdigit() or len(arch) < 2:
8041        return False
8042    major, minor = int(arch[:-1]), int(arch[-1])     # "70" -> 7.0, "86" -> 8.6, "120" -> 12.0
8043    if not (major >= 8 or (major == 7 and minor == 0)):
8044        return False
8045    if any(a in (args or []) for a in ("--gpus", "--layer-split")):
8046        return False
8047    e = dict(env or {})
8048    nv_chunk = e.get("STRATA_NV_CHUNK", os.environ.get("STRATA_NV_CHUNK"))
8049    defaults = e.get("STRATA_DEFAULTS", os.environ.get("STRATA_DEFAULTS"))
8050    if (nv_chunk is not None and str(nv_chunk).startswith(("0", "16"))) or str(defaults) in ("026", "0.2.6", "v0.2.6"):
8051        return False
8052    return 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
8057    default, the config or the engine's arguments (recommend, never force).  `ram` is this PC's RAM, `model_ram_gb`
8058    what the chosen model keeps in it."""
8059    tips = []
8060    cache = arg_after(args, "--expert-cache")
8061    if win and cache is not None and cache != "auto":
8062        tips.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")
8064    prefill = arg_after(args, "--prefill")
8065    if prefill == "auto:32768" and ram < PREFILL_RISK_RAM_GB:
8066        tips.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")
8068    elif prefill == "auto" and ram >= PREFILL_BIG_RAM_GB and not bare_auto_is_32768(gpu, args, env):   # already the default there (round 0212)
8069        tips.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")
8071    resident = any(a in args for a in ("--resident-experts", "--resident-budget-gib"))
8072    if resident and ram <= HEADROOM_RAM_GB and "STRATA_RESIDENT_HEADROOM_GIB" not in (env or {}):
8073        tips.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")
8076    if vision == "gpu" and 0 < vram_gb <= SMALL_VISION_VRAM_GB:
8077        tips.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")
8080    return 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)."""
8089    env = os.environ if env is None else env
8090    return 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
8095    fills it, and when the desktop needs more VRAM amdgpu moves the cache to system RAM, where the OOM killer then ends
8096    the compositor.  A recommendation, setup changes nothing."""
8097    return [f"If this AMD card also drives your desktop and the desktop or apps crash once the model is loaded, keep "
8098            f"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,
8104    which hashes only files that changed since they last checked out).  A mirror that ignored range requests left the
8105    shards' starts there instead, and the draft layer built from them accepted nothing - with no error anywhere."""
8106    if not (mtp / "tensors").is_dir():
8107        return False
8108    r = subprocess.run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "verify", "--out", str(mtp)], env=env,
8109                       stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace")
8110    return 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
8115    in setup (--draft-vocab, saved in the model's config; the default file when none)."""
8116    from strata_control import drafting
8117    if drafting.provide_vocab(data, choice or "cjk") is None:
8118        warn("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
8123    choice for a DFlash2-only install, which has no MTP folder for refresh_draft_vocab to work on."""
8124    if data is None:
8125        return
8126    from strata_control import drafting
8127    if drafting.vocab_target(data).is_file():
8128        drafting.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,
8135    Bulgarian, 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
8136    the tokens of German, Spanish, French and Polish text).
8137    Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept."""
8138    new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin"
8139    if not new.exists() or not rt.is_dir():
8140        return
8141    if dst.exists():
8142        old = hashlib.sha256(dst.read_bytes()).hexdigest()
8143        shipped = OLD_DRAFT_VOCABS | {hashlib.sha256((ROOT / "data" / f).read_bytes()).hexdigest()
8144                                      for f in DRAFT_VOCABS.values() if (ROOT / "data" / f).exists()}
8145        if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest():
8146            return
8147        ok("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)"))
8152    shutil.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'
8157    order): an MTP folder already in `done` is left alone.  Several configs can name one MTP folder (a second config of
8158    the same model: another GPU mode, another context), each with its own "draft_vocab".  Refreshed once per config,
8159    the folder ended with the subset of the config used LONGEST ago: a config without the key (cjk) put the default
8160    subset over the cyrillic one of the config in use, and its Russian answers were drafted without Cyrillic tokens.
8161    The folder takes the subset of the most recently used config that names it; a start still installs its own
8162    config's."""
8163    args = cfg.get("args") or []
8164    if "--mtp" not in args[:-1]:
8165        return
8166    from strata_control import drafting
8167    data = drafting.data_dir_of(args)
8168    if data is not None:                                  # the DFlash2 copy, once per data folder, the config used last first like the MTP folder below
8169        dkey = ("dflash2", os.path.normcase(os.path.abspath(data)))
8170        if dkey not in done:
8171            done.add(dkey)
8172            refresh_dflash2_vocab(data, cfg.get("draft_vocab", "cjk"))
8173    rt = Path(args[args.index("--mtp") + 1])
8174    key = os.path.normcase(os.path.abspath(rt))
8175    if key in done:
8176        return
8177    done.add(key)
8178    refresh_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
8183    older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'.  Such a
8184    card gets the engine compiled for all of them, before the start.  A Pascal / Volta card added to a model on the
8185    CUDA 13 engine moves the model to the experimental CUDA 12 engine (CUDA 13 has no code for it)."""
8186    if engine_component.is_reference(cfg.get("exe")):
8187        return cfg                                    # the server checks the installed component, not ROOT/engine
8188    tk = config_toolkit(cfg)
8189    if tk == 13 and any(int(g["arch"]) < CUDA13_MIN_ARCH for g in cards):
8190        return use_cuda12(cards, cfg_path, cfg, yes)
8191    missing = [g for g in cards if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))]
8192    if not missing:
8193        return cfg
8194    acquisition.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)")
8196    eng = engine_dir(tk)
8197    info = eng / "BUILD.json"
8198    meta = json.loads(info.read_text(encoding="utf-8"))
8199    say()
8200    say("  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.")
8202    main = gpu_info(cards[0]["index"])
8203    archs = sorted(set(arch_numbers(meta.get("archs"))) | {int(g["arch"]) for g in cards})
8204    vision = meta.get("vision") or ("gpu" if (eng / VEXE).exists() else "none")
8205    build_engine({**main, "archs": archs}, vision, yes, llama_override(), toolkit=tk)
8206    dirs = json.loads(info.read_text(encoding="utf-8")).get("cuda_dirs") or []
8207    cfg["lib_dirs"] = dirs + [d for d in cfg.get("lib_dirs") or [] if d not in dirs]
8208    write_config(cfg_path, cfg)
8209    return 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
8214    CUDA 12 libraries, or compiled here with a CUDA 12.x toolkit (Linux, --build, or no ready-made one)."""
8215    eng = None if build else get_prebuilt(url_base, gpu, vision, toolkit=12)
8216    if eng is not None and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local":
8217        pip_cuda_libs(12)
8218        if vision != "none" and not (eng / VEXE).exists():
8219            eng = None
8220    return 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."""
8225    meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8"))
8226    return 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
8231    the experimental CUDA 12 engine (one engine per model; its other models keep theirs)."""
8232    acquisition.require("the experimental CUDA 12 engine")
8233    old = min(int(g["arch"]) for g in cards)
8234    acquisition.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"))
8236    say()
8237    warn(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)")
8239    main = gpu_info(cards[0]["index"]) or cards[0]
8240    vision = "gpu" if cfg.get("vision") else "none"
8241    eng = get_cuda12_engine(os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL),
8242                            {**main, "archs": sorted({int(g["arch"]) for g in cards})}, vision, yes)
8243    cfg["exe"] = str(eng / EXE)
8244    cfg["cuda"] = 12
8245    cfg["lib_dirs"] = engine_lib_dirs(eng, 12)
8246    if cfg.get("vision") and (eng / VEXE).exists():
8247        cfg["vision"]["exe"] = str(eng / VEXE)
8248    write_config(cfg_path, cfg)
8249    ok(f"engine: {eng / EXE} (CUDA 12, experimental)")
8250    return 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."""
8255    serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
8256             "--port", str(port)] + (["--open"] if open_browser else [])
8257    if WIN:
8258        script = home() / f"run-{model.lower()}.bat"
8259        script.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")
8261    else:
8262        script = home() / f"run-{model.lower()}.sh"
8263        script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n",
8264                          encoding="utf-8")
8265        script.chmod(0o755)
8266    return 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
8273    Factor 1 removes the automatic expansion - the trained angles stand as they are - but it is not a
8274    switch for rope as a whole: an explicitly chosen method's settings keep their defined behavior.
8275    """
8276    return 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
8282    An explicit --rope-scaling/--rope-scale always wins - a valid user-supplied factor is kept verbatim even
8283    when a reduction changed the context.  Past the trained range an omitted method defaults to yarn -
8284    llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the
8285    magnitude correction keeps the attention temperature - and an omitted factor is derived from the
8286    final context (final / trained, at least 1), as is an explicitly chosen method's missing factor
8287    inside the trained range: factor 1, the trained angles, no expansion.  An explicit none is refused
8288    past the trained range (the setup will not configure a run it knows is out of spec) rather than
8289    silently overridden.
8290    """
8291    if scale is not None and (not math.isfinite(scale) or scale < 1.0):
8292        raise ValueError("--rope-scale must be a finite value >= 1, e.g. --rope-scale 4")
8293    if ctx <= trained:
8294        if scale is not None and scaling in (None, "none"):
8295            raise ValueError("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the "
8296                             "trained 262144, so there is nothing to scale)")
8297        if scaling in (None, "none"):
8298            return None, None          # the stock model, by choice or by default
8299        return scaling, scale if scale is not None else derived_factor(ctx, trained)
8300    if scaling == "none":
8301        raise 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")
8305    return 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:
8311    the Mac check, the pack by unified memory, the engine build, the Metal defaults). Nothing of the CUDA / HIP paths
8312    is used or changed."""
8313    return 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
8318    Intel engine: it is compiled from source on the PC (docs/INTEL_ARC.md), then sycl/setup_intel.py runs this setup
8319    with the Intel steps swapped in. Nothing of the CUDA / HIP paths is used or changed."""
8320    say()
8321    say("  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).")
8323    if WIN:
8324        fail("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")
8326    say("  There is no ready-made Intel engine: it is built from source with Intel oneAPI (icpx + oneMKL),")
8327    say("  docs/INTEL_ARC.md. Setup continues with sycl/setup_intel.py.")
8328    rest, skip = [], False
8329    for x in argv:                                     # setup_intel.py drives this setup through its AMD path
8330        if skip:
8331            skip = False
8332        elif x == "--backend":
8333            skip = True
8334        elif not x.startswith("--backend="):
8335            rest.append(x)
8336    script = ROOT / "sycl" / "setup_intel.py"
8337    if not script.exists():
8338        fail(f"{script} is missing", "use a full Strata checkout (git clone) - docs/INTEL_ARC.md")
8339    return 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
8346    cards 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."""
8348    from strata_cli.launch import adopt
8349    from strata_control import intel_app
8350    say("Strata on an Intel Arc card (the SYCL engine)")
8351    step(1, "checking this computer")
8352    if not intel_app.supported_here():
8353        fail("the Intel Arc engine runs on Linux only", "there is no Windows or Mac Intel engine yet")
8354    family = a.family or "qwen"
8355    if family not in FAMILIES or not intel_app.can_set_up(family, FAMILIES[family]):
8356        fail(f"cannot set up {family} for an Intel Arc card", "choose a Qwen3.8-Flash-Next, Swift, Coder, Gyro or Unsloth size")
8357    fam, model = FAMILIES[family], a.model
8358    if not model:
8359        fail("an Intel Arc setup needs --model, e.g. --model Q2_0")
8360    data, _elsewhere = data_folder_for(a)
8361    tag = fam["tag"] + model
8362    if a.gguf_dir:
8363        model_dir = Path(a.gguf_dir)
8364    else:
8365        model_dir = (Path(a.models_dir) if a.models_dir else data / "models") / tag
8366    if model_dir.is_file():
8367        model_dir = model_dir.parent
8368    shards = intel_app.model_files_in(model_dir, family, fam)
8369    if not shards:
8370        fail(intel_app.NO_DOWNLOAD)
8371    ok(f"model files: {model_dir} ({len(shards)} file{'s' if len(shards) != 1 else ''})")
8372    cards = intel_app.arc_cards()
8373    vram = max((float(c.get("vram_gb") or 0) for c in cards), default=0.0)
8374    ok("graphics card: " + (", ".join(f"{c['name']} ({c['vram_gb']:g} GB)" for c in cards) or "an Intel Arc"))
8375    if a.check:
8376        return 0
8377    SHAPE_ENGINE.clear()
8378    if fam.get("shape"):                               # a feed model of its own shape: its own engine component, fetched from the signed feed (strata_control/shape_engine.py)
8379        SHAPE_ENGINE["shape"], SHAPE_ENGINE["title"] = fam["shape"], fam.get("title")
8380        shape_engine_fetch(a)
8381    step(2, "preparing the model for this graphics card")
8382    pack = data / "packs" / tag.lower()
8383    if not ((pack / "experts.bin").exists() or ((pack / "index.txt").exists() and (pack / "tokenizer" / "vocab.json").exists())):
8384        a.gguf_dir, a.prepare_pack = str(model_dir), str(pack)
8385        rc = prepare_pack_only(a)
8386        if rc:
8387            return rc
8388    else:
8389        ok(f"model already prepared: {pack}")
8390    step(3, "writing the run settings")
8391    notes: list = []
8392    cfg, problems = adopt.plan(family=family, model=model, model_dir=model_dir, data_dir=data, src=ROOT, context=a.context or 32768, kv=a.kv,
8393                               model_name=f"{fam.get('name', family)}-{model.lower()}", family_def=fam, log=home() / f"strata-{tag.lower()}.log",
8394                               backend="sycl", vram_gb=vram, notes=notes, pack_name=tag.lower())
8395    if cfg is None:
8396        fail("Strata cannot start this model on the Intel Arc card yet: " + "; ".join(problems))
8397    if a.port:
8398        cfg["port"] = a.port
8399    if a.host:
8400        cfg["host"] = a.host
8401    if a.api_key:
8402        cfg["api_key"] = a.api_key
8403    if a.browser is not None:
8404        cfg["open_browser"] = a.browser
8405    cfg_path = home() / f"strata-{tag.lower()}.json"
8406    write_setup_config(cfg_path, cfg)
8407    for n in notes:
8408        say("  " + n)
8409    ok(f"run settings: {cfg_path.name}")
8410    say()
8411    say("All set.")
8412    return 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
8417    there and never fetched or built. A model can be downloaded and prepared before the engine is installed; the run config
8418    names "component:strata-engine" and the engine is looked up when the model is loaded. llama.cpp's source zip is fetched
8419    for gguf-py only (the preparation tools), as setup always did: no git, no compiler."""
8420    from strata_control import engine_component as EC
8421    llama = llama_cpp_if_here()
8422    try:
8423        found = EC.resolve(full=False)
8424        eng, meta = Path(found.root), {"version": found.version, "backend": found.backend, "source": "local"}
8425        ok(f"engine component: {found.version} ({found.platform}-{found.backend}) in {eng}")
8426        if found.backend == "hip" and is_rdna2(gpu) and any(a in RDNA2_ARCHS for a in found.hip_archs):
8427            for line in rdna2_notes(gpu):                       # the RX 6000 package: built, not tested on a real card
8428                say(line)
8429    except EC.EngineMissing as e:
8430        plain = getattr(e, "plain_notice", None) or getattr(e, "driver_notice", None)
8431        if 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.
8435            fail(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")
8438        eng = home() / "engine"
8439        meta = {"version": "99.0.0", "source": "local", "component": "missing"}   # its version is checked when it loads
8440        warn(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")
8442    if vision != "none":
8443        if (eng / VEXE).is_file():
8444            ok(f"image encoder: {eng / VEXE} (carried by the engine component)")
8445            return llama, eng, meta, [], gpu, vision
8446        warn("this engine component has no image encoder (strata-vision): images off for this model")
8447    return 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
8452    once 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
8453    go 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."""
8454    from strata_control import engine_component as EC, shape_engine
8455    shape, title = SHAPE_ENGINE["shape"], SHAPE_ENGINE.get("title")
8456    name = shape_engine.shown(shape, title)                          # what a person reads: the model's title (shape_engine.USE_TITLE)
8457    from strata_cli import update_cmd
8458    source = update_cmd._feed_source(argparse.Namespace(feed=getattr(a, "feed", None)), EC.components_dir())
8459    exe = shape_engine.ensure(shape, source, emit=lambda m: say("  " + m), title=title)
8460    if exe is None:
8461        if os.environ.get("STRATA_ALLOW_NO_ENGINE") == "1":
8462            warn(shape_engine.WORDS["setup_skip"].format(model=name))
8463            return None
8464        fail(shape_engine.WORDS["setup_failed"].format(model=name), shape_engine.WORDS["setup_failed_hint"])
8465    found = shape_engine.find(shape, full=False, title=title)
8466    ok(shape_engine.WORDS["setup_ok"].format(model=name, version=found.version, folder=found.root))
8467    return 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
8472    separate component next to the Strata engine (shape_engine_fetch); the run config names it ("component:strata-q4-lite") and every start looks it up.
8473    Returns what engine_step returns."""
8474    shape = SHAPE_ENGINE["shape"]
8475    llama = llama_cpp_if_here()
8476    found = shape_engine_fetch(a)
8477    if found is None:
8478        return llama, home() / "engine", {"version": "99.0.0", "source": "local", "component": "missing"}, [], gpu, "none"
8479    eng, meta = Path(found.root), {"version": found.version, "backend": found.backend, "source": "local", "shape": shape}
8480    if vision != "none":
8481        if (eng / VEXE).is_file():
8482            ok(f"image encoder: {eng / VEXE} (carried by the engine component)")
8483            return llama, eng, meta, [], gpu, vision
8484        warn("this engine component has no image encoder (strata-vision): images off for this model")
8485    return 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
8490    BUILD.json, its library folders, the GPU (AMD on Windows: as the engine sees it), the image-encoder choice)."""
8491    if SHAPE_ENGINE.get("shape"):
8492        return shape_engine_step(a, gpu, vision)
8493    if CONTROL:
8494        return control_engine_step(gpu, vision)
8495    llama = llama_override()
8496    ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)")
8497    if hip and WIN:                                    # AMD on Windows: the ready-made HIP engine (no compiler)
8498        eng = None if a.build else get_prebuilt_hip(a.prebuilt, gpu)
8499        if eng is None:
8500            fail("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)")
8503        gpu = hip_card(eng, gpu, amd)
8504        a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu
8505    else:
8506        eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision, **({"toolkit": 12} if cuda_tk == 12
8507                                                                                    else {}))
8508    if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local":
8509        pip_cuda_libs(cuda_tk)
8510        if vision != "none" and not (eng / VEXE).exists():
8511            warn("the ready-made engine has no image encoder: compiling it")
8512            eng = None
8513        else:
8514            vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text(encoding="utf-8")), gpu, vision)
8515    if eng is None:
8516        eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk)
8517    meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8"))
8518    if hip and WIN:                                    # the ready-made engine's rocm/bin, first on the engine's PATH
8519        lib_dirs = [str(d) for d in hip_lib_dirs(eng)]
8520    else:
8521        lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk)
8522    return 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)."""
8527    try:
8528        text = subprocess.run([str(eng / EXE), "--families"], capture_output=True, text=True, errors="replace", timeout=60,
8529                              env=engine_env(eng)).stdout      # #2372: with the engine's rocm/bin on PATH
8530    except (OSError, subprocess.SubprocessError):
8531        return {"qwen4exp"}
8532    names = set(text.split())
8533    return 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."""
8543    try:
8544        from strata_control import engine_component as EC
8545        eng = Path(EC.resolve(full=False).root)
8546    except Exception:                                  # noqa: BLE001 - no engine installed (yet): setup checks again when it installs
8547        return None
8548    if not (eng / EXE).is_file():
8549        return None
8550    key = str(eng / EXE)
8551    if key not in _FEED_FAMILIES:
8552        _FEED_FAMILIES[key] = engine_families(eng)
8553    return _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)."""
8558    def __getattr__(self, name):
8559        try:
8560            return globals()[name]
8561        except KeyError:
8562            raise AttributeError(name) from None
8563
8564    def __setattr__(self, name, value):
8565        globals()[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
8570    nothing, and prints nothing, when the feed has no models. See strata_control/feed_models.py."""
8571    from strata_control import feed_models
8572    source = None
8573    if fetch and not acquisition.is_forbidden():
8574        try:
8575            from strata_cli import update_cmd
8576            source = update_cmd._feed_source(argparse.Namespace(feed=feed), home())
8577        except Exception:                              # noqa: BLE001 - no feed address: the cached list only
8578            source = 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)
8580    loaded = feed_models.load(source, fetch=source is not None, say=lambda line: say(f"  {line} ..."))
8581    if loaded.models:
8582        feed_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)."""
8587    return [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
8592    size that does (#5715, strata_control/own_path_fit.py; the smallest when none fits).  A recommendation only: any size can be chosen."""
8593    from strata_control import own_path_fit
8594    return 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."""
8599    from strata_control import own_path_fit
8600    return 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)."""
8605    fits = [m for m, d in fam["models"].items() if ram >= d["ram_gb"]]
8606    return 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
8611    2026-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
8612    VRAM (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
8613    default answer is yes; what is asked for with --vision gpu / cpu is kept, with a note (recommend, never force)."""
8614    asked = a.vision
8615    vram = float(gpu.get("vram_gb", 0.0))
8616    if asked in ("no", "none"):
8617        return "none"
8618    if asked is None:
8619        from strata_control import vision_reader as VR
8620        mode = VR.default_mode(vram)
8621        say()
8622        say(f"  Images: {fam['title']} can also read pictures (screenshots, photos, scanned pages). This adds a "
8623            f"{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)."
8625                if 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)."))
8628        if ask("Do you want images?", ["y", "n"], "y", a.yes) != "y":
8629            return "none"
8630        asked = "yes"
8631    if hip:
8632        return hip_vision(asked, vram)               # settled against the engine's readers in hip_reader() (GPU reader, else CPU)
8633    if asked == "yes":
8634        asked = "gpu" if (vram <= 0 or vram >= IMAGES_GPU_ENCODER_MIN_VRAM_GB) else "cpu"
8635    if asked == "gpu" and 0 < vram < IMAGES_GPU_ENCODER_MIN_VRAM_GB:
8636        warn(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")
8638    return 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
8643    the recurrent state of the GDN layers."""
8644    return 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
8655    solo path's own)."""
8656    size = fam["sha256"][fam["file"].format(q=model)][0] / 1e9
8657    base = size * 0.93 + 4.5       # the routed experts + the dense weights and buffers (the file's 7% beyond them)
8658    return 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
8663    still fits in VRAM with the slots' sessions, up to 4 (a batch reads each expert once for all its rows).  On a card
8664    that does not hold every expert even for one session (the hybrid mode already) it is recommended too, as an offer with
8665    its price said: measured on
8666    an RTX 3060 12 GB, 4 requests together run ~1.5x as fast as one, a request alone ~5% slower, because the slots take
8667    VRAM from the expert cache; up to the count whose sessions leave PARALLEL_SMALL_ROOM_GB of the card."""
8668    slot = own_path_parallel_slot_gb(fam, ctx)
8669    best = max([n for n in (2, 3, 4) if own_path_parallel_fits_all(fam, model, vram_gb, ctx, n)], default=0)
8670    if best:
8671        return best
8672    if own_path_parallel_fits_all(fam, model, vram_gb, ctx, 0):
8673        return 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
8676    room = max(vram_gb - 4.5, 0.0)
8677    return 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
8682    it (kept as asked: recommend, never force)."""
8683    rec = own_path_parallel_recommend(fam, model, vram_gb, ctx)
8684    slot = own_path_parallel_slot_gb(fam, ctx)
8685    if a_parallel is None or a_parallel <= 1:
8686        if not rec:
8687            return ["Several requests at once (opt-in, --parallel N): left at one at a time, because this card cannot spare "
8688                    f"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)."]
8691        if own_path_parallel_fits_all(fam, model, vram_gb, ctx, rec):
8692            return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together instead of one after "
8693                    f"the other (each takes ~{slot:.1f} GB of VRAM at this context; docs/BATCHING.md)."]
8694        return [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: "
8696                f"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)."]
8701    lines = [f"parallel requests: {a_parallel} at once (each takes ~{slot:.1f} GB of VRAM at this context, "
8702             f"{a_parallel * slot:.1f} GB in all)"]
8703    if a_parallel > PARALLEL_MAX:
8704        lines.append(f"the engine runs at most {PARALLEL_MAX} at once; it will use {PARALLEL_MAX}")
8705    if not rec:
8706        lines.append("recommended for this card: one at a time - there is no room for more sessions; kept as you chose")
8707    elif a_parallel > rec:
8708        lines.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")
8710    return 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
8715    engine, the GGUF (pinned revision, size and SHA-256), the tokenizer from the GGUF, the config and the start
8716    script.  The engine places the experts itself (every one in VRAM when they fit, else the most-used ones there and
8717    the rest on the CPU), so there is no pack, profile or RAM budget to choose."""
8718    fam = OWN_PATH_FAMILIES[family]
8719    say()
8720    say(f"  {fam['title']} - {fam['by']}: {fam['about']}")
8721    ok(f"model: {fam['title']}")
8722    if fam.get("license"):
8723        say(f"  Its license: {fam['license']}")
8724    if multi:
8725        warn(f"{fam['title']} runs on one GPU so far: using GPU {gpu.get('index', 0)} ({gpu_name(gpu)}) only")
8726    names = list(fam["models"])
8727    if a.model and a.model not in names:
8728        fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names))
8729    say()
8730    for i, m in enumerate(names, 1):
8731        d = fam["models"][m]
8732        size = fam["sha256"][fam["file"].format(q=m)][0]
8733        from strata_control import fit_label
8734        fit = f"   <- {fit_label.label(size / 1e9, ram, low_ram_vram(gpu))}"        # the file against the RAM and the card's memory together
8735        say(f"  {i}) {m:10s} {d['about']}; download {size / 1e9:.1f} GB{fit}")
8736    rec = own_path_size(fam, ram)
8737    if not a.model:
8738        say(f"  Recommended for {ram:.0f} GB of RAM: {rec} (the largest that fits; any size can be chosen)")
8739    model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)],
8740                                     str(names.index(rec) + 1), a.yes)) - 1]
8741    if ram < fam["models"][model]["ram_gb"]:
8742        confirm_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,
8744                     f"{model} needs about {fam['models'][model]['ram_gb']} GB of RAM",
8745                     f"choose a smaller size, or --model {model} --yes to install it anyway", "  Install it anyway?")
8746        warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose")
8747    ok(f"size: {model}")
8748    tag = fam["tag"] + model
8749    rec_ctx = own_path_context(fam, gpu.get("vram_gb", 0.0), model)
8750    if a.context:
8751        ctx = a.context
8752    else:
8753        ctxs = own_path_contexts()                     # the model's trained length; no rope scaling on this path yet
8754        say()
8755        say("  Context length = how much text the model can see at once. Its cache takes "
8756            f"{fam['kv_bytes_per_token'] * 32768 / 2**30:.1f} GB of VRAM per 32K tokens, room the experts would use:")
8757        for i, c in enumerate(ctxs, 1):
8758            say(f"  {i}) {c // 1024}K tokens" + ("   (recommended for your GPU)" if c == rec_ctx else ""))
8759        ctx = ctxs[int(ask("Context?", [str(i) for i in range(1, len(ctxs) + 1)], str(ctxs.index(rec_ctx) + 1),
8760                           a.yes)) - 1]
8761    if ctx > 262144:
8762        warn(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")
8764    too_big = own_path_context_warning(fam, model, float(gpu.get("vram_gb", 0.0)), ctx)
8765    if too_big:                                        # #5715: said before the start; the choice is kept (recommend, never force)
8766        warn(too_big)
8767    ok(f"context: {ctx} tokens")
8768    vision = own_path_vision(a, fam, gpu, hip)
8769    ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision])
8770    vram_gb = float(gpu.get("vram_gb", 0.0))
8771    par = getattr(a, "parallel", None)
8772    par_said = False
8773    if par is None and not a.yes:                      # offered, with its price; Enter keeps one at a time (never forced)
8774        say()
8775        for line in own_path_parallel_note(None, fam, model, vram_gb, ctx):
8776            say("  " + line)
8777        par_said = True
8778        if own_path_parallel_recommend(fam, model, vram_gb, ctx):
8779            n = 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))
8781            par = n if n > 1 else None
8782    if 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"):
8783        warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} "
8784             "does not use them")
8785    folder = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag
8786    gguf = folder / fam["file"].format(q=model)
8787    size = fam["sha256"][gguf.name][0]
8788    part = gguf.with_name(gguf.name + ".part")
8789    def have(p: Path) -> bool:                         # --gguf-dir: the person's own file has no finish mark; verify_sha256 checks and writes it
8790        return p.exists() and (done(p) or bool(a.gguf_dir))
8791    left = 0 if have(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9
8792    if left and free_gb(folder) < left:
8793        fail(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"))
8794    if left and free_gb(folder) < left + 1:
8795        warn(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
8797    step(3, "Python packages")
8798    pip_install(runtime_packages(),
8799                "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil, textual (the screens)")
8800
8801    step(4, "the Strata engine")
8802    llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision)
8803    reader = None
8804    if hip and vision != "none":
8805        vision, reader = hip_reader(eng, vision, gpu)
8806    elif vision != "none" and not (eng / VEXE).exists():
8807        warn("this engine has no image encoder: images off (run setup again with --build to compile it)")
8808        vision = "none"
8809    if CONTROL and meta.get("component") == "missing":
8810        pass                                           # 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
8812    elif fam["arch"] not in engine_families(eng):
8813        if 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
8814            warn(f"{fam['title']} is {FEED_UNAVAILABLE[family]['reason']}")
8815        else:
8816            fail(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")
8818    ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}")
8819
8820    step(5, f"downloading {fam['title']} {model}")
8821    if have(gguf):
8822        ok(f"{gguf.name} already downloaded")
8823    else:
8824        if a.gguf_dir:
8825            fail(f"{gguf} is missing", f"put {gguf.name} in {folder}, or drop --gguf-dir to download it")
8826        download(fam["hf"] + gguf.name, gguf)
8827    verify_sha256(gguf, *fam["sha256"][gguf.name], own=bool(a.gguf_dir))
8828    ok(f"model file: {gguf}")
8829    mmproj = folder / fam["mmproj"]
8830    if vision != "none":                               # the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked
8831        if 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
8833            if share_sibling_file(mmproj, Path(a.models_dir), mmproj.name, fam["sha256"][mmproj.name][0]):
8834                say(f"  {mmproj.name}: the copy of another {fam['title']} size is used (no download)")
8835        if have(mmproj):
8836            ok(f"{mmproj.name} already downloaded")
8837        else:
8838            if a.gguf_dir:
8839                fail(f"{mmproj} is missing", f"put {mmproj.name} in {folder}, or drop --gguf-dir to download it")
8840            download(fam["mmproj_hf"] + mmproj.name, mmproj, "vision encoder")
8841        verify_sha256(mmproj, *fam["sha256"][mmproj.name], own=bool(a.gguf_dir))
8842        ok(f"vision encoder: {mmproj}")
8843
8844    step(6, "preparing the model for Strata")
8845    data, _ = data_folder_for(a)
8846    pack = data / "packs" / tag.lower()            # only the tokenizer: the engine reads the GGUF itself
8847    if not (pack / "tokenizer" / "vocab.json").exists():
8848        run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(gguf), "--out", str(pack)],
8849            env=dict(os.environ, **gguf_py_env()))
8850    ok(f"tokenizer: {pack / 'tokenizer'}")
8851
8852    step(7, "writing the start script")
8853    args = ["--native", str(gguf), "--max-context", str(ctx), "--prefill", "auto", "--mtp", str(fam["mtp"])]
8854    if a.vram_reserve_mib is not None:             # VRAM left free for other programs: the experts take that much less
8855        vram = gpu.get("vram_gb", 0.0)
8856        if vram > 0:
8857            args += ["--expert-vram", f"{max(vram - 3.0 - a.vram_reserve_mib / 1024, 0):.1f}"]
8858        ok(f"VRAM kept free for other programs: about {a.vram_reserve_mib} MiB (the experts' share is set lower)")
8859    cfg = {"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}
8862    if cuda_tk == 12:
8863        cfg["cuda"] = 12
8864    if hip:
8865        cfg["backend"] = "hip"
8866    if gpu.get("count", 1) > 1 or a.gpu is not None:
8867        cfg["gpu"] = gpu["index"]
8868        cfg["gpus_asked"] = True
8869    if a.host:
8870        cfg["host"] = a.host
8871    if a.api_key:
8872        cfg["api_key"] = a.api_key
8873    if a.browser is not None:
8874        cfg["open_browser"] = a.browser
8875    cfg["args"] = recommend_pool_workers(cfg["args"])   # --pool-workers: this engine path's CPU expert threads too
8876    for line in pool_workers_note(cfg["args"]):
8877        warn(line)
8878    cfg_path = home() / f"strata-{tag.lower()}.json"
8879    if vision != "none":
8880        old_cfg = cfg_path if cfg_path.is_file() else adopted
8881        vt = vision_tokens(getattr(a, "vision_tokens", None), vision, old_cfg)
8882        cfg["args"].append("--vision")
8883        cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(gguf), "gpu": vision == "gpu",
8884                         "max_tokens": vt}          # the text model, opened vocab-only
8885        if reader is not None:                      # AMD: the HIP reader with the CPU reader behind it, or the CPU reader
8886            from strata_control import vision_reader as VR
8887            cfg["vision"] = VR.vision_section(reader, cfg["vision"])
8888        if vision == "cpu":
8889            cfg["vision"]["threads"] = vision_threads()
8890    elif getattr(a, "vision_tokens", None) is not None:
8891        warn("--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
8893    if par is not None:
8894        if par >= 2:
8895            cfg["parallel"] = par
8896            for i, line in enumerate(own_path_parallel_note(par, fam, model, vram_gb, ctx)):
8897                (ok if i == 0 else warn)(line)
8898        else:
8899            cfg["parallel"] = 1
8900            ok("parallel requests: one at a time (--parallel 1)")
8901    write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None, explicit_args(a))
8902    script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False)
8903    ok(f"start script: {script.name}")
8904    say()
8905    say("All set.")
8906    say(f"  API (OpenAI):     http://127.0.0.1:{port}/v1   (any API key; model name: anything)")
8907    say(f"  API (Anthropic):  http://127.0.0.1:{port}/v1/messages")
8908    say(f"  Next time:        just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away")
8909    if vision != "none":
8910        say("  Images:           send them in the chat page, in chat.py (/image <path>) or over the API")
8911    if par is None and not par_said:                   # the opt-in, said once (nothing changes)
8912        for line in own_path_parallel_note(None, fam, model, vram_gb, ctx):
8913            say("  " + line)
8914    if a.no_start:
8915        return 0
8916    return 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
8921    size (pinned revision, size and SHA-256 checked) and, with --vision, the image encoder - and says plainly that
8922    Strata cannot start it yet.  Nothing is configured: no engine, no pack, no start script."""
8923    fam = PREVIEW_FAMILIES[a.family]
8924    names = list(fam["models"])
8925    say()
8926    say(f"  {fam['title']} - {fam['by']}: {fam['about']}")
8927    warn(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")
8929    if a.model and a.model not in names:
8930        fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names))
8931    ram = ram_gb()
8932    for i, m in enumerate(names, 1):
8933        d = fam["models"][m]
8934        size = fam["sha256"][fam["file"].format(q=m)][0]
8935        fit = "" if ram >= d["ram_gb"] else f"   <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"
8936        say(f"  {i}) {m:10s} {d['about']}; download {size / 1e9:.1f} GB{fit}")
8937    if a.check:
8938        return 0
8939    model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], "1", a.yes)) - 1]
8940    say(f"  Its license: {fam['license']}")
8941    want = [fam["file"].format(q=model)]
8942    if a.vision in ("yes", "gpu", "cpu"):
8943        want.append(fam["mmproj"])
8944    folder = Path(a.models_dir) / (fam["tag"] + model)
8945    files = [folder / w for w in want]
8946    left = sum(fam["sha256"][f.name][0] - (f.with_name(f.name + ".part").stat().st_size
8947                                           if f.with_name(f.name + ".part").is_file() else 0)
8948               for f in files if not (f.exists() and done(f))) / 1e9
8949    if left and free_gb(folder) < left:
8950        fail(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"))
8951    if left and free_gb(folder) < left + 1:
8952        warn(f"little free disk space in {folder}: {free_gb(folder):.1f} GB free for about {left:.1f} GB. Setup goes on and should fit")
8953    step(5, f"downloading {fam['title']} {model}")
8954    for f in files:
8955        url = (fam["mmproj_hf"] if f.name == fam["mmproj"] else fam["hf"]) + f.name
8956        download(url, f, "vision encoder" if f.name == fam["mmproj"] else None)
8957        verify_sha256(f, *fam["sha256"][f.name])
8958    ok(f"{fam['title']} {model}: {folder}")
8959    say()
8960    say(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.")
8962    return 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
8967    2026-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)."""
8969    from strata_control import vision_reader as VR
8970    if asked in ("no", "none", "off"):
8971        return "none"
8972    if asked is None and not images_default(model, "qwen", ram):
8973        return "none"
8974    if MODELS.get(model, {}).get("vision") is False:
8975        if asked is not None:
8976            warn(f"images are not available with {model} yet: off")
8977        return "none"
8978    mode = VR.wanted(asked, None, unified=True)
8979    if mode == "cpu":
8980        warn(VR.MAC_CPU_NOTE)
8981    return 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
8986    without it gets pictures off, said once."""
8987    from strata_control import vision_reader as VR
8988    r = VR.choose(eng, vision, windows=False, mac=True)
8989    if r.mode == "none":
8990        warn(r.note or "this engine has no picture reader: pictures off")
8991    return 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
8996    are 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
8997    download); the model's files are never downloaded or changed."""
8998    if not a.gguf_dir:
8999        fail("--prepare-pack needs --gguf-dir, the folder with the model's .gguf files")
9000    family = a.family or "qwen"
9001    if family not in FAMILIES:
9002        fail(f"cannot prepare a pack for the family {family}", "choose qwen, swift, coder or gyro")
9003    fam, model = FAMILIES[family], a.model
9004    if not model:
9005        fail("--prepare-pack needs --model, e.g. --model IQ3_XXS")
9006    models_dir = Path(a.gguf_dir)
9007    files = gguf_dir_shards(models_dir, fam, model)
9008    problem = gguf_dir_problem(models_dir, files[0], fam, model)
9009    if problem:
9010        fail(*problem)
9011    pack = Path(a.prepare_pack)
9012    step(1, "preparing the model for this graphics card")
9013    llama = llama_override()
9014    ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py)")
9015    env = dict(os.environ, **gguf_py_env())
9016    if not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists():
9017        run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(files[0]), "--out", str(pack),
9018             *fam.get("pack_args", [])], env=env)
9019    if not (pack / "tokenizer" / "vocab.json").exists():
9020        fail("the pack was built but has no tokenizer", "run it again; if it repeats, the model files may be damaged")
9021    ok(f"model prepared: {pack}")
9022    return 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."""
9031    return 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)."""
9036    sys.path.insert(0, str(mac_tools_dir()))
9037    import metal_repack as R
9038    for f in files:
9039        rd = R.Reader(f)
9040        rd.f.close()
9041        if any(t["name"] == R.PLE for t in rd.tensors):
9042            return f
9043    fail(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."""
9048    cmd = ["pgrep", "-x", "strata"]
9049    if hasattr(os, "getuid"):
9050        cmd[1:1] = ["-u", str(os.getuid())]
9051    try:
9052        out = subprocess.run(cmd, capture_output=True, text=True, timeout=10).stdout
9053    except (OSError, subprocess.SubprocessError):
9054        return []
9055    return [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)."""
9060    from strata_control import mac_fit as MF
9061    out = native.with_name(native.name + ".experts")
9062    if out.exists() and done(out):
9063        ok(f"the experts' streaming copy: {out.name}")
9064        return
9065    sys.path.insert(0, str(mac_tools_dir()))
9066    import stream_experts as X
9067    need = X.size_bytes(native) / 1e9
9068    free = free_gb(native.parent)
9069    if not os.access(native.parent, os.W_OK):
9070        warn(f"{native.parent} cannot be written: the experts' streaming copy ({need:.0f} GB) is not written; the "
9071             f"engine streams from the model file ({MF.STREAM_COPY_GAIN} slower)")
9072        return
9073    if free < need + MAC_EXPERTS_MARGIN_GB:
9074        warn(f"the experts' streaming copy needs {need:.0f} GB and {MAC_EXPERTS_MARGIN_GB:.0f} GB to spare on the disk "
9075             f"({free:.0f} GB free): not written; the engine streams from the model file ({MF.STREAM_COPY_GAIN} "
9076             f"slower). Free some space and run ./setup.sh --setup again to add it")
9077        return
9078    say(f"  Writing the experts in SSD-read order (one time, {need:.0f} GB; each expert is read with one request) ...")
9079    run([sys.executable, str(mac_tools_dir() / "stream_experts.py"), "--gguf", str(native), "--verify"])
9080    mark(out)
9081    ok(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),
9086    and 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."""
9087    running = mac_engine_pids()
9088    if running:
9089        fail(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")
9091    native.parent.mkdir(parents=True, exist_ok=True)
9092    lock = native.parent / MAC_PREPARE_LOCK
9093    lock.write_text(str(os.getpid()))
9094    return 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
9099    in its shard); the same step as metal/setup_mac.py."""
9100    from strata_control import mac_fit as MF
9101    say(f"  Writing the model's experts and weights into one file for the GPU (one time, "
9102        f"{MF.MAC_MODELS[model]['shard1_gb']:.0f} GB) ...")
9103    run([sys.executable, str(mac_tools_dir() / "metal_repack.py"), "--shard1", str(files[0]), "--out", str(native), "--verify"])
9104    mark(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
9109    downloads 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
9111    metal/setup_mac.py. Which sizes a Mac can run, whether one stays in memory or streams its experts from the SSD, and the
9112    Metal flags of the config are strata_control/mac_fit.py's, the module setup_mac.py and the model list use too."""
9113    from strata_control import mac_fit as MF
9114    say("Strata on a Mac (Apple Silicon, Metal)")
9115    step(1, "checking your Mac")
9116    info = MF.mac_info()
9117    ram = float(info["ram_gb"] or ram_gb())
9118    ok(f"{info['chip']}, {ram:.0f} GB unified memory, macOS {info['macos'] or '?'}")
9119    if info.get("rosetta_python"):
9120        say("  (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)")
9122    problems = MF.mac_problems(info, need_compiler=False)       # the app compiles nothing: no Command Line Tools needed
9123    for p in problems:
9124        warn(p)
9125    data, elsewhere = data_folder_for(a)
9126    roots = [data, *elsewhere]
9127    models_root = Path(a.models_dir) if a.models_dir else data / "models"
9128    free = free_gb(data if data.exists() else home())
9129    ok(f"free disk: {free:.0f} GB at {data}")
9130    if a.check:
9131        return 1 if problems else 0
9132    if problems:
9133        fail(problems[0])
9134
9135    step(2, "your choices")
9136    app_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)
9137    if a.family not in (None, *MF.all_families()):
9138        fail(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")
9140    rec, notes = MF.recommend_model(ram)
9141    if rec not in app_sizes:
9142        rec = "Q2_0"
9143    model = a.model or rec
9144    if model not in app_sizes:
9145        fail(f"{model} is not offered on a Mac in the app", "choose one of: " + ", ".join(app_sizes))
9146    for n in MF.model_note(model, ram):
9147        warn(n)
9148    vision = mac_vision(a.vision, model, ram)
9149    ctx = a.context or MF.recommend_context(ram)
9150    if ctx > MF.TESTED_CONTEXT:
9151        say(f"  context {ctx}: measured on the Mac up to {MF.TESTED_CONTEXT} (needles found at 8K-32K); longer is kept")
9152    ok(f"{model}, context {ctx}")
9153    family = MF.MAC_MODELS[model].get("family", "qwen")
9154    fam = FAMILIES[family]
9155    SHAPE_ENGINE.clear()
9156    if fam.get("shape"):                               # a feed model of its own shape: its own Metal engine component (strata_control/shape_engine.py)
9157        SHAPE_ENGINE["shape"], SHAPE_ENGINE["title"] = fam["shape"], fam.get("title")
9158    tag = fam["tag"] + model
9159    stream = MF.streams(model, ram)
9160
9161    step(4, "the Strata engine (Metal)")
9162    from strata_control import engine_component as EC
9163    llama = llama_cpp_if_here()                        # gguf-py for the preparation tools only (fetched when one runs): no git, no compiler
9164    ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py for the preparation tools)")
9165    reader = None
9166    try:
9167        if SHAPE_ENGINE.get("shape"):
9168            found = shape_engine_fetch(a)
9169            if found is None:
9170                raise EC.EngineMissing("no engine for the model's shape", None)
9171        else:
9172            found = EC.resolve(full=False)
9173        ok(f"engine component: {found.version} ({found.platform}-{found.backend})")
9174        if vision != "none":
9175            reader = mac_reader(Path(found.root), vision)
9176            vision = reader.mode
9177    except EC.EngineMissing as e:
9178        warn(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")
9180        if vision != "none":
9181            warn("pictures are off for now: the picture reader comes with the engine (run setup again once it is installed)")
9182            vision = "none"
9183    else:
9184        if family == "gyro":                           # an engine from before the trellis kernels refuses the file when it loads
9185            try:
9186                has_tq = b"inputs are rotated on the GPU" in Path(found.exe).read_bytes()
9187            except (OSError, AttributeError):
9188                has_tq = True                          # cannot tell: not a reason to hold the install back
9189            if not has_tq:
9190                warn(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")
9192    ok("engine: the engine component (looked up when the model loads)")
9193    ok("images: " + {"none": "off", "gpu": "on (read on the Mac's GPU)", "cpu": "on (read on the CPU)"}[vision])
9194
9195    step(5, f"downloading {fam['title']} {model}")
9196    models_dir = Path(a.gguf_dir) if a.gguf_dir else models_root / tag
9197    files = 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)]
9199    problem = gguf_dir_problem(models_dir, files[0], fam, model) if a.gguf_dir else None
9200    if problem:                                        # files Strata cannot run, or another choice's files
9201        fail(*problem)
9202    mark_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
9203    repacked = 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
9204    native = data / "metal" / f"{tag.lower()}-metal.gguf"
9205    need = 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)
9207    if free_gb(models_dir if models_dir.exists() else data) < need:
9208        warn(f"about {need:.0f} GB are needed on the disk: kept as you chose; it may run out")
9209    if not a.gguf_dir:
9210        models_dir.mkdir(parents=True, exist_ok=True)
9211        missing = [s.name for s in files if not (s.exists() and done(s))]
9212        if missing:
9213            say(f"  The model files go in {models_dir}")
9214        for s in files:
9215            if s.exists() and done(s):
9216                ok(f"{s.name} already downloaded")
9217                continue
9218            download(model_hf(fam, model) + s.name, s)
9219    check_shards(files)
9220    ok("model files present")
9221    mmproj = None
9222    if vision != "none":
9223        mmproj = Path(models_root) / fam["mmproj"]
9224        if not mmproj.exists():                        # an earlier install's copy (the same file for every family)
9225            mmproj = find_in(roots, f"models/{fam['mmproj']}") or mmproj
9226        kind, mmproj = resolve_reader(fam["mmproj"], mmproj, models_root, roots, a.gguf_dir, (ISTA_FILES.get(fam["mmproj"]) or (None,))[0])
9227        if kind == "fetch" and not (mmproj.exists() and done(mmproj)):
9228            download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder")
9229        if fam["mmproj"] in ISTA_FILES and kind != "alt":       # (a verified Unsloth F16 file was checked against its own pin)
9230            verify_sha256(mmproj, *ISTA_FILES[fam["mmproj"]])
9231        ok(f"vision encoder: {mmproj}" + (" (Unsloth's mmproj-F16.gguf, SHA-256 checked)" if kind == "alt" else ""))
9232
9233    step(6, "preparing the model for Strata")
9234    pack = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower()
9235    env = dict(os.environ, **gguf_py_env())
9236    shards = [files[0], files[0]] if family == "gyro" else files      # Gyro: one file, the model and its n-gram table
9237    pack_todo = not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists()
9238    prep_lock = mac_prepare_lock(native) if repacked and (pack_todo or not (native.exists() and done(native))) else None
9239    try:
9240        if repacked:
9241            if not (native.exists() and done(native)):
9242                mac_repack(files, model, native)
9243            shards = [native, mac_ple_shard(files)]
9244        if pack_todo:
9245            run([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)
9247    finally:
9248        if prep_lock is not None:
9249            prep_lock.unlink(missing_ok=True)
9250    ok(f"model prepared: {pack}")
9251    use_mtp = MF.stream_mtp(stream, ram)
9252    no_layer = bool(MF.MAC_MODELS.get(model, {}).get("no_mtp"))
9253    if 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
9254        say("  The model list says this model has no draft layer (MTP), so none is fetched or used.")
9255        use_mtp = False
9256    mtp = (find_in(roots, "mtp/mtp-q2_0.gguf") or data / "mtp" / "mtp-q2_0.gguf").parent
9257    rt = mtp / "rt"
9258    if stream and not use_mtp:
9259        ok("the experts stream from the SSD" + ("" if no_layer else ": no MTP draft layer (one token per step is faster there)"))
9260    elif stream:
9261        ok(f"the experts stream from the SSD; the MTP draft layer stays on, with --spec {MF.STREAM_SPEC}")
9262    if use_mtp and a.mtp == "off" and not (mtp / "mtp-q2_0.gguf").exists():
9263        ok("the draft layer (MTP) is off: its ~5 GB are not downloaded (`--mtp on` fetches it later)")   # round 8, N3
9264        use_mtp = False
9265    elif use_mtp and getattr(a, "drafter", None) == "dflash2" and not (mtp / "mtp-q2_0.gguf").exists():
9266        ok("DFlash2 is the drafter: the MTP draft layer's ~5 GB are not downloaded (choosing the MTP later fetches it once)")
9267        provide_dflash2_vocab(data, a.draft_vocab or "cjk")
9268        use_mtp = False
9269    if use_mtp and not (mtp / "mtp-q2_0.gguf").exists():
9270        say("  The MTP draft layer (speculative decoding) comes from the original Qwen checkpoint: only its ~5 GB of MTP tensors are downloaded.")
9271        if fetch_mtp(mtp, env) is False:                   # offline: the model starts without the layer
9272            use_mtp = False
9273        else:
9274            run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0",
9275                 "--out", str(mtp / "mtp-q2_0.gguf")], env=env)
9276    if use_mtp:
9277        rt.mkdir(parents=True, exist_ok=True)          # the Metal engine reads mtp-q2_0.gguf beside it (no rt pack)
9278        refresh_draft_vocab(rt, a.draft_vocab or "cjk")
9279        ok(f"MTP draft layer: {mtp / 'mtp-q2_0.gguf'}")
9280    if repacked and stream and ram < MF.STREAM_MTP_FROM_GB:
9281        mac_experts_file(shards[0])                    # a small Mac: its misses are many; a big Mac's arena holds most experts
9282
9283    step(7, "writing the run settings")
9284    port = a.port or 8080
9285    profile = ROOT / "data" / "expert-profile.bin"
9286    neutral = getattr(__import__("strata_control.setup_config", fromlist=["x"]), "neutral_profile_if_other_shape", None)       # (f-0213-p8merge: F4, the owner's line)
9287    if 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
9288        sys.path.insert(0, str(ROOT / "tools"))
9289        from gguf_reader import GGUFFile
9290        profile = neutral(profile, shards[0], pack, GGUFFile, say)
9291    args = MF.engine_args(pack, shards, rt, ctx, stream, ram, profile, model)     # Unsloth: --native the repacked file, --ple-gguf the table's shard
9292    cfg = {"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"}}
9295    if a.host:
9296        cfg["host"] = a.host
9297    if a.api_key:
9298        cfg["api_key"] = a.api_key
9299    if a.draft_vocab:
9300        cfg["draft_vocab"] = a.draft_vocab
9301    if a.browser is not None:
9302        cfg["open_browser"] = a.browser
9303    if vision != "none":                               # the Mac's one program reads on the GPU (--gpu) or the CPU (strata_control/vision_reader.py)
9304        from strata_control import vision_reader as VR
9305        cfg["args"].append("--vision")
9306        cfg["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)})
9308        if vision == "cpu":
9309            cfg["vision"]["threads"] = vision_threads()
9310    cfg_path = home() / f"strata-{tag.lower()}.json"
9311    write_setup_config(cfg_path, cfg)
9312    script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False)
9313    ok(f"start script: {script.name}")
9314    say()
9315    say("All set.")
9316    return 0
9317
9318
9319def main() -> int:
9320    try:                                               # the engine programs setup runs start no debugger on a user's machine (strata_control/childenv.py)
9321        from strata_control.childenv import quiet_crash_env
9322        quiet_crash_env()
9323    except Exception:
9324        pass
9325    try:                                               # files made by a run as administrator still belong to the user
9326        from strata_control import private_files as _pf
9327        _pf.adopt_user_defaults()
9328    except Exception:
9329        pass
9330    if sys.platform == "darwin" and not CONTROL:       # a Mac: metal/setup_mac.py (the Metal engine); the app (Control mode) goes on below
9331        return 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
9333                               for i, v in enumerate(sys.argv[1:]) if v == flag or v.startswith(flag + "=")), None)
9334    from strata_control import retired
9335    if retired.is_name(_peek("--family")) or (_peek("--model") and retired.is_name(_peek("--model"))
9336                                              and (not _peek("--family") or retired.is_name(_peek("--family")))):
9337        say("  " + retired.NOT_OFFERED)                # DeepSeek: no longer offered (strata_control/retired.py)
9338        return 2
9339    if (_peek("--family") and _peek("--family") not in {**FAMILIES, **OWN_PATH_FAMILIES}) \
9340            or (_peek("--model") and not _peek("--family") and model_alias(_peek("--model")) not in MODELS
9341                and not any(model_alias(_peek("--model")) in f["models"] for f in OWN_PATH_FAMILIES.values())):
9342        feed_models_setup(_peek("--feed"))             # a name the built-in tables do not know may be a model of the signed feed
9343        if _peek("--family") in FEED_UNAVAILABLE:
9344            fail(f"{FEED_UNAVAILABLE[_peek('--family')]['title']} is {FEED_UNAVAILABLE[_peek('--family')]['reason']}")
9345    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
9346    ap.add_argument("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES),
9347                    help="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)")
9349    ap.add_argument("--model", type=model_alias, choices=list(dict.fromkeys([*MODELS, *(m for f in PREVIEW_FAMILIES.values()
9350                                                                       for m in f["models"])])))
9351    ap.add_argument("--context", type=int)
9352    ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"],
9353                    help="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")
9356    ap.add_argument("--rope-scale", type=float,
9357                    help="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)")
9359    ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4", "fp16"],
9360                    help="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)")
9362    ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"],
9363                    help="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)")
9365    ap.add_argument("--vision-tokens", type=int, metavar="N",
9366                    help="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)
9370    ap.add_argument("--images", choices=["qwen-image", "no"],
9371                    help=argparse.SUPPRESS)
9372    ap.add_argument("--image-quant", choices=["Q4_K_M", "Q6_K", "Q8_0"],
9373                    help=argparse.SUPPRESS)
9374    ap.add_argument("--image-backend", choices=["cuda", "hip", "vulkan", "cpu"],
9375                    help=argparse.SUPPRESS)
9376    ap.add_argument("--image-native", choices=["on", "off"],
9377                    help=argparse.SUPPRESS)
9378    ap.add_argument("--image-noise", choices=["on", "off"],
9379                    help=argparse.SUPPRESS)
9380    ap.add_argument("--image-vae", choices=["on", "off"],
9381                    help=argparse.SUPPRESS)
9382    ap.add_argument("--image-gpu-policy", choices=["auto", "keep", "shrink", "unload"],
9383                    help=argparse.SUPPRESS)
9384    ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF",
9385                    help="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")
9387    ap.add_argument("--port", type=int, help="the server's port (default: the one the install was set up with, 8080 for a new one)")
9388    ap.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)")
9390    ap.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)")
9393    ap.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)")
9395    ap.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")
9398    ap.add_argument("--no-remote-expert-opt", action="store_true",
9399                    help="with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)")
9400    ap.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)")
9402    ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0 or --host ::); "
9403                                      "several keys: key1,key2")
9404    ap.add_argument("--no-browser", dest="browser", action="store_false", default=None,
9405                    help="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)")
9407    ap.add_argument("--browser", dest="browser", action="store_true",
9408                    help="open the chat page again when the model is ready (the default; undoes --no-browser)")
9409    ap.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")
9411    ap.add_argument("--move-data", action="store_true",
9412                    help="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)")
9414    ap.add_argument("--set-default-data-dir", action="store_true",
9415                    help="with --data-dir: remember the new folder as the data folder without moving anything")
9416    ap.add_argument("--models-dir", help="where the GGUF files go (default: <data folder>/models)")
9417    ap.add_argument("--dsv41-package", metavar="FILE", help=argparse.SUPPRESS)      # DeepSeek's: answered with retired.NOT_OFFERED
9418    ap.add_argument("--feed", metavar="URL|DIR",
9419                    help="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)")
9421    ap.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)")
9423    ap.add_argument("--yes", action="store_true", help="accept the recommended answers")
9424    ap.add_argument("--setup", action="store_true", help="install another model or change settings")
9425    ap.add_argument("--no-start", action="store_true", help="install only, do not start the model")
9426    ap.add_argument("--update", action="store_true",
9427                    help="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)")
9429    ap.add_argument("--rollback-engine", action="store_true",
9430                    help="put back the engine an update replaced (kept in engine/.previous), and keep the current one there")
9431    ap.add_argument("--build", action="store_true", help="compile the engine instead of using the ready-made one")
9432    ap.add_argument("--source", choices=SOURCES, default=None,
9433                    help="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)")
9436    ap.add_argument("--prepare-pack", metavar="PACK_DIR",
9437                    help="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")
9439    ap.add_argument("--inspect", nargs="+", metavar=("SOURCE", "VARIANT"),
9440                    help="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")
9442    ap.add_argument("--cuda", choices=["12", "13", "auto"], default=os.environ.get("STRATA_CUDA") or None,
9443                    help="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")
9446    ap.add_argument("--prebuilt", default=os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL),
9447                    help="where the ready-made engine is (a URL folder or a local folder)")
9448    ap.add_argument("--check", action="store_true", help="only check this PC and exit")
9449    ap.add_argument("--calibrate", action="store_true",
9450                    help="tune the engine's settings for this PC (about 15-30 minutes, longer on a slow card), then start the model")
9451    ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS),
9452                    help="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")
9460    ap.add_argument("--low-ram", choices=["auto", "on", "off", "resident", "mmap"], default="auto",
9461                    help="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")
9465    ap.add_argument("--resident-budget-gib", type=float, metavar="N",
9466                    help="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)")
9468    ap.add_argument("--vram-reserve-mib", type=int, metavar="N",
9469                    help="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")
9471    ap.add_argument("--mtp", choices=["on", "off"],
9472                    help="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")
9475    ap.add_argument("--drafter", choices=["mtp", "dflash2"],
9476                    help="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")
9479    ap.add_argument("--parallel", type=int, metavar="N",
9480                    help="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")
9482    ap.add_argument("--replicas", type=int, metavar="N",
9483                    help="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)")
9486    ap.add_argument("--replica-profile", action="store_true", default=False,
9487                    help="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)")
9491    ap.add_argument("--kv-streaming", choices=["auto", "on", "off"], default="auto",
9492                    help="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")
9494    ap.add_argument("--backend", choices=["cuda", "hip", "sycl"],
9495                    help="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)")
9498    ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS)
9499    a = ap.parse_args()
9500    if getattr(a, "gguf_dir", None):                   # the person's own files: their finish marks go to Strata's marks/, never beside them
9501        own_files_in(a.gguf_dir)
9502    if getattr(a, "dsv41_package", None):              # DeepSeek's engine package: no longer offered (strata_control/retired.py)
9503        say("  " + retired.NOT_OFFERED)
9504        return 2
9505    if a.model and a.model not in MODELS and a.family not in PREVIEW_FAMILIES:
9506        ap.error(f"--model {a.model} is a size of " + ", ".join(f"--family {f}" for f, d in PREVIEW_FAMILIES.items()
9507                                                              if a.model in d["models"]))
9508    if a.source:
9509        os.environ["STRATA_SOURCE"] = a.source
9510    if a.prepare_pack:                                 # an Intel Arc card: the model's pack, nothing else (no engine, no download of the model)
9511        return prepare_pack_only(a)
9512    if a.inspect:                                      # headers only: nothing is installed
9513        sys.exit(subprocess.run([sys.executable, str(ROOT / "tools" / "strata_inspect.py"), *a.inspect[:2]]).returncode)
9514    if sys.platform == "darwin" and CONTROL:           # the app on a Mac: model files only; the Metal engine is a component
9515        return mac_control_setup(a)
9516    if a.backend == "sycl":                            # Intel Arc: the app / Terminal's installer mode prepares the files and writes the config; a checkout builds from source
9517        if CONTROL:
9518            return intel_control_setup(a)
9519        return sycl_setup(sys.argv[1:])
9520    if a.resident_budget_gib is not None and not a.resident_budget_gib > 0:
9521        ap.error("--resident-budget-gib takes a number of GiB above 0, e.g. --resident-budget-gib 32")
9522    if a.vision_tokens is not None and a.vision_tokens < 1:
9523        ap.error("--vision-tokens takes a number of image tokens, 1 or more, e.g. --vision-tokens 768")
9524    if a.vram_reserve_mib is not None and a.vram_reserve_mib < 0:
9525        ap.error("--vram-reserve-mib takes a number of MiB, 0 or more, e.g. --vram-reserve-mib 2048")
9526    if a.gpu is not None:                             # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report)
9527        if "," in a.gpu:
9528            a.gpus, a.gpu = a.gpus or a.gpu, None
9529        elif a.gpu.strip().isdigit():
9530            a.gpu = int(a.gpu)
9531        else:
9532            ap.error(f"--gpu takes a GPU number as nvidia-smi numbers them, e.g. --gpu 1 (or --gpus 0,2), not {a.gpu!r}")
9533    a._roles = None
9534    if a.gpu_roles:
9535        if a.gpu is not None or a.gpus:
9536            ap.error("use --gpu-roles (a role for each card) or --gpu / --gpus (which cards), not both")
9537        from strata_control import gpu_roles as GR
9538        try:
9539            named = GR.parse_roles(a.gpu_roles)
9540        except ValueError as e:
9541            ap.error(f"--gpu-roles: {e}")
9542        on = [i for i, r in named.items() if r != "off"]
9543        if not on:
9544            ap.error("--gpu-roles: setup needs at least one card that is Main or Helper")
9545        mains = [i for i, r in named.items() if r == "main"] or [sorted(on)[-1]]
9546        helpers = sorted(i for i in on if i != mains[0])
9547        a._roles_explicit = True
9548        a._roles = {**{i: "off" for i in named}, **{i: "helper" for i in helpers}, mains[0]: "main"}
9549        order = helpers + [mains[0]]
9550        if len(order) > 1:
9551            a.gpus = ",".join(str(i) for i in order)
9552        else:
9553            a.gpu = order[0]
9554    say("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)")
9556    have = installed_configs()
9557    if 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):
9558        from strata_control import retired
9559        for c in retired_configs():                    # DeepSeek: named, left as it is
9560            say("  " + 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).
9564    plain_start = bool(have) and not (a.setup or a.model or a.family or a.check or a.no_start or a.update
9565                                      or a.calibrate or a.rollback_engine or a.data_dir)
9566    models_dir_given = a.models_dir is not None
9567    data, elsewhere = data_folder_in_place() if plain_start else data_folder_for(a)   # the model files
9568    roots = [data, *elsewhere]
9569    if a.models_dir is None:
9570        a.models_dir = str(data / "models")
9571
9572    if a.rollback_engine:                              # #670
9573        return rollback_engine(12 if a.cuda == "12" else 13)
9574
9575    # ---- 0. already installed: just start it
9576    if a.update:                                       # #475: UPDATE.bat / update.sh - never starts the model
9577        return update_install(have, a)
9578    explicit = a.setup or a.model or a.family or a.check or a.no_start
9579    adopted = None                                     # #629: the earlier install this copy is set up like
9580    if not have and not explicit:                      # a new copy of Strata (an update unzipped elsewhere): set it
9581        prev = previous_config(elsewhere, load_settings())   # up like the last one, from the files already here
9582        if prev is not None:
9583            ch = choices_from_config(prev)
9584            if ch["model"]:
9585                say(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.")
9587                a.family, a.model, a.context = ch["family"], ch["model"], a.context or ch["context"]
9588                adopted = prev
9589                a.kv = a.kv or ch["kv"]
9590                a.vision = a.vision or ch["vision"]
9591                a.experimental_speed_projection = a.experimental_speed_projection or ch["esp"]
9592                a.host, a.api_key = a.host or ch["host"], a.api_key or ch["api_key"]
9593                a.port = a.port or ch["port"]
9594                if a.vram_reserve_mib is None:          # #493: an explicit reserve set up before
9595                    a.vram_reserve_mib = ch.get("vram_reserve_mib")
9596                if a.cuda is None and ch.get("cuda") == 12:   # the experimental CUDA 12 engine, as before
9597                    a.cuda = "12"
9598                if isinstance(ch.get("gpu"), list):     # a layer split: set up across the same cards again
9599                    a.gpus = a.gpus or ",".join(str(g) for g in ch["gpu"])
9600                    a.layer_split = a.layer_split or ch.get("layer_split")
9601                else:
9602                    a.gpu = a.gpu if a.gpu is not None else ch.get("gpu")
9603                a.yes = True
9604    global 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
9608    run_gpu = start_gpus(a.gpus) or a.gpu
9609    port = a.port or 8080                              # a new install's port (issue #32: --port for an existing one)
9610    if a.calibrate and (a.setup or a.check or not have):    # #2036: said, not dropped
9611        why = ("--setup" if a.setup else "--check" if a.check else "no model is installed yet")
9612        warn(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]")
9614    if have and a.calibrate and not (a.setup or a.check):
9615        targets = calibration_targets(have, a.model, a.family)
9616        if not targets:                                # #2036: --model names a model that is not installed
9617            names = ", ".join(sorted({choices_from_config(c)["model"] or c.stem for c in have}))
9618            fail(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")
9620        have = targets
9621        engine_update_note()
9622        pick_cfg = have[0]
9623        if len(have) > 1:
9624            say()
9625            for i, c in enumerate(have, 1):
9626                say(f"  {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}")
9627            pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1]
9628        if not calibrate_config(pick_cfg):             # #447: said again where it is not lost above the start
9629            say()
9630            warn("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")
9632        return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,
9633                     keep={"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})
9635    if have and not (a.setup or a.model or a.family or a.check or a.no_start):
9636        engine_update_note()
9637        if len(have) == 1:
9638            return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,
9639                     keep={"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})
9641        say()
9642        for i, c in enumerate(have, 1):
9643            say(f"  {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}")
9644        say(f"  {len(have) + 1}) install another model / change settings")
9645        pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes))
9646        if pick <= len(have):
9647            return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,
9648                     keep={"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})
9650        data, elsewhere = data_folder_for(a)      # "install another model": now the model files are gathered
9651        roots = [data, *elsewhere]
9652        if not models_dir_given:
9653            a.models_dir = str(data / "models")
9654
9655    # ---- 1. the PC
9656    step(1, "checking your PC")
9657    found = gpus()
9658    amd = amd_gpus()
9659    amd_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)
9661    OLD_GPUS = OLD_GPUS or old_gpus_opt_in(found, named_gpus(a.gpu, a.gpus), a.cuda,
9662                                           other=bool(amd_ok) or a.backend == "hip")
9663    if OLD_GPUS and a.backend != "hip":
9664        warn(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)")
9666    nv_ok = any(gpu_problem(g) is None for g in found)
9667    if not nv_ok and not amd_ok and a.backend != "hip" and maxwell_note(found):    # #3218: a warning with the way forward
9668        warn(maxwell_note(found))
9669    hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok))
9670    if 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)
9672        say()
9673        say("  This PC has NVIDIA and AMD cards Strata can use:")
9674        say("  1) NVIDIA: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in found if gpu_problem(g) is None)
9675            + "   (recommended)")
9676        say("  2) AMD: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB{', unified memory' if g.get('uma') else ''})"
9677                               for g in amd_ok)
9678            + f"   ({'the ready-made AMD engine' if WIN else 'compiled here'}, pictures on"
9679              " - docs/AMD_HIP.md)")
9680        say("  One engine drives the cards of one make: a model is never split across NVIDIA and AMD cards, and two models at the same")
9681        say("  time, one on each, is not supported yet.")
9682        from strata_control import gpu_fit
9683        bigger = 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")
9685        if bigger:
9686            say("  " + bigger)
9687        hip = ask("Which cards?", ["1", "2"], "1", a.yes or a.check) == "2"
9688        if a.check and not hip:
9689            say(f"  (the AMD card: {'START-HERE.bat' if WIN else './setup.sh'} --backend hip)")
9690    cuda_tk = 13                                       # NVIDIA: the toolkit of this model's engine (cuda_choice)
9691    if hip:                                            # AMD: compiled here; Windows: ready-made
9692        if WIN and a.gpus:
9693            fail("several AMD cards sharing one model (--gpus) is Linux-only for now", "use one card: --gpu N")
9694        say("  Your AMD GPUs:" if amd else "  No AMD GPU found (" + ("Windows lists no AMD display adapter)." if WIN
9695                                                                   else "the amdgpu driver's KFD topology is empty)."))
9696        for g in amd:
9697            say(f"    GPU {g['index']}: {g['name']}, {amd_mem_text(g)} - " + (amd_problem(g) or "can be used"))
9698        if not WIN:                                    # WSL: the Linux HIP engines hang there; a warning, the run goes on
9699            from strata_control.engine_component import wsl_amd_note
9700            wsl_note = wsl_amd_note("hip", wsl=is_wsl())
9701            if wsl_note:
9702                warn(wsl_note)
9703        usable = [g for g in amd if amd_problem(g) is None]
9704        if not WIN and (amd or amd_pci_devices()):     # a warning only: recommend, never force
9705            acc = amd_device_access_problem()
9706            if acc:
9707                warn(acc)
9708        if not amd and not WIN:                        # the KFD topology is empty: name a Strix Halo the kernel sees
9709            for d in amd_pci_devices():
9710                if d["pci_id"] in STRIX_HALO_PCI_IDS:
9711                    say(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)")
9714        if not usable:
9715            fail("no AMD GPU Strata can use", f"the AMD backend runs on {AMD_CARDS}")
9716        if a.gpus:                                     # a layer split across these cards, the first one the main
9717            chosen = amd_parse_gpus(a.gpus, amd)
9718            gpu = chosen[0]
9719        elif a.gpu is not None:
9720            gpu = next((g for g in usable if g["index"] == a.gpu), None)
9721            if gpu is None:
9722                fail(f"AMD GPU {a.gpu} cannot be used", "use one of: " + ", ".join(f"--gpu {g['index']}" for g in usable))
9723            chosen = [gpu]
9724        else:
9725            gpu = min(usable, key=amd_rank)            # a discrete card before an APU, then the most memory
9726            chosen = [gpu]
9727            if len(usable) > 1 and any(g.get("uma") for g in usable) != all(g.get("uma") for g in usable):
9728                others = [g for g in usable if g is not gpu]
9729                say(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
9733        gpu = {**gpu, "count": len(amd), "archs": sorted({g["arch"] for g in chosen})}
9734        chosen = [gpu] + chosen[1:]
9735        sel = [g["index"] for g in chosen]
9736        multi = sel if len(sel) > 1 else []
9737        a.gpu = gpu["index"] if len(amd) > 1 else a.gpu
9738        if multi:
9739            ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)")
9740        ok(f"GPU: {gpu['name']}, {amd_mem_text(gpu) if gpu.get('uma') else format(gpu['vram_gb'], '.1f') + ' GB VRAM'}, "
9741           f"{gpu['arch']} (AMD: docs/{'STRIX_HALO' if is_strix_halo(gpu) else 'AMD_HIP'}.md)")
9742        if WIN and str(gpu.get("arch") or "").startswith("gfx12"):   # only a pointer; no default changes
9743            say("  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\"")
9745        if gpu.get("uma"):
9746            for line in igpu_notes(gpu, ram_gb()):
9747                (warn if line.startswith("!") else say)(line.lstrip("!"))
9748        for line in unused_apu_notes(chosen, amd, ram_gb()):
9749            (warn if line.startswith("!") else say)(line.lstrip("!"))
9750        for line in rdna2_notes(gpu):
9751            say(line)
9752    else:
9753        if not found:
9754            fail("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 ""))
9757        if len(found) > 1 or gpu_problem(found[0]) is not None:
9758            gpu_table(found)
9759        sel = choose_gpus(a, found)                    # asked when two or more cards can share the model
9760        multi = sel if len(sel) > 1 else []
9761        a.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)
9762        GPU_PICK = a.gpu
9763        gpu = gpu_info(a.gpu)
9764        chosen = [gpu_info(i) for i in sel]
9765        gpu["archs"] = sorted({x["arch"] for x in chosen})  # the engine needs code for every one of them
9766        if multi:
9767            ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)")
9768        ok(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']}")
9770        cuda_tk, why = cuda_choice(gpu["archs"], a.cuda, driver_major(gpu))   # one engine per model: its oldest card decides
9771        if why:
9772            (warn if cuda_tk == 13 or str(a.cuda) == "12" else ok)(f"CUDA {cuda_tk}: {why}")
9773        min_driver = CUDA12_COMPAT_DRIVER if cuda_tk == 12 else MIN_DRIVER
9774        if driver_major(gpu) < min_driver:
9775            fail(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")
9778        if cuda_tk == 12:
9779            cuda12_min_driver(feed=True)                   # the CUDA 12 package's driver floor: the installed package, else the signed feed (#4247)
9780            if note := cuda12_driver_warning(driver_major(gpu)):
9781                warn(note)
9782    if gpu["vram_gb"] < 11:
9783        warn("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")
9785    ram = ram_gb()
9786    cpu, avx2, avx512 = cpu_info()
9787    need = min(d["ram_gb"] for d in MODELS.values() if not d.get("mem_total"))   # Gyro counts VRAM + RAM: not a RAM floor
9788    low_ok = low_ram_fits("IQ1_M", ram, low_ram_vram(gpu)) and a.low_ram != "off"   # the smallest model, mapped
9789    if 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)
9793        confirm_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,
9796                     f"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")
9800        warn(f"going on with {ram:.0f} GB of RAM, as you chose")
9801    ram_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]
9804    pf = page_file_gb()
9805    if pf is not None and pf < 4:
9806        warn(page_file_advice(pf, page_file_setting()))
9807    ok(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)
9809    link = None if hip or gpu.get("uma") else pcie_link(int(gpu.get("index", 0)))
9810    if link is not None:
9811        line, problem = pcie_lines(link)
9812        ok(line)
9813        if problem:
9814            warn(problem)
9815    floor = cpu_floor(avx2)
9816    if floor == "unsupported":
9817        fail("this CPU has neither AVX2 nor SSE4.2; Strata needs at least SSE4.2 (Intel Nehalem, 2008, or newer)")
9818    if 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.
9821        warn("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")
9824    elif 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.
9828        warn(f"this CPU has no AVX2: Strata support for it is EXPERIMENTAL and slow. Setup compiles the engine on this "
9829             f"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")
9832        if hip and WIN:
9833            fail("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")
9835        a.build = True
9836    if a.check:
9837        say()
9838        any_fits = False
9839        for m, d in MODELS.items():
9840            verdict = ("EXPERIMENTAL, " if d.get("experimental") else "") + model_fit_label(m, ram, gpu)
9841            if d.get("budget") and hip and d.get("nvidia_only"):   # #429: not run on AMD yet
9842                verdict += " - NVIDIA only so far, untested on AMD"
9843            if hip and d.get("repo"):                  # the ready-made NVFP4 packs: no AMD kernels at all
9844                verdict = "NVIDIA only (the AMD engine has no NVFP4 kernels)"
9845            else:
9846                any_fits = any_fits or (model_fit_label(m, ram, gpu) == "fits" and not d.get("mem_total"))
9847            say(f"  {m:8s} needs ~{model_files_gb(m):.0f} GB of RAM + VRAM: {verdict}")
9848        if 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.
9851            say(f"\nThis PC cannot run Strata yet: no model size fits {ram:.0f} GB of RAM (the smallest needs about "
9852                f"{need} GB). --model NAME --yes installs one anyway, slowly.")
9853            return 1
9854        say("\nThis PC can run Strata. Run it again without --check to install.")
9855        return 0
9856
9857    # ---- 2. the questions
9858    step(2, "your choices")
9859    if not a.family and not a.yes and FEED_MODELS is None:
9860        feed_models_setup(getattr(a, "feed", None))    # the signed feed's models, listed after the built-in ones (nothing happens when it has none)
9861    fams = menu_families(hip)
9862    feed_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)
9863    fams = [f for f in fams if f not in feed_late]
9864    if a.family:
9865        family = a.family
9866    else:
9867        tier = tier_pick(ram, low_ram_vram(gpu))
9868        rec_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]
9869        for i, f in enumerate(fams, 1):
9870            d = FAMILIES[f]
9871            say(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 ""))
9874        rest = [*(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]
9876        for j, f in enumerate(rest, len(fams) + 1):    # families with an engine path of their own
9877            d = {**FAMILIES, **OWN_PATH_FAMILIES}[f]
9878            say(f"  {j}) {d['title']:20s} {d['by']} - {d['about']}   [new]" + (f"   ({FEED_UNAVAILABLE[f]['reason']})" if f in FEED_UNAVAILABLE else ""))
9879        for u in FEED_UNAVAILABLE.values():            # a feed model this engine does not run: said, never offered (unless the owner's rule allows it, above)
9880            if not u.get("allowed"):
9881                say(f"  -) {u['title']:20s} {u['by']} - {u['reason']}")
9882        allf = fams + rest
9883        if tier_note(ram, low_ram_vram(gpu)) and rec_fam == "swift":
9884            say("  " + tier_note(ram, low_ram_vram(gpu)))
9885        family = allf[int(ask("Which model?", [str(i) for i in range(1, len(allf) + 1)],
9886                              str(allf.index(rec_fam) + 1), a.yes)) - 1]
9887    if family in OWN_PATH_FAMILIES:                    # Qwen3.6: its own engine path, its own steps 2-7
9888        return install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted)
9889    fam = FAMILIES[family]
9890    SHAPE_ENGINE.clear()
9891    if fam.get("shape"):                               # a feed model of its own shape: its own engine component (strata_control/shape_engine.py)
9892        SHAPE_ENGINE["shape"], SHAPE_ENGINE["title"] = fam["shape"], fam.get("title")
9893    if 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
9895        fail(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")
9897    if fam.get("ready") and a.gguf_dir:
9898        warn(f"--gguf-dir does not apply to {fam['title']}: its files are ready-made packs, not GGUF shards")
9899        a.gguf_dir = None
9900    ok(f"model: {fam['title']}")
9901    if fam.get("feed") and fam.get("drafter") == "none" and a.mtp is None:
9902        a.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
9903        a.feed_no_drafter = True                       # and no drafter at its starts either: the run config says "drafting": "off" (setup_config; APP-LIN 0.2.14)
9904        say("  The model list says this model has no draft layer (MTP), so none is fetched or used.")
9905    if fam.get("ready") and nvfp4_cpu_note(avx2, avx512):   # #2347: a note (the AVX2 rows work), not a refusal
9906        warn(nvfp4_cpu_note(avx2, avx512))
9907    if fam.get("license"):
9908        say(f"  Its license: {fam['license']}")
9909    say()
9910    names = [m for m in MODELS if family in MODELS[m].get("families", ("qwen", "swift"))]
9911    names.sort(key=lambda m: bool(MODELS[m].get("experimental")))   # an experimental size last, never the default
9912    if 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
9914        elsewhere_fams = [f for f in FAMILIES if f in MODELS[a.model].get("families", ("qwen", "swift"))]
9915        fail(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) + ")"
9917                if elsewhere_fams else "")
9918             + (f".\n       {SUPPORTED_GGUFS}" if a.gguf_dir else ""))
9919    installed = installed_size(family, names, have)
9920    for i, m in enumerate(names, 1):
9921        d = MODELS[m]
9922        fit = f"   <- {model_fit_label(m, ram, gpu)}"          # "fits" or "may run slower": the weight files against the RAM and the card's memory together
9923        if d.get("mem_total"):             # Gyro: the download includes the n-gram table, the memory figure does not
9924            say(f"  {i}) {m}{size_tag(family, m, installed)} {d['about']}; download {d['download_gb']:.1f} GB "
9925                f"(the n-gram table is in the file), memory {d['ram_gb']} GB{fit}")
9926            continue
9927        if d.get("budget"):
9928            keeps = (f"~{resident_budget_gib(m, ram)} GB" if unsloth_budget(m, ram, gpu, a.resident_budget_gib)
9929                     else "all")
9930            say(f"  {i}) {m}{size_tag(family, m, installed)} {d['about']}; download {d['download_gb']:.0f} GB, keeps {keeps} of its "
9931                f"{d['arena_gb']:.0f} GB of experts in RAM{fit}")
9932            continue
9933        say(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}")
9934    rec = str(names.index(installed or recommended_size(family, names, ram, low_ram_vram(gpu))) + 1)
9935    model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1]
9936    budget, q4_split = None, False
9937    in_budget = bool(MODELS[model].get("budget")) and unsloth_budget(model, ram, gpu, a.resident_budget_gib)
9938    if 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)
9944        if MODELS[model].get("experimental"):
9945            warn(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")
9948        if 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
9951            confirm_risk(f"{model} has not been run on AMD cards yet: its prompt kernels are NVIDIA-only, so on "
9952                         f"{gpu_name(gpu)} long prompts read much more slowly, and it may not work at all",
9953                         bool(a.model), a.yes, f"{model} is NVIDIA-only so far", "choose one of the 2-3-bit models, "
9954                         f"or --model {model} --yes to try it on AMD anyway", "  Try it anyway?")
9955            warn(f"installing {model} on an AMD card, as you chose (please report how it runs)")
9956        if ram < MODELS[model]["ram_gb"] and model_fit_label(model, ram, gpu) != "fits":
9957            have = resident_budget_gib(model, ram)
9958            total = int(MODELS[model]["arena_gb"] / 1.073741824)
9959            confirm_risk(f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB: "
9960                         f"it would keep {have} GiB of its {total} GiB of experts in RAM and read the other "
9961                         f"{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,
9963                         f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB",
9964                         f"choose a smaller size, or --model {model} --yes to install it anyway", "  Install it anyway?")
9965            warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose")
9966        if in_budget:
9967            budget = budget_choice(model, ram, a.resident_budget_gib)
9968            if multi and not unsloth_together(a, model, ram, fallback_card(a, gpu, chosen), chosen):
9969                gpu = fallback_card(a, gpu, chosen)
9970                multi, sel, chosen = [], [gpu["index"]], [gpu]
9971            q4_split = bool(multi) and not resident_split()   # #498: on several GPUs without the RAM budget (#642: kept)
9972            if not q4_split:
9973                ok(f"RAM budget: {budget:g} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD")
9974        else:
9975            ok(f"all {MODELS[model]['arena_gb']:.0f} GB of {model}'s experts in RAM (they and "
9976               f"{UNSLOTH_RESIDENT_BESIDE_GB} GiB more fit this PC's {ram:.0f} GB; --resident-budget-gib N keeps only "
9977               "N GiB of them)")
9978        if a.low_ram not in ("auto", "off"):
9979            warn(f"--low-ram {a.low_ram} does not apply to {model}: it always reads part of its experts from the files")
9980    elif a.resident_budget_gib is not None:
9981        warn(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")
9983    low_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)
9985    if low_ram and multi and not resident_split() and not low_ram_together(a, model, ram, fallback_card(a, gpu, chosen), chosen):
9986        gpu = fallback_card(a, gpu, chosen)
9987        multi, 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)
9990    if MODELS[model].get("mem_total"):
9991        if mem_have(model, ram, gpu["vram_gb"]) < MODELS[model]["ram_gb"]:   # recommend, never force: a warning
9992            warn(f"{model} needs {MODELS[model]['ram_gb']} GB of VRAM and RAM together; this PC has "
9993                 f"{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")
9995    elif not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4:
9996        confirm_paging(model, ram, a.low_ram, a.yes, bool(a.model))
9997    ok(f"size: {model}")
9998    from 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)
10000    if _q4:
10001        warn(_q4)
10002    if MODELS[model].get("license"):                   # the ready-made packs: each size has its own license
10003        say(f"  Its license: {MODELS[model]['license']}")
10004    tag = fam["tag"] + model                           # names of the pack, config and start script
10005    small = min(x["vram_gb"] for x in chosen)         # each card keeps its layers' KV of the whole context
10006    rec_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
10008    rec_ctx = min(rec_ctx, ram_ctx(model, ram, low_ram))
10009    if a.context:
10010        ctx = a.context
10011    else:
10012        say()
10013        say("  Context length = how much text the model can see at once (your chat, files, tool output).")
10014        say("  Longer needs more VRAM for it, so fewer experts fit on the GPU:")
10015        for i, c in enumerate(CONTEXTS, 1):
10016            need_c = ctx_ram_need(model, c, low_ram)
10017            note = ("   (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)"
10020                    if c > 131072 and need_c is not None and need_c > ram else "")
10021            say(f"  {i}) {c // 1024}K tokens{note}")
10022        ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(CONTEXTS) + 1)],
10023                               str(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.
10026    need_gb = ctx_ram_need(model, ctx, low_ram)
10027    if need_gb is not None and ram < need_gb and ctx > 131072:
10028        warn(f"{ctx // 1024}K with {model} needs ~{need_gb:.0f} GB of RAM by setup's estimate "
10029             f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest); this PC has "
10030             f"{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.")
10032    scaling = a.rope_scaling
10033    if 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.
10036        say()
10037        say(f"  A {ctx // 1024}K context runs the model past its trained 262,144 positions: the rotary angles")
10038        say("  get rescaled (llama.cpp's RoPE extension). yarn keeps the trained angles on the high-frequency")
10039        say("  pairs and corrects the magnitudes; linear shrinks every angle. Override any time with")
10040        say("  --rope-scaling.")
10041        scaling = ask("RoPE extension method?", ["yarn", "linear"], "yarn", a.yes)
10042    try:
10043        scaling, rope_scale = resolve_rope(ctx, scaling, a.rope_scale)
10044    except ValueError as e:
10045        fail(str(e))
10046    if scaling is not None:
10047        origin = ("final context / trained 262144; override with --rope-scale" if a.rope_scale is None
10048                  else "as requested")
10049        ok(f"rope scaling: {scaling}, factor {rope_scale:g} ({origin})")
10050    ok(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)
10052    kv = "fp16" if ctx <= 8192 else (a.kv or "int8")
10053    if ctx > 8192 and not a.kv and not a.yes:
10054        say()
10055        say("  KV cache precision (the model's memory of the conversation):")
10056        say("  1) 8-bit   (recommended: what every published number was measured with)")
10057        say("  2) 4-bit   half the memory (about 4% faster at 128K), but measurably less precise on long")
10058        say("             documents; long-context lookups (needle tests) still pass")
10059        kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1]
10060    if ctx > 8192:
10061        ok(f"KV cache: {KV_WORDS.get(kv, kv)}")
10062    if MODELS[model].get("vision", fam.get("vision")) is False:     # UD-IQ4_XS: images, unlike UD-Q4_K_XL
10063        vision = "none"
10064        if a.vision not in (None, "no", "none"):
10065            warn(f"images are not available with {model} yet: off")
10066    elif hip:
10067        # Unsloth's files on AMD: pictures on by default, the reader by the 24 GB rule (hip_vision; docs/QUANTS.md)
10068        vision = hip_vision(a.vision if a.vision is not None or not images_default(model, family, ram, gpu)
10069                            else "yes", float((gpu or {}).get("vram_gb") or 0.0))
10070    elif a.vision:
10071        vision = flash_vision_encoder(a.vision, gpu) if a.vision != "no" else "none"
10072        vision = "none" if vision in ("no", "none") else vision
10073    else:
10074        small = 0 < float(gpu.get("vram_gb") or 0.0) < IMAGES_GPU_ENCODER_MIN_VRAM_GB
10075        say()
10076        say("  Images: the model can also read pictures (screenshots, photos, scanned pages). This adds a 0.9 GB")
10077        if small:
10078            say("  download. On a card under 24 GB the encoder runs on the CPU (a few seconds per picture, nothing taken")
10079            say("  from the GPU, pictures read at up to 300 tokens; --vision-tokens 1024 for more detail): the GPU")
10080            say("  encoder keeps ~1.4 GB of VRAM free, which costs 3-5% of text speed on 16 GB cards (measured) and")
10081            say("  more on some PCs. --vision gpu if you want pictures in under a second.")
10082        else:
10083            say("  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)
10085        default = "y" if images_default(model, family, ram, gpu) else "n"
10086        vision = flash_vision_encoder("yes", gpu) if ask("Do you want images?", ["y", "n"], default, a.yes) == "y" else "none"
10087    ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision])
10088    if vision != "none" and MODELS[model].get("vision_untested"):
10089        warn(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.
10096    resident = False
10097    if low_ram and not fam.get("ready"):               # NVFP4's packs: the RAM-budget mode instead (step 7)
10098        arena = MODELS[model]["arena_gb"]
10099        vram = low_ram_vram(gpu) - (VISION[vision]["reserve_mib"] / 1024 if vision != "none" else 0)
10100        with_mtp = a.mtp != "off"                       # the draft layer's ~1 GB comes out of the expert cache
10101        share = low_ram_gpu_share(model, vram, ctx, kv, with_mtp)
10102        rest = arena - low_ram_gpu_gb(model, vram, ctx, kv, with_mtp)
10103        resident = a.low_ram == "resident" or (a.low_ram != "mmap" and low_ram_resident(model, ram, vram, ctx, kv, with_mtp))
10104        if multi:      # every chosen card's share (the image encoder on the main one); #364 #384: the mapped variant
10105            held = min(arena, low_ram_gpu_gb(model, vram, ctx, kv, with_mtp) +
10106                       sum(low_ram_gpu_gb(model, low_ram_vram(x), ctx, kv, with_mtp) for x in chosen[1:]))
10107            share, 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
10109            resident = resident_split() and (a.low_ram == "resident" or
10110                                             (a.low_ram != "mmap" and ram >= rest + LOW_RAM_HEADROOM_GB))
10111            if resident:
10112                ok(f"low-RAM mode on {len(chosen)} GPUs: they hold ~{100 * share:.0f}% of {model}'s experts "
10113                   f"({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")
10115            else:
10116                ok(f"low-RAM mode on {len(chosen)} GPUs: {model}'s experts ({arena:.0f} GB) are read from the model "
10117                   f"folder through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPUs hold "
10118                   f"~{100 * share:.0f}% of them")
10119                if share < 0.6:
10120                    warn("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)")
10122        elif resident:
10123            ok(f"low-RAM mode: the GPU holds ~{100 * share:.0f}% of {model}'s experts ({arena:.0f} GB) and the other "
10124               f"~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy in the model folder")
10125        else:
10126            ok(f"low-RAM mode: {model}'s experts ({arena:.0f} GB) are read from the model folder through the OS file "
10127               f"cache instead of a copy in RAM ({ram:.0f} GB); the GPU holds ~{100 * share:.0f}% of them")
10128            if share < 0.6:
10129                warn("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
10133    esp = None
10134    esp_choice = (a.experimental_speed_projection or "").strip()
10135    if family in ("qwen", "coder"):                   # the Coder: the same model's residual stream
10136        if not esp_choice:
10137            say()
10138            say("  EXPERIMENTAL - speed projection: a small control vector applied while the model runs (layers 4-44).")
10139            say("  It changes how the model answers: its package describes it as a refusal-direction projection (the")
10140            say("  model declines far fewer requests). Off unless you choose it; when on, the web app can switch it off")
10141            say("  per chat. Details: data/experimental-speed-projection/README.md")
10142            esp_choice = "on" if ask("Turn on the experimental speed projection?", ["y", "n"], "n", a.yes) == "y" else "off"
10143        if esp_choice.lower() not in ("off", "no", "n", "0"):
10144            esp = ESP_VECTOR if esp_choice.lower() in ("on", "yes", "y", "1") else Path(esp_choice).expanduser().resolve()
10145            if not esp.is_file():
10146                fail(f"the experimental speed projection's vector is missing: {esp}")
10147        ok("experimental speed projection: " + ("ON (experimental)" if esp else "off"))
10148    elif esp_choice.lower() not in ("", "off", "no", "n", "0"):
10149        warn("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off"
10150             if family == "swift" else f"the experimental speed projection is not tested with {model}: left off")
10151    ready = bool(fam.get("ready"))                     # NVFP4: ready-made packs (NVFP4_REPOS), no GGUF shards
10152    if ready:
10153        models_dir = Path(a.models_dir)
10154        for r in elsewhere:                            # already downloaded and checked in a Strata folder elsewhere
10155            if all(ready_verified(ready_where(r / "models", f), f[5]) for f in ready_needed(model, r / "models")):
10156                models_dir = r / "models"
10157                ok(f"model files found in {models_dir}")
10158                break
10159        shards = [ready_where(models_dir, f) for f in ready_files(model)]
10160    else:
10161        models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag
10162        shards = 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)]
10164    problem = gguf_dir_problem(models_dir, shards[0], fam, model) if a.gguf_dir else None
10165    if problem:                                        # #444: files Strata cannot run, or another choice's files
10166        fail(*problem)
10167    if not ready and not a.gguf_dir and not all(sh.exists() and done(sh) for sh in shards):
10168        for r in elsewhere:                            # already downloaded in a Strata folder on another drive
10169            cand = [r / "models" / tag / sh.name for sh in shards]
10170            if all(c.exists() and done(c) for c in cand):
10171                models_dir, shards = cand[0].parent, cand
10172                ok(f"model files found in {models_dir}")
10173                break
10174    mark_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
10175    have_model = all(ready_verified(ready_where(models_dir, f), f[5]) for f in ready_needed(model, models_dir)) if ready else \
10176        all(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
10179    on_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
10180    to_fetch = 0 if a.gguf_dir or have_model else max(MODELS[model]["download_gb"] - on_disk, 0)
10181    if ready and not have_model and MODELS[model].get("prepare") and prepared_done(model, models_dir):
10182        to_fetch = sum(f[4] for f in ready_needed(model, models_dir)
10183                       if 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
10186    pack_now = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower()
10187    pack_bin = ready or ((pack_now / "experts.bin").exists() and (pack_now / "index.txt").exists())   # ready: in the download
10188    mtp_have = find_in(roots, "mtp/rt/experts.bin") is not None
10189    q2_avx = model == "Q2_0" and avx512 and family == "qwen"
10190    prep_gb = MODELS[model].get("prepare_gb", 0.0) if ready and MODELS[model].get("prepare") and \
10191        not prepared_done(model, models_dir) else 0.0
10192    margin = 2 if mtp_have else 8                      # working room: a guess, not bytes that will be written
10193    mtp_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)
10194    copy_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)
10195    real = 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
10197    need = real + margin
10198    free_now = free_gb(models_dir)
10199    problem = 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 ""))
10201    if problem:
10202        fail(*problem)
10203    if free_now < need:
10204        warn(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
10208    step(3, "Python packages")
10209    pip_install(runtime_packages(),
10210                "numpy, jinja2, regex, pyyaml, tqdm, requests, pillow, psutil, textual (the screens)")
10211
10212    # ---- 4. the engine
10213    step(4, "the Strata engine")
10214    llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision)
10215    reader = None
10216    if hip and vision != "none":                       # AMD: the engine folder's reader (GPU, else CPU), settled now the engine is known
10217        vision, reader = hip_reader(eng, vision, gpu)
10218    if (ready or family == "gyro") and meta.get("source") != "local" and \
10219            tuple(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
10221        warn(f"the ready-made engine {meta.get('version')} has no {'NVFP4' if ready else 'Gyro'} experts yet: compiling "
10222             "the engine from this source")
10223        eng = build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk)
10224        meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8"))
10225        lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk)
10226    engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())
10227    need_engine = MODELS[model].get("engine", UNSLOTH_ENGINE)
10228    # checked before the 94-188 GB download
10229    if (MODELS[model].get("budget") or family == "gyro") and engine_ver < need_engine:
10230        fail(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")
10232    ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}")
10233
10234    # ---- 5. the model files
10235    step(5, f"downloading {fam['title']} {model}")
10236    if ready:                                          # pinned files of the pack's repository, each SHA-256-checked
10237        say(f"  The model files go in {models_dir / MODELS[model]['repo'].replace('/', '--')}")
10238        if model_source() == "modelscope":
10239            warn("these packs are on Hugging Face only: downloading them from " + hf_endpoint())
10240        ready_fetch(model, models_dir)
10241    elif not a.gguf_dir:
10242        missing = [s.name for s in shards if not (s.exists() and done(s))]
10243        if missing:                                    # #495: files downloaded by hand go here, or --gguf-dir
10244            say(f"  The model files go in {models_dir}")
10245            say(f"  Files you already have: put them here with their original names ({', '.join(missing)}), or use "
10246                "--gguf-dir <their folder>.")
10247            if model_source() == "modelscope":
10248                say(f"  Downloading from ModelScope ({ms_endpoint()}); --source huggingface downloads from Hugging Face")
10249                warn("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")
10252            elif hf_endpoint() != HF_DEFAULT:
10253                say(f"  Downloading from {hf_endpoint()} (HF_ENDPOINT)")
10254        for s in shards:
10255            if s.exists() and done(s):
10256                ok(f"{s.name} already downloaded")
10257                continue
10258            # the original's shard 2 is the same file for all its sizes and the Coder: reuse one that is already here
10259            other = [p for p in Path(a.models_dir).glob("*/Qwen3.8-Flash-Next-GSQ-RCO-*-00002-of-00002.gguf") if done(p)]
10260            if family in ("qwen", "coder") and s.name.endswith("00002-of-00002.gguf") and other and not s.exists():
10261                try:
10262                    os.link(other[0], s)
10263                    mark(s)
10264                    ok(f"{s.name} shared with {other[0].parent.name} (identical file)")
10265                    continue
10266                except OSError:
10267                    pass
10268            download(model_hf(fam, model) + s.name, s)
10269    if not ready:
10270        check_shards(shards)
10271    for s in ([] if ready else shards):                # the Unsloth files: pinned sizes and SHA-256
10272        if s.name in fam.get("sha256", {}):
10273            verify_sha256(s, *fam_pin(fam, s), own=bool(a.gguf_dir))
10274    ok("model files present")
10275    mmproj = Path(a.models_dir) / fam.get("mmproj", MMPROJ)
10276    if not mmproj.exists():                            # an earlier install's copy (the same file for every family)
10277        mmproj = find_in(roots, f"models/{fam.get('mmproj', MMPROJ)}") or mmproj      # a feed model without a picture reader has no fam["mmproj"]
10278    if 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
10281        kind, 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])
10283        if kind == "fetch":
10284            download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder")
10285        if fam.get("mmproj_sha256") and kind != "alt":   # the NVFP4 family pins it by size and SHA-256 too
10286            verify_sha256(mmproj, *fam["mmproj_sha256"])
10287        ok(f"vision encoder: {mmproj}" + (" (Unsloth's mmproj-F16.gguf, SHA-256 checked)" if kind == "alt" else ""))
10288        if vision == "cpu" and "BF16" in mmproj.name:       # a tip only (recommend, never force; #625)
10289            say("       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
10293    step(6, "preparing the model for Strata")
10294    pack = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower()
10295    env = dict(os.environ, **gguf_py_env())
10296    prepared = bool(ready and MODELS[model].get("prepare"))
10297    if prepared and not prepared_done(model, models_dir):
10298        say("  NVIDIA's checkpoint is turned into a Strata pack on this PC (once; 20-40 minutes, reads the 102 GB, writes about")
10299        say(f"  {MODELS[model]['prepare_gb']:.0f} GB). Nothing of NVIDIA's weights leaves this PC.")
10300        ensure_nvfp4_local_packages()
10301        run([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)
10304        ok("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, ""))))
10306    if ready:                                          # the downloaded pack folder is the pack, experts.bin included
10307        pack = ready_paths(model, models_dir)["pack"]
10308    elif 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
10310        if not (pack / "index.txt").exists() or not (pack / "experts.bin").exists():   # index.txt is written last
10311            say("  Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...")
10312            run([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
10314            run([sys.executable, str(ROOT / "tools" / "pack_index.py"), "--pack", str(pack)], env=env)
10315        if not (pack / "tokenizer" / "vocab.json").exists():
10316            run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(shards[0]),
10317                 "--out", str(pack)], env=env)   # writes <pack>/tokenizer/
10318    elif 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)
10321        run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack),
10322             *fam.get("pack_args", [])], env=env)
10323    if low_ram and not ready and not (pack / "experts.bin").exists():
10324        say(f"  Writing the experts into one file for the low-RAM mode (one time, {MODELS[model]['arena_gb']:.0f} GB) ...")
10325        run([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
10327    ok(f"model prepared: {pack}")
10328    mtp = 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
10330    rt = mtp / "rt"
10331    corrupt = (rt / "experts.bin").exists() and not prepared and mtp_corrupt(mtp, env)
10332    if corrupt:
10333        warn("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")
10335    if a.mtp == "off" and not (rt / "experts.bin").exists():
10336        ok("the draft layer (MTP) is off: its ~5 GB are not downloaded (`--mtp on` fetches it later)")   # round 8, N3
10337    elif getattr(a, "drafter", None) == "dflash2" and not (rt / "experts.bin").exists():
10338        ok("DFlash2 is the drafter: the MTP draft layer's ~5 GB are not downloaded (choosing the MTP later fetches it once)")
10339        provide_dflash2_vocab(data, a.draft_vocab or saved_draft_vocab(home() / f"strata-{tag.lower()}.json") or "cjk")
10340    elif corrupt or not (rt / "experts.bin").exists():
10341        say("  The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:")
10342        say("  only its ~5 GB of MTP tensors are downloaded.")
10343        if fetch_mtp(mtp, env) is not False:               # (False: offline, nothing to pack)
10344            run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0",
10345                 "--out", str(mtp / "mtp-q2_0.gguf")], env=env)
10346            run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)],
10347                env=env)
10348    # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en)
10349    draft_vocab = a.draft_vocab or saved_draft_vocab(home() / f"strata-{tag.lower()}.json")
10350    if (rt / "experts.bin").exists():
10351        refresh_draft_vocab(rt, draft_vocab or "cjk")
10352        ok(f"MTP draft layer: {rt}")
10353    refresh_dflash2_vocab(data, draft_vocab or "cjk")        # an existing DFlash2 copy follows the choice too
10354    for line in draft_vocab_note(gpu.get("vram_gb", 0.0), draft_vocab):   # #474: a recommendation, nothing changes
10355        say("  " + line)
10356
10357    # ---- 7. the start script
10358    step(7, "writing the start script")
10359    sys.path.insert(0, str(ROOT / "tools"))
10360    from gguf_reader import GGUFFile                   # the PLE table's shard: shard 2 (original) or 1 (Swift)
10361    if ready:   # the dense GGUF as --native and --native-dense-gguf (--native alone would look for a second shard),
10362        rp = ready_paths(model, models_dir)            # the FP8 n-gram table, the BF16 token embedding
10363        ple = rp["ple"]
10364        model_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 [])]
10366    else:
10367        ple = next((s for s in shards if any(t.name == "per_layer_token_embd.weight" for t in GGUFFile(s).tensors)), None)
10368        if ple is None:
10369            fail("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)
10371        model_args = ["--pack", str(pack), "--native", str(shards[0]),
10372                      *(["--ple-gguf", str(ple)] if len(shards) <= 2 else [])]
10373    from 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(
10375        a=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__])
10376    cfg, cfg_path, cal, args, ctx, kv, resident = (_built.cfg, _built.cfg_path, _built.cal, _built.args, _built.ctx, _built.kv, _built.resident)
10377    write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None, explicit_args(a),
10378                       after_carry=(lambda c: uma_cache_guard(c, model, gpu)) if gpu.get("uma") else None)
10379    script = 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
10381    if 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":
10384        tuned = calibrate_config(cfg_path)
10385    else:
10386        tuned = None                                   # not asked for: nothing to repeat below
10387    ok(f"start script: {script.name}")
10388
10389    say()
10390    say("All set.")
10391    say(f"  API (OpenAI):     http://127.0.0.1:{port}/v1   (any API key; model name: anything)")
10392    say(f"  API (Anthropic):  http://127.0.0.1:{port}/v1/messages")
10393    if a.host and a.host not in ("127.0.0.1", "localhost"):
10394        say(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"))
10396    say(f"  Next time:        just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away")
10397    if vision != "none":
10398        say("  Images:           send them in the chat page, in chat.py (/image <path>) or over the API")
10399    if cfg.get("images"):
10400        say(f"  Image generation: POST http://127.0.0.1:{port}/v1/images/generations (OpenAI's images API)")
10401    if a.parallel is None:                             # #465: the opt-in, said once (nothing changes)
10402        for 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"]):
10404            say("  " + line)
10405    if tuned is False:                                 # #447: a failed tuning is repeated here, not only above
10406        say("  Tuning:           FAILED (the reason is above): the default settings stay - "
10407            f"{'START-HERE.bat' if WIN else './setup.sh'} --calibrate tries again")
10408    if a.no_start:
10409        return 0
10410    # offered only when someone answers (--yes asks nothing), default no; the benchmark starts its own server and stops it
10411    if 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 "
10413            f"(later: {'BENCH.bat' if WIN else './bench.sh'})", ["y", "n"], "n", a.yes) == "y":
10414        subprocess.call([sys.executable, str(ROOT / "tools" / "strata_bench.py"), "--config", str(cfg_path), "--port", str(port)])
10415    return start(cfg_path, port)
10416
10417
10418if __name__ == "__main__":
10419    try:
10420        sys.exit(main())
10421    except acquisition.AcquisitionRefused as e:         # a start that would have installed something: said, not done
10422        say(f"\n  [X]  {e}")
10423        sys.exit(e.exit_code)
10424    except KeyboardInterrupt:
10425        say("\nstopped.")
10426        sys.exit(1)
10427