From ec59208d87d29511fd23ef2adbc264e5abf0adb6 Mon Sep 17 00:00:00 2001 From: Robert Karl Date: Sat, 17 Oct 2026 20:38:18 -0700 Subject: [PATCH] Remove the installers and downloaders (rule 1: network at setup, build or start) setup.py and its launchers, the Docker and Nix files, requirements.txt, the MCP installer, the image-generation installer, the AMD Windows packager and their tests. Nothing the engines read or the build uses lived in these files; the engine's runtime data (data/, tools/hip/*.txt) stays. tools/requirements.txt lists the two packages the offline pack tools need. UPSTREAM.md records the cut. Verified: no file under CMakeLists.txt, cmake/, tools/vision or the engine sources references a removed path (grep); git status clean after the commit. --- .dockerignore | 27 - Dockerfile | 119 - SETUP.bat | 3 - START-HERE.bat | 52 - UPDATE.bat | 81 - UPSTREAM.md | 13 +- conftest.py | 9 - docker-entrypoint.sh | 106 - flake.lock | 27 - flake.nix | 49 - requirements.txt | 23 - setup.py | 8223 ----------------- setup.sh | 69 - tools/hip/package_windows.py | 173 - tools/image/install.py | 101 - tools/image/qimage.py | 203 - tools/image/sdcpp_native/apply.py | 75 - tools/image/sdcpp_native/qi21-native.cu | 679 -- .../sdcpp_native/qwen_image_2_1_native.hpp | 601 -- tools/requirements.txt | 3 + tools/strata_mcp.py | 1885 ---- tools/test_docker_entrypoint.py | 117 - tools/test_poly_prebuilt.py | 174 - tools/test_qimage.py | 202 - tools/test_setup_amd.py | 578 -- tools/test_setup_bench_tips.py | 99 - tools/test_setup_choices.py | 663 -- tools/test_setup_compute_mode.py | 36 - tools/test_setup_config.py | 277 - tools/test_setup_configs.py | 63 - tools/test_setup_cuda_repo.py | 115 - tools/test_setup_draft_vocab.py | 153 - tools/test_setup_engine_hash.py | 390 - tools/test_setup_engine_keep.py | 105 - tools/test_setup_gguf_models.py | 290 - tools/test_setup_glm.py | 452 - tools/test_setup_golden.json | 1129 --- tools/test_setup_golden.py | 214 - tools/test_setup_hotfix_tag.py | 53 - tools/test_setup_hybrid.py | 117 - tools/test_setup_lfm.py | 126 - tools/test_setup_llama_archive.py | 173 - tools/test_setup_lowram.py | 84 - tools/test_setup_mac.py | 281 - tools/test_setup_menu.py | 210 - tools/test_setup_modelscope.py | 139 - tools/test_setup_nvfp4.py | 180 - tools/test_setup_oldcpu.py | 95 - tools/test_setup_older_gpus.py | 287 - tools/test_setup_page_file.py | 158 - tools/test_setup_parallel.py | 63 - tools/test_setup_pcie.py | 44 - tools/test_setup_pins.py | 360 - tools/test_setup_prompts.py | 149 - tools/test_setup_qwen36.py | 307 - tools/test_setup_remote_opt.py | 98 - tools/test_setup_rerun_size.py | 104 - tools/test_setup_risk.py | 514 -- tools/test_setup_rocm_indexes.json | 1159 --- tools/test_setup_rocm_pins.py | 168 - tools/test_setup_rope.py | 121 - tools/test_setup_shard_check.py | 54 - tools/test_setup_small_card.py | 131 - tools/test_setup_stale_stamp.py | 153 - tools/test_setup_start_gpus_amd.py | 40 - tools/test_setup_strix_halo.py | 561 -- tools/test_setup_sycl.py | 228 - tools/test_setup_unsloth.py | 860 -- tools/test_setup_update.py | 208 - tools/test_setup_update_gpu.py | 53 - tools/test_strata_mcp.py | 671 -- update.sh | 63 - 72 files changed, 15 insertions(+), 25575 deletions(-) delete mode 100644 .dockerignore delete mode 100644 Dockerfile delete mode 100644 SETUP.bat delete mode 100644 START-HERE.bat delete mode 100644 UPDATE.bat delete mode 100644 conftest.py delete mode 100755 docker-entrypoint.sh delete mode 100644 flake.lock delete mode 100644 flake.nix delete mode 100644 requirements.txt delete mode 100644 setup.py delete mode 100755 setup.sh delete mode 100644 tools/hip/package_windows.py delete mode 100644 tools/image/install.py delete mode 100644 tools/image/qimage.py delete mode 100644 tools/image/sdcpp_native/apply.py delete mode 100644 tools/image/sdcpp_native/qi21-native.cu delete mode 100644 tools/image/sdcpp_native/qwen_image_2_1_native.hpp create mode 100644 tools/requirements.txt delete mode 100644 tools/strata_mcp.py delete mode 100644 tools/test_docker_entrypoint.py delete mode 100644 tools/test_poly_prebuilt.py delete mode 100644 tools/test_qimage.py delete mode 100644 tools/test_setup_amd.py delete mode 100644 tools/test_setup_bench_tips.py delete mode 100644 tools/test_setup_choices.py delete mode 100644 tools/test_setup_compute_mode.py delete mode 100644 tools/test_setup_config.py delete mode 100644 tools/test_setup_configs.py delete mode 100644 tools/test_setup_cuda_repo.py delete mode 100644 tools/test_setup_draft_vocab.py delete mode 100644 tools/test_setup_engine_hash.py delete mode 100644 tools/test_setup_engine_keep.py delete mode 100644 tools/test_setup_gguf_models.py delete mode 100644 tools/test_setup_glm.py delete mode 100644 tools/test_setup_golden.json delete mode 100644 tools/test_setup_golden.py delete mode 100644 tools/test_setup_hotfix_tag.py delete mode 100644 tools/test_setup_hybrid.py delete mode 100644 tools/test_setup_lfm.py delete mode 100644 tools/test_setup_llama_archive.py delete mode 100644 tools/test_setup_lowram.py delete mode 100644 tools/test_setup_mac.py delete mode 100644 tools/test_setup_menu.py delete mode 100644 tools/test_setup_modelscope.py delete mode 100644 tools/test_setup_nvfp4.py delete mode 100644 tools/test_setup_oldcpu.py delete mode 100644 tools/test_setup_older_gpus.py delete mode 100644 tools/test_setup_page_file.py delete mode 100644 tools/test_setup_parallel.py delete mode 100644 tools/test_setup_pcie.py delete mode 100644 tools/test_setup_pins.py delete mode 100644 tools/test_setup_prompts.py delete mode 100644 tools/test_setup_qwen36.py delete mode 100644 tools/test_setup_remote_opt.py delete mode 100644 tools/test_setup_rerun_size.py delete mode 100644 tools/test_setup_risk.py delete mode 100644 tools/test_setup_rocm_indexes.json delete mode 100644 tools/test_setup_rocm_pins.py delete mode 100644 tools/test_setup_rope.py delete mode 100644 tools/test_setup_shard_check.py delete mode 100644 tools/test_setup_small_card.py delete mode 100644 tools/test_setup_stale_stamp.py delete mode 100644 tools/test_setup_start_gpus_amd.py delete mode 100644 tools/test_setup_strix_halo.py delete mode 100644 tools/test_setup_sycl.py delete mode 100644 tools/test_setup_unsloth.py delete mode 100644 tools/test_setup_update.py delete mode 100644 tools/test_setup_update_gpu.py delete mode 100644 tools/test_strata_mcp.py delete mode 100755 update.sh diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 4f341af..0000000 --- a/.dockerignore +++ /dev/null @@ -1,27 +0,0 @@ -# Keep the image to the source only: everything generated is re-created on -# first start (inside the container or on the /data volume). -.git - -# local Python environment (rebuilt in the image) -.venv/ -__pycache__/ -*.pyc -.pytest_cache/ - -# setup.py outputs and downloads (engine, packs, models, logs) -/engine/ -/build/ -/build*/ -/dist/ -/packs/ -/mtp/ -/models/ -/Strata-data/ -third_party/llama.cpp/ -third_party/*.zip -*.done -*.log -strata-*.json -strata-*.txt -run-*.sh -run-*.bat diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index e6e2db3..0000000 --- a/Dockerfile +++ /dev/null @@ -1,119 +0,0 @@ -# syntax=docker/dockerfile:1 -# -# PolyStrata: Qwen3.8-Flash-Next on NVIDIA GPUs (RTX 30/40/50, 12+ GB VRAM; two or -# three cards can share one model, 8 GB each - docs/MULTI_GPU.md). -# -# The engine is compiled during docker build, so the first container start only -# downloads the model (~70 GB) and starts the server. docker build has no GPU, -# so the CUDA architectures are fixed here instead of read from nvidia-smi: the -# engine is a fat binary with a cubin per listed arch, and the runtime picks the -# one matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster -# build; a card outside the set needs a rebuild with its own arch. -# -# Build: -# docker build -t strata . -# docker build -t strata --build-arg CUDA_ARCHITECTURES=89 . # RTX 40 only -# -# Run (host needs an NVIDIA driver >= 580 and nvidia-container-toolkit): -# docker run --rm --gpus all \ -# -p 8080:8080 \ -# --ulimit memlock=-1 \ -# -v strata-data:/data \ -# -e MODEL=IQ2_XS \ -# strata -# -# Setup choices are env vars, read by docker-entrypoint.sh: FAMILY, MODEL, CONTEXT, -# VISION (no | yes | cpu), KV (int8 | q4_0 | k8v4), GPU (one card) or GPUS ("0,2" -# or "all", with LAYER_SPLIT), LOW_RAM (auto | on | off), HOST, PORT, API_KEY, -# GGUF_DIR (GGUF files you already have), RESIDENT_BUDGET_GIB, KV_STREAMING. -# -# Only the model files, the prepared pack, the MTP layer and the install config -# live in the /data volume; the engine is part of the image. PolyStrata loads 32-62 GB -# into RAM, so a capped container needs -e LOW_RAM=on: setup.py reads the RAM from -# /proc/meminfo, which here is the host's total, not the container's limit. Add an -# API key before exposing the port to a network: -e API_KEY=. Pass -# -e REINSTALL=1 to change the model settings later. -# -# --gpus all on a host with two usable cards: setup takes both (the layer split is -# its recommended default). Pin one card with -e GPU=0, or name them with -# -e GPUS=0,2. A volume set up for one card switches to the pair on its first start -# on a two-card host unless GPU or GPUS pins it. LOW_RAM=on runs on one card. - -FROM nvidia/cuda:13.0.0-devel-ubuntu24.04 - -# STRATA_EXECV=1: setup.py replaces itself with the server, so the server is PID 1 -# and docker stop's SIGTERM reaches it (see setup.start). Normal Linux starts, which -# don't set it, keep spawning the server as a child. -ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 LANG=C.UTF-8 STRATA_EXECV=1 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential ca-certificates curl git libatomic1 libgomp1 \ - python3 python3-pip python3-venv unzip \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /opt/strata -COPY . . - -# RTX 20 (75), RTX 30 (86), RTX 40 (89), RTX 50 (120), plus 80 for A-series. CMakeLists -# refuses anything below 75. BUILD_VISION=0 skips the image encoder build. -ARG CUDA_ARCHITECTURES=75;80;86;89;120 -ARG BUILD_VISION=1 - -RUN python3 -m venv .venv \ - && .venv/bin/pip install --no-cache-dir --upgrade pip \ - && .venv/bin/pip install --no-cache-dir -r requirements.txt \ - && chmod +x setup.sh docker-entrypoint.sh - -# llama.cpp at the pinned commit, then the engine and the image encoder, built -# exactly the way setup.py builds them: native code for the CPU that builds the -# image, so build it on the PC it runs on. BUILD.json is what setup.py reads to -# decide whether an engine is current: source=local with a matching src hash -# means the first start reuses it instead of recompiling. -RUN .venv/bin/python - <<'PYEOF' -import json, os, pathlib, shutil -import setup - -llama = setup.get_llama_cpp() -nvcc, _ = setup.find_nvcc() -arch = os.environ.get("CUDA_ARCHITECTURES", "75;80;86;89;120").strip().strip('"').replace(",", ";") -vision = "gpu" if os.environ.get("BUILD_VISION", "1") == "1" else "none" - -setup.cmake_build(setup.ROOT, setup.ROOT / "build", "strata", - ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_Q6K_EXPERTS=ON", "-DSTRATA_MMQ_KQUANTS=ON", "-DSTRATA_BUILD_TESTS=OFF", - f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}", - f"-DSTRATA_GGML_DIR={llama}"], None, "build-strata.bat") -if vision != "none": - setup.cmake_build(setup.ROOT / "tools" / "vision", setup.ROOT / "build-vision", "strata-vision", - [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=ON", "-DSTRATA_PORTABLE=OFF", - f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}"], None, "build-vision.bat") - -eng = setup.ROOT / "engine" -eng.mkdir(exist_ok=True) -shutil.copy2(setup.ROOT / "build" / setup.EXE, eng / setup.EXE) -if (setup.ROOT / "build" / setup.KQ_LIB).exists(): # the K-quant MMQ prompt library (UD-Q4/Q5/Q6_K_XL files) - shutil.copy2(setup.ROOT / "build" / setup.KQ_LIB, eng / setup.KQ_LIB) -if vision != "none": - shutil.copy2(setup.ROOT / "build-vision" / "bin" / setup.VEXE, eng / setup.VEXE) -bindir = pathlib.Path(nvcc).parent -meta = {"source": "local", "version": setup.source_version(), - "archs": [int(a.split("-")[0]) for a in arch.split(";") if a.split("-")[0].isdigit()], "vision": vision, - "cuda_dirs": [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()], - "src": setup.source_hash(setup.ENGINE_SOURCES), - "vision_src": setup.source_hash(setup.VISION_SOURCES) if vision != "none" else None} -(eng / "BUILD.json").write_text(json.dumps(meta, indent=1)) -PYEOF - -# the cmake trees are build-time only; the engine itself is what the container needs -RUN rm -rf build build-vision - -VOLUME ["/data"] -EXPOSE 8080 - -# /health is answered before the API key gate, so it works with or without one. -# The port only opens after the model loads (1-3 minutes, longer on a first run), -# so the start period is generous: a too short one marks a still-loading container -# unhealthy and a restart policy would kill it mid-download. -HEALTHCHECK --interval=30s --timeout=5s --start-period=600s --retries=3 \ - CMD curl -fs "http://127.0.0.1:${PORT:-8080}/health" || exit 1 - -ENTRYPOINT ["./docker-entrypoint.sh"] diff --git a/SETUP.bat b/SETUP.bat deleted file mode 100644 index d2e6541..0000000 --- a/SETUP.bat +++ /dev/null @@ -1,3 +0,0 @@ -@echo off -rem Change settings or install another model (the same as START-HERE.bat --setup). -call "%~dp0START-HERE.bat" --setup %* diff --git a/START-HERE.bat b/START-HERE.bat deleted file mode 100644 index ad050c0..0000000 --- a/START-HERE.bat +++ /dev/null @@ -1,52 +0,0 @@ -@echo off -rem PolyStrata for Windows: the first run installs everything and starts the model; later runs just start it. -rem Needs only an NVIDIA or AMD graphics driver. Python is installed for your user account if it is missing (no admin needed). -setlocal -title PolyStrata -cd /d "%~dp0" -if exist ".venv\Scripts\python.exe" goto run - -call :findpy -if defined PY goto venv -echo. -echo Python 3.10 or newer is not installed. Installing Python 3.12 for your user account ... -where winget >nul 2>nul -if errorlevel 1 goto pyorg -winget install -e --id Python.Python.3.12 --scope user --silent --source winget --accept-package-agreements --accept-source-agreements --disable-interactivity -call :findpy -if defined PY goto venv -:pyorg -echo Downloading the Python installer from python.org ... -powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol='Tls12'; Invoke-WebRequest -UseBasicParsing https://www.python.org/ftp/python/3.12.10/python-3.12.10-amd64.exe -OutFile \"$env:TEMP\strata-python-setup.exe\"" -if exist "%TEMP%\strata-python-setup.exe" "%TEMP%\strata-python-setup.exe" /quiet InstallAllUsers=0 PrependPath=1 Include_launcher=1 Include_test=0 -call :findpy -if defined PY goto venv -echo. -echo Python could not be installed automatically. -echo Install 64-bit Python 3.12 from https://www.python.org/downloads/ ("Add python.exe to PATH"), -echo then double-click START-HERE.bat again. -pause -exit /b 1 - -:venv -rem a private environment inside this folder, so nothing is installed into the system Python -%PY% -m venv .venv -if exist ".venv\Scripts\python.exe" goto run -echo Could not create the Python environment in .venv -pause -exit /b 1 - -:run -".venv\Scripts\python.exe" setup.py %* -if errorlevel 1 pause -exit /b - -:findpy -rem the py launcher first, then python on PATH (not the Microsoft Store stub), then the usual per-user folders -set "PY=" -py -3 -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) and sys.maxsize > 2**32 else 1)" >nul 2>nul -if not errorlevel 1 set "PY=py -3" & goto :eof -python -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) and sys.maxsize > 2**32 else 1)" >nul 2>nul -if not errorlevel 1 set "PY=python" & goto :eof -for %%V in (313 312 311 310) do if exist "%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe" set "PY="%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe"" & goto :eof -goto :eof diff --git a/UPDATE.bat b/UPDATE.bat deleted file mode 100644 index eefbc6c..0000000 --- a/UPDATE.bat +++ /dev/null @@ -1,81 +0,0 @@ -@echo off -rem Update PolyStrata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then -rem what START-HERE.bat does before a start - the engine (a new one when this version needs it), the Python packages, -rem each installed model's settings and draft subset. The model files are not touched. Start the model later with -rem START-HERE.bat. Options are passed on to setup.py. -setlocal -title PolyStrata - update -cd /d "%~dp0" -rem All of it in one block: cmd reads a .bat file while it runs it, and the git pull can change this very file. -( - if exist ".git" ( - where git >nul 2>nul || ( - echo This folder is a git clone, but git is not on PATH: install Git for Windows ^(winget install Git.Git^) - echo or run "git pull" here yourself, then run UPDATE.bat again. - pause - exit /b 1 - ) - echo Getting the newest PolyStrata ^(git pull^) ... - git pull --ff-only - if errorlevel 1 ( - rem The history was rewritten on 2026-10-06, see #1276: a clone from before has no commit in common with origin/main. - set "REWR=" - git merge-base HEAD origin/main >nul 2>nul - if errorlevel 1 set "REWR=1" - git rev-parse --is-shallow-repository 2>nul | findstr /x true >nul && set "REWR=" - if defined REWR ( - echo. - echo This clone is on the repository's old history ^(cleaned up on 2026-10-06^): it has no commit in common - echo with origin/main, so it cannot be updated by git pull. - set "DIRTY=" - for /f "delims=" %%i in ('git status --porcelain --untracked-files^=no') do set "DIRTY=1" - if defined DIRTY ( - echo You have local changes to tracked files here, so nothing was touched. To move to the new history - echo yourself ^(your untracked files, models and settings stay where they are^): - echo git branch pre-cleanup-backup - echo git stash push - echo git checkout -B main origin/main - echo then run UPDATE.bat again. - pause - exit /b 1 - ) - set "BK=pre-cleanup-backup" - git rev-parse --verify -q refs/heads/pre-cleanup-backup >nul 2>nul && set "BK=pre-cleanup-backup-%RANDOM%" - set "BR=main" - for /f "delims=" %%i in ('git symbolic-ref --short -q HEAD 2^>nul') do set "BR=%%i" - call git branch %%BK%% HEAD - if errorlevel 1 ( - echo Could not make the backup branch: nothing was updated. - pause - exit /b 1 - ) - call git checkout -q -B %%BR%% origin/main - if errorlevel 1 ( - call git branch -D %%BK%% >nul 2>nul - echo. - echo Could not move to the new history ^(the reason is above^): nothing was updated. By hand: - echo git checkout -B main origin/main - pause - exit /b 1 - ) - call echo Moved to the new history. Your old commits are kept in the branch %%BK%%. - echo Untracked files ^(models, settings, the engine^) were not touched. - ) else ( - echo. - echo git pull did not succeed ^(the reason is above^): nothing was updated. Files you changed here can stop it: - echo "git status" lists them. - pause - exit /b 1 - ) - ) - ) else ( - echo This copy of PolyStrata was not made with git, so it cannot fetch new files itself. Download the newest one: - echo https://github.com/VecSzn/PolyStrata/archive/refs/heads/main.zip - echo unzip it anywhere and run START-HERE.bat ^(or UPDATE.bat^) in it: it finds the model files in PolyStrata-data - echo and sets itself up the same way - nothing big is downloaded again. - echo Checking this copy's engine and settings meanwhile ... - ) - call "%~dp0START-HERE.bat" --update %* - if not errorlevel 1 pause - exit /b -) diff --git a/UPSTREAM.md b/UPSTREAM.md index 442b6b4..93e37d6 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -61,4 +61,15 @@ No changes yet. ## Removed -Nothing yet. The import is the current head of the engine tree. +Each entry names the rule above that it satisfies. + +- **Rule 1, installers and downloaders:** `setup.py` (8,223 lines: hardware detection, pip, CUDA, llama.cpp zips, + prebuilt engines from GitHub releases, model files from Hugging Face or ModelScope, pack and MTP orchestration, + run-config JSON, start), `setup.sh`, `SETUP.bat`, `START-HERE.bat`, `UPDATE.bat`, `update.sh`, `Dockerfile`, + `docker-entrypoint.sh`, `.dockerignore`, `flake.nix`, `flake.lock`, `requirements.txt` (replaced by + `tools/requirements.txt`: numpy and regex, for the offline tools only), `conftest.py` (pytest root for + `setup.py`'s tests), `tools/strata_mcp.py` (an installer driven over MCP), `tools/image/` (stable-diffusion.cpp, + Vulkan SDK and model downloads), `tools/hip/package_windows.py` (AMD nightly wheels), and their tests + (`tools/test_setup_*.py` with two golden JSONs, `test_strata_mcp.py`, `test_qimage.py`, + `test_docker_entrypoint.py`, `test_poly_prebuilt.py`). The jobs of `setup.py` that were not downloads (choosing + engine flags per card, RAM and context) become documented flags in `README.md`. diff --git a/conftest.py b/conftest.py deleted file mode 100644 index fdaddb0..0000000 --- a/conftest.py +++ /dev/null @@ -1,9 +0,0 @@ -"""pytest: setup.py's data-folder migration (#198) saves the data folder it settled on in the user's settings file -(%APPDATA%\PolyStrata\settings.json, ~/.config/polystrata/settings.json) and can MOVE model files from a folder it finds there. -A test that reaches it must never touch the real file, so the whole session gets its own config home.""" -import os -import tempfile - -_home = tempfile.mkdtemp(prefix="strata-pytest-config-") -os.environ["APPDATA"] = _home -os.environ["XDG_CONFIG_HOME"] = _home diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh deleted file mode 100755 index 23ffddb..0000000 --- a/docker-entrypoint.sh +++ /dev/null @@ -1,106 +0,0 @@ -#!/bin/sh -# Entry point for the PolyStrata container. The engine is compiled during docker -# build and lives in the image, so the first start only downloads the model. -# The install config is kept on the /data volume so a recreated container skips -# the setup pass and goes straight to serving. -set -e -cd /opt/strata || exit 1 - -# #1584: the engine in the image is built with AVX2 CPU kernels. A host CPU without AVX2 (Sandy / Ivy Bridge Xeons, -# Bulldozer) runs it into an illegal instruction. A warning, not a stop: recommend, never force (the flags file -# can be wrong in a VM, and a build made on that host may be fine). STRATA_CPUINFO is for the test. -cpuinfo="${STRATA_CPUINFO:-/proc/cpuinfo}" -if [ -r "$cpuinfo" ] && grep -q '^flags' "$cpuinfo" && ! grep -m1 '^flags' "$cpuinfo" | grep -qw avx2; then - echo "WARNING: this host CPU has no AVX2. The engine in this image is built for CPUs with AVX2, so it may stop" >&2 - echo " with 'illegal instruction' (exit 132). Build the image on this machine (docker build), which compiles the" >&2 - echo " engine for the CPU it runs on, and see docs/INSTALL.md (Older CPUs, experimental) for the older-CPU build." >&2 -fi - -STRATA_DATA="${STRATA_DATA:-/data}" -FAMILY="${FAMILY:-qwen}" -MODEL="${MODEL:-IQ2_XS}" -CONTEXT="${CONTEXT:-32768}" -VISION="${VISION:-no}" # no | yes | cpu (the image encoder on the CPU) -HOST="${HOST:-0.0.0.0}" -PORT="${PORT:-8080}" -API_KEY="${API_KEY:-}" -KV="${KV:-}" # int8 | q4_0 | k8v4; empty: setup.py's own default (int8) -GPUS="${GPUS:-}" # "0,2" or "all": one model across several cards (docs/MULTI_GPU.md) -GPU="${GPU:-}" # one card, numbered as nvidia-smi numbers them -LAYER_SPLIT="${LAYER_SPLIT:-}" # with GPUS: where each later card's layers start (default: auto) -LOW_RAM="${LOW_RAM:-auto}" # on: the experts come from the pack's experts.bin, not from RAM -GGUF_DIR="${GGUF_DIR:-}" # a mounted folder with GGUF files you already have: no download -RESIDENT_BUDGET_GIB="${RESIDENT_BUDGET_GIB:-}" # UD-Q4_K_XL: GiB of experts kept in RAM (default: setup's pick) -KV_STREAMING="${KV_STREAMING:-}" # auto | on | off; empty: setup.py's own default (auto) -CONFIG="${CONFIG:-}" # a config file to start with (wins over MODEL's /data/config/strata-.json) - -# setup.py starts the newest strata-*.json it finds, so link in exactly the one -# this family and model were set up with. The config is the recorded output of -# that setup (the pack, the profile, the quant, the KV decision), not settings -# the entry point could rebuild from env vars. qwen has an empty family tag. -case "$FAMILY" in qwen) prefix="" ;; *) prefix="${FAMILY}-" ;; esac -tag="${prefix}$(printf '%s' "$MODEL" | tr 'A-Z' 'a-z')" -cfg="$STRATA_DATA/config/strata-$tag.json" -mkdir -p "$STRATA_DATA/config" - -# REINSTALL is only needed to change settings for a model that is already set up -# (context, vision, KV, host, api_key). Switching between models already on the -# volume needs no setup pass: their config is already there. -# -# KV / GPUS / GPU / LAYER_SPLIT are passed only when set, so an unset one keeps -# setup.py's own default. LOW_RAM is always passed: setup.py measures the PC's RAM -# from /proc/meminfo, which in a container is the host's total, not the container's -# limit, so a memory-capped container has to ask for the low-RAM mode itself. -# -# Which config the server starts with (#1244): CONFIG when set; else a link in /opt/strata that already points -# into $STRATA_DATA/config/ (a pod command that picked one by linking); else MODEL's strata-.json. -link="/opt/strata/strata-$tag.json" -keep="" -if [ -n "$CONFIG" ]; then - [ -f "$CONFIG" ] || { echo "CONFIG=$CONFIG does not exist." >&2; exit 1; } -elif [ "${REINSTALL:-0}" != "1" ] && [ -L "$link" ] && [ -f "$link" ]; then - case "$(readlink "$link")" in "$STRATA_DATA"/config/*) keep=1 ;; esac -fi - -if [ -n "$CONFIG" ]; then - ln -sfn "$CONFIG" "$link" - echo "Config: $CONFIG (from CONFIG)" -elif [ -n "$keep" ]; then - echo "Config: $(readlink "$link") (existing link kept)" -elif [ "${REINSTALL:-0}" = "1" ] || [ ! -f "$cfg" ]; then - if [ -n "$GGUF_DIR" ]; then - echo "Setting up $tag from the GGUF files in $GGUF_DIR (the engine is already in the image)." - else - echo "Setting up $tag: downloading the model (~70 GB; the engine is already in the image)." - fi - set -- --family "$FAMILY" --model "$MODEL" --context "$CONTEXT" --vision "$VISION" \ - --data-dir "$STRATA_DATA" --host "$HOST" --api-key "$API_KEY" \ - --port "$PORT" --no-start --low-ram "$LOW_RAM" - if [ -n "$KV" ]; then set -- "$@" --kv "$KV"; fi - if [ -n "$GPUS" ]; then set -- "$@" --gpus "$GPUS"; fi - if [ -n "$GPU" ]; then set -- "$@" --gpu "$GPU"; fi - if [ -n "$LAYER_SPLIT" ]; then set -- "$@" --layer-split "$LAYER_SPLIT"; fi - if [ -n "$GGUF_DIR" ]; then set -- "$@" --gguf-dir "$GGUF_DIR"; fi - if [ -n "$RESIDENT_BUDGET_GIB" ]; then set -- "$@" --resident-budget-gib "$RESIDENT_BUDGET_GIB"; fi - if [ -n "$KV_STREAMING" ]; then set -- "$@" --kv-streaming "$KV_STREAMING"; fi - .venv/bin/python setup.py --setup --yes "$@" - [ -e "/opt/strata/strata-$tag.json" ] && { cmp -s "/opt/strata/strata-$tag.json" "$cfg" || cp -f "/opt/strata/strata-$tag.json" "$cfg"; } - echo "Config: $cfg (from MODEL $MODEL, just set up)" -else - # #1244: the copy on the volume is the one that counts, so a regular file left in /opt/strata by an earlier setup - # (or by an image built with one) must not stand in for it: edits to /data/config would be ignored - ln -sfn "$cfg" "/opt/strata/strata-$tag.json" - echo "Config: $cfg (from MODEL $MODEL)" -fi - -# Later starts skip straight here: setup.py finds the installed config and -# launches serve/server.py (OpenAI- and Anthropic-compatible API on :8080). -# GPUS / GPU / LAYER_SPLIT are repeated on purpose. Given at the start they pin the -# cards for this model, and setup.py saves them in its config; without them a config -# that names one card is offered once to a pair, on its own, when the host has two -# cards that can share the model (setup.py's offer_together, docs/MULTI_GPU.md). -set -- --port "$PORT" -if [ -n "$GPUS" ]; then set -- "$@" --gpus "$GPUS"; fi -if [ -n "$GPU" ]; then set -- "$@" --gpu "$GPU"; fi -if [ -n "$LAYER_SPLIT" ]; then set -- "$@" --layer-split "$LAYER_SPLIT"; fi -exec .venv/bin/python setup.py "$@" diff --git a/flake.lock b/flake.lock deleted file mode 100644 index 43cbb9f..0000000 --- a/flake.lock +++ /dev/null @@ -1,27 +0,0 @@ -{ - "nodes": { - "nixpkgs": { - "locked": { - "lastModified": 1791594108, - "narHash": "sha256-XK4KceonkwD8LuMAt/vNrz982mXJM5jeHAxMwsUXXAQ=", - "owner": "nixos", - "repo": "nixpkgs", - "rev": "6510408d147d8c5e6d76043e899e9251756f6a75", - "type": "github" - }, - "original": { - "owner": "nixos", - "ref": "nixos-unstable", - "repo": "nixpkgs", - "type": "github" - } - }, - "root": { - "inputs": { - "nixpkgs": "nixpkgs" - } - } - }, - "root": "root", - "version": 7 -} diff --git a/flake.nix b/flake.nix deleted file mode 100644 index e5f6fc9..0000000 --- a/flake.nix +++ /dev/null @@ -1,49 +0,0 @@ -{ - description = "Nix environment for Strata"; - - inputs = { - nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; - }; - - outputs = { self, nixpkgs, ... }: - let - system = "x86_64-linux"; - pkgs = import nixpkgs { - inherit system; - # Allow NVIDIA's CUDA toolkit (nvcc, cudart, cuBLAS, ...). - config.allowUnfree = true; - config.cudaSupport = true; - }; - - # setup.py wants CUDA 13.0: the ready-made engine is built with 13.0.88, and 13.2.0/13.2.1 miscompile for sm_120. - cudaPackages = pkgs.cudaPackages_13_0; - # One merged toolkit root (bin/nvcc, include/, lib/ with cudart and cuBLAS) for CUDA_HOME / CUDAToolkit_ROOT. - cuda = cudaPackages.cudatoolkit; - # The gcc that this nvcc supports as its host compiler. - stdenv = cudaPackages.backendStdenv; - - in - { - devShells."${system}" = { - default = (pkgs.mkShell.override { inherit stdenv; }) { - packages = with pkgs; [ - # ./setup.sh: makes .venv and runs setup.py - python3 - - # setup.py's engine build. cmake/ninja from PATH: the pip wheels' binaries do not run on NixOS. - cuda - cmake - ninja - ]; - - shellHook = '' - export CUDA_HOME=${cuda} - export CUDA_PATH=${cuda} - export CUDAHOSTCXX=${stdenv.cc}/bin/c++ - # The pip wheels in .venv (numpy, pillow, ...) need libstdc++ and zlib; the engine needs the driver's libcuda. - export LD_LIBRARY_PATH=/run/opengl-driver/lib:${pkgs.lib.makeLibraryPath [ stdenv.cc.cc.lib pkgs.zlib ]}''${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} - ''; - }; - }; - }; -} diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 3db8418..0000000 --- a/requirements.txt +++ /dev/null @@ -1,23 +0,0 @@ -# The Python packages setup.py installs into .venv, pinned so a checkout installs the same ones on any day (#214). -# setup.py's pip step reads this file; an install from before it keeps the packages it has. -# Python 3.10+ (numpy's newest releases need a newer Python: one line per range). -numpy==2.5.3; python_version >= "3.12" -numpy==2.4.6; python_version == "3.11" -numpy==2.2.6; python_version < "3.11" -jinja2==3.1.6 -regex==2026.9.10 -pyyaml==6.0.3 -tqdm==4.70.1 -requests==2.34.2 -cmake==4.4.3 -ninja==1.13.2 -pillow==12.3.0 -psutil==7.2.2 - -# their dependencies -markupsafe==3.0.3 -certifi==2026.7.22 -charset-normalizer==3.5.1 -idna==3.20 -urllib3==2.8.0 -colorama==0.4.6; sys_platform == "win32" diff --git a/setup.py b/setup.py deleted file mode 100644 index 17b8ca8..0000000 --- a/setup.py +++ /dev/null @@ -1,8223 +0,0 @@ -#!/usr/bin/env python3 -"""PolyStrata one-click setup and start (Windows and Linux, NVIDIA or AMD GPUs). - - START-HERE.bat (Windows) / ./setup.sh (Linux) - they install Python if needed and run this file - -The first time it asks four questions - which model (the original Qwen3.8-Flash-Next or the Swift 1.5 fine-tune), -which 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 -API; a small page there shows that it runs). Every later start skips straight to running the model: nothing that -is already downloaded, installed or prepared is done again. - -What the first run does (each step is skipped when it is already done): - - 1. checks your PC: NVIDIA or AMD GPU and driver, RAM, CPU, free disk space - 2. asks the questions - 3. installs the Python packages it needs into .venv (numpy, jinja2, ..., and NVIDIA's CUDA libraries) - 4. gets the PolyStrata engine: a ready-made build for RTX 20/30/40/50 cards (no compiler needed); if none fits your PC, - it installs the build tools (asks first) and compiles the engine for your GPU. AMD (--backend hip, chosen by - itself on a PC with no usable NVIDIA card): the ready-made HIP engine on Windows, compiled here on Linux - 5. downloads the model from Hugging Face (resumable), and the vision encoder if you want images - 6. prepares the model for PolyStrata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint) - 7. writes run-.bat / run-.sh and starts the model - -GLM 5.3 Flash (--family glm, docs/GLM.md) is a second model with an engine of its own, compiled here: Linux, one -NVIDIA card. Its setup asks for the context and the conversation cache and has no steps for a pack or images. The -model has one draft block for all its sizes: a size whose file leaves it out gets the block alone (~2.8 GB). - -That engine also runs Qwen3.6-35B-A3B (--family qwen36), Ornith 1.5 (--family ornith) and Gemma 4 26B-A4B (--family -gemma4) from one GGUF each, 13 to 17 GB (docs/BACKENDS.md). Their setup is GLM's, with nothing more to fetch. - -Options: --family qwen|swift|..., --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --rope-scaling none|linear|yarn -(--rope-scale F; past the trained 262144 the setup adds yarn and the factor is the final context over 262144, -at least 1 - an explicit --rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port -8080, --yes (recommended -answers, no questions), --setup (install another model / change settings instead of starting), --no-start, ---host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off -(EXPERIMENTAL, off by default), ---models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made -engine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's or UD-IQ4_XS's experts in RAM), ---kv-streaming on|off|auto. - -Setup recommends, it never forces: the recommended answers are the defaults (--yes, or Enter), and a bigger choice -than it recommends - a longer context, more GPUs, a bigger RAM budget, a size it thinks will not fit - is kept, with -what it risks. With --yes, an explicit flag (--model, --gpus, ...) is the consent to a risk setup would otherwise -stop at; --yes alone is not. -""" -from __future__ import annotations - -import argparse -import ctypes -import glob -import hashlib -import json -import math -import os -import platform -import re -import shutil -import struct -import subprocess -import sys -import textwrap -import time -import urllib.error -import urllib.request -import zipfile -from pathlib import Path - -ROOT = Path(__file__).resolve().parent -WIN = os.name == "nt" -# #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of -# https://huggingface.co/api/models/ when this was pinned), so a checkout installs the same files on any -# day. A revision the repository no longer has falls back to its current files, with a message (download()). -HF_REVISIONS = { - "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", # 2026-09-29 - "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "b22d729eae29b5796f76fb70f91aef549b9fc52c", # 2026-09-24 - "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF": "5348543e0147355ac9cbcb031184a3546350988e", # 2026-09-29 - "unsloth/Qwen3.8-Flash-Next-GGUF": "38bb39ee97821de2c9009abb7e93950eec396e66", # 2026-09-30 - "neuralll/GLM-5.3-Flash-GSQ-RCO-3.0bit-Q4Kattn-GGUF": "7feedfeb5ee924bfbe0064c63b124728b443ddc0", # 2026-09-26 - "patrickbdevaney/GLM-5.3-Flash-REAP50-GGUF": "46cb1bb887721d919e978d2f3eb18da245fecd77", # 2026-10-05 - "unsloth/GLM-5.3-Flash-GGUF": "621d456e93e926e4b52f85cff5f634358c1828f9", # 2026-10-05 - "mudler/Ornith-1.5-35B-A3B-APEX-MTP-GGUF": "4c326713c52d13fdb40983a2a09a46cca8e88739", # 2026-10-05 - "unsloth/gemma-4-26B-A4B-it-GGUF": "c099eb48e663fd284577b04978a94ffccb261841", # 2026-10-05 - "peculiar-ragdoll/Tiel-Coder-35B-A3B-GGUF-MTP": "bbe9e566f39e4fc9652ac66b71968289a03c520a", # 2026-09-10 - "unsloth/Qwen3.6-35B-A3B-MTP-GGUF": "5bc3e238d916f48a861bac2f8a1990a0e9b7e98d", # 2026-10-12 - "unsloth/DeepSeek-V4-Flash-0731-GGUF": "fbbb5b93fb787c21338159b0af3318bb3f4d9768", # 2026-10-15 - "unsloth/LFM2.5-24B-A2B-GGUF": "faa77113e93335b63423e9e8d33395f86eaf8946", # 2026-10-15 - "LiquidAI/LFM2.5-24B-A2B-GGUF": "0912d33141f77e10705345a6732bfd83f0252fdc", # 2026-10-15 - "openbmb/MiniCPM-V-4.7-35B-A3B-gguf": "77f6d8cb08b2b115ce27d2e2ac1359e126921689", # 2026-10-12 -} - - -HF_DEFAULT = "https://huggingface.co" - - -def hf_endpoint() -> str: - """#495: the Hugging Face host - HF_ENDPOINT as huggingface_hub reads it (a mirror, e.g. https://hf-mirror.com), - else huggingface.co. The pinned revisions and the SHA-256 checks are the same whichever host serves the files.""" - return (os.environ.get("HF_ENDPOINT") or "").strip().rstrip("/") or HF_DEFAULT - - -def hf(repo: str) -> str: - """The download folder of a Hugging Face repository at its pinned revision.""" - return f"{hf_endpoint()}/{repo}/resolve/{HF_REVISIONS[repo]}/" - - -def hf_unpinned(url: str) -> str: - """The same file at the repository's current revision (main).""" - return re.sub(r"^(https?://[^/]+/.+?/resolve/)[0-9a-f]{40}/", r"\1main/", url, count=1) - - -# ModelScope (www.modelscope.cn) hosts every repository above under the same name, with the same file paths and -# sizes, and is reachable from mainland China where huggingface.co often is not. It serves a repository's current -# files (no pinned revision), so a file from it is checked against the SHA-256 ModelScope publishes for it, and the -# MTP tensors against the pinned checkpoint's own hashes (tools/mtp_fetch.py). -# --source / STRATA_SOURCE: huggingface (what auto means), or modelscope: only when asked for (a different host -# serving current files, not our pinned revision: setup never switches to it by itself, it recommends it, #908). -MS_DEFAULT = "https://www.modelscope.cn" -SOURCES = ("auto", "modelscope", "huggingface") -HF_FILE = re.compile(r"^https?://[^/]+/(?P[^/]+/[^/]+)/resolve/[^/]+/(?P.+)$") -_sources = {} # model_source()'s answer per (STRATA_SOURCE, HF_ENDPOINT, host) -_ms_files = {} - - -def ms_endpoint() -> str: - return (os.environ.get("MODELSCOPE_ENDPOINT") or "").strip().rstrip("/") or MS_DEFAULT - - -def reachable(url: str, timeout: float = 5.0) -> bool: - """Whether `url` answers a HEAD request with success (2xx, after redirects) within `timeout` seconds.""" - try: - urllib.request.urlopen(urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}), - timeout=timeout).close() - return True - except OSError: # HTTPError too: an error page is not the file - return False - - -def model_source() -> str: - """"modelscope" or "huggingface". ModelScope only when --source modelscope / STRATA_SOURCE=modelscope asks for it; - everything else (auto, a HF_ENDPOINT mirror chosen on purpose, #495) is Hugging Face. Setup does not switch hosts - by itself (#908): ModelScope serves a repository's current files, not our pinned revision.""" - want = (os.environ.get("STRATA_SOURCE") or "auto").strip().lower() - key = (want, os.environ.get("HF_ENDPOINT") or "", ms_endpoint()) - if key not in _sources: - _sources[key] = "modelscope" if want in ("ms", "modelscope") else "huggingface" - return _sources[key] - - -def source_hint(url: str) -> str: - """The recommendation that goes with a failed download from Hugging Face: ModelScope, by an explicit choice.""" - if "huggingface" in url or "hf-mirror" in url: - return ("; if huggingface.co does not reach you (mainland China), the same files are on ModelScope: run setup " - "with --source modelscope (docs/INSTALL.md)") - return "" - - -def ms_file(url: str): - """(repo, path) when `url` is a Hugging Face file of a repository setup knows (HF_REVISIONS), else None.""" - m = HF_FILE.match(url) - if m is None or m.group("repo") not in HF_REVISIONS: - return None - return m.group("repo"), m.group("path") - - -def ms_url(repo: str, path: str) -> str: - return f"{ms_endpoint()}/models/{repo}/resolve/master/{path}" - - -def ms_meta(repo: str, path: str): - """(size, sha256) ModelScope publishes for a file, or None when it cannot be asked.""" - if repo not in _ms_files: - try: - api = f"{ms_endpoint()}/api/v1/models/{repo}/repo/files?Recursive=true" - with urllib.request.urlopen(urllib.request.Request(api, headers={"User-Agent": "strata-setup"}), - timeout=60) as r: - files = json.loads(r.read())["Data"]["Files"] - _ms_files[repo] = {f["Path"]: (int(f.get("Size") or 0), (f.get("Sha256") or "").lower()) for f in files} - except (OSError, ValueError, KeyError, TypeError): - return None - return _ms_files[repo].get(path) - - -HF = hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") -LLAMA_CPP_COMMIT = "3cf03257f219afbe7334045ff7c6a06ac68c627d" -LLAMA_CPP_ZIP = f"https://github.com/ggml-org/llama.cpp/archive/{LLAMA_CPP_COMMIT}.zip" -# The image encoder's own llama.cpp: MiniCPM-V 4.7's mtmd is newer than the engines' pin, and the engines stay on -# the Strata project's pin until it moves; only strata-vision builds from this one (a second checkout, like #14 suggests). -VISION_LLAMA_CPP_COMMIT = "69f201a2051ea9b9e9b50c3cc56afd9e2ae64414" -VISION_LLAMA_CPP_ZIP = f"https://github.com/ggml-org/llama.cpp/archive/{VISION_LLAMA_CPP_COMMIT}.zip" - -# The ready-made engine: , a zip with strata(.exe), strata-vision(.exe) and BUILD.json, built -# by tools/make_release.py. Set this to the GitHub release download folder when publishing, e.g. -# "https://github.com//PolyStrata/releases/latest/download/" (or pass --prebuilt / set STRATA_PREBUILT_URL). -# With the default, the release of this checkout's own version (PREBUILT_TAG_URL, CMakeLists.txt's version) is -# tried first and the latest release is the fallback (#214): an older checkout keeps the engine it shipped with. -# The Qwen engine is the Strata project's, unchanged, so its ready-made build comes from that project's releases. -PREBUILT_URL = "https://github.com/Niko1221/Strata/releases/latest/download/" -# The repository the release assets and their SHA-256 come from; `engine_digest` reads the API here even -# when --prebuilt points the download somewhere else, because the hash is only worth having if it comes -# from somewhere the download does not. -REPO = "Niko1221/Strata" -PREBUILT_TAG_URL = "https://github.com/Niko1221/Strata/releases/download/v{version}/" -PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" -# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages -CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] -MIN_DRIVER = 580 # CUDA 13.0 -# Older NVIDIA GPUs (experimental): CUDA 13 dropped Pascal (sm_60/61) and Volta (sm_70), so a model whose GPUs include -# one runs a second engine, built with CUDA 12.9 (-DSTRATA_EXPERIMENTAL_SM60=ON) and kept in its own folder: the -# ready-made one is CUDA12_ASSET (Windows; on Linux it is compiled here with a CUDA 12.x toolkit). One engine runs per -# model, so the choice is per model config, by its oldest GPU; --cuda 12|13 overrides it (docs/OLDER_GPUS.md). -CUDA13_MIN_ARCH = 75 # the oldest compute capability CUDA 13 compiles for (sm_75, RTX 20) -CUDA12_ASSET = "strata-windows-x64-cuda12.zip" if WIN else "strata-linux-x64-cuda12.zip" -CUDA12_WHEELS = ["nvidia-cublas-cu12==12.9.1.4", "nvidia-cuda-runtime-cu12==12.9.79"] -# CUDA 12.x minor-version compatibility (NVIDIA's table: Linux 525.60.13, Windows 527.41); the wheels match the 12.9.1 -# toolkit the CUDA 12 zip is built with (cuBLAS 12.9.1.4, runtime 12.9.79). Not tested on such an old driver here. -CUDA12_MIN_DRIVER = 528 if WIN else 525 -ENGINE12_DIR = "engine-cuda12" -MIN_ENGINE = (0, 1, 45) # versions compare all numbers; 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 -# KV bytes per context token and attention layer: 8-bit 1056, rotated 4-bit 576, hybrid K8V4 (8-bit K, 4-bit V) 816 -KV_CELL_BYTES = {"q4_0": 576, "k8v4": 816} -PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"] -REQUIREMENTS = ROOT / "requirements.txt" # the same packages and their dependencies, pinned (#214) - -# NVFP4 experts (MODEL-UPDATE Phase 4; the engine path is ported from sergqwer/strata-nvfp4, MIT). Ready-made PolyStrata -# packs on Hugging Face by the fork's author: nothing is converted here. Every file is pinned by its upload's commit, -# 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 -# table and the BF16 token embedding are the same files in both repositories (a second install links them). The -# MTP draft layer is setup's own, as for every other model, so the repositories' mtp/ folder is not downloaded. -# role: pack = the experts pack folder (index.txt, experts.bin, ...), dense = the dense GGUF (--native and -# --native-dense-gguf), ple = the FP8 n-gram table (--ple-gguf), embd = the BF16 token embedding (--embd-gguf) -NVFP4_GPTQ_REPO = "Maximilian228/Qwen3.8-Flash-Next-NVFP4-GPTQ-Strata" # Qwen's BF16 experts by GPTQ (the fork) -NVFP4_NVIDIA_REPO = "Maximilian228/Qwen3.8-Flash-Next-NVIDIA-NVFP4-Strata" # nvidia/Qwen3.8-Flash-Next-NVFP4, converted -_NVFP4_TOKENIZER = { - "pack/tokenizer/chat_template.jinja": ("pack", 8952, "c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041"), - "pack/tokenizer/merges.txt": ("pack", 3600844, "080cf95432173729d160346b7882bd2a644b07f7a3813a3eb73f4e66787bfde9"), - "pack/tokenizer/token_type.json": ("pack", 744960, "5088c8c298fc06af8382ddb3b76c888703ac2634e82263b97eedcc2ad202738b"), - "pack/tokenizer/tokenizer.json": ("pack", 554, "87be2ac47d8bc7393b7435df6ccd276740019a393941a2585d5edce59f450c54"), - "pack/tokenizer/vocab.json": ("pack", 5737005, "4ba64f0332abcfb0b600b7df1537d1e836e68009d5fb7cdb77339738dc6365c4"), -} -_NVFP4_SHARED = { - "ple-fp8.gguf": ("ple", 51200246176, "37f89b8ce5a3425932763257c40229ec02723ad2ab14b4bbfc26a486f4725c9c"), - "token-embd-bf16.gguf": ("embd", 1271398656, "386203af9070c7b43acb24ded8922876721d97bbad1a709b25cb49d694a7f51d"), -} -NVFP4_REPOS = { - NVFP4_GPTQ_REPO: {"revision": "640a1db97446ddd5e89d2b70ecd0297987192c93", "files": { - "pack/dense.bin": ("pack", 1538035200, "974df6dcefcae85e3fd2c19fcc12eeaacaadde8261ab732d5af5af6ce2e25a7a"), - "pack/experts.bin": ("pack", 67948118016, "325e5e0d85c262a8d8278daf73b20696ec877d9a3ff584e57391fa69ad10bc64"), - "pack/index.txt": ("pack", 93663, "f62dc71e1c74a72794db54d3917bc71131cc6eae6f3dcdc3fdada48ff70f93ab"), - "pack/native_experts.txt": ("pack", 1599, "615f655fb28bf60b243664860b135710bf4177b111c6be89073e780a35de1018"), - **_NVFP4_TOKENIZER, - "qwen-nvfp4-gptq-dense.gguf": ("dense", 5991569472, "abdf74336b53d8f7ca3d99947f1eac8f19b8a544966750127cb61e561b127e3b"), - **_NVFP4_SHARED}}, - NVFP4_NVIDIA_REPO: {"revision": "cca8f7fee5ce0af932097340a75e06df25c4e57d", "files": { - "pack/dense.bin": ("pack", 1538625024, "1f1c2422069de292673ae6cee7d69f7090732dec69f3f125612a0de456279714"), - "pack/experts.bin": ("pack", 67948118016, "bb42080bb7585505b64d091d5a734c05376bbd6171406fa9688a46fbc261b957"), - "pack/index.txt": ("pack", 117490, "17793d1c5b187a73d3c1dc1677af4d4c9b23845394dd7e88bfa53396b41b77e3"), - "pack/native_experts.txt": ("pack", 1590, "d7f8b4372bb122f3d711030e5d522bff1c8746ac7d133a59a2cc7277283e59b6"), - **_NVFP4_TOKENIZER, - "qwen-nvidia-nvfp4-dense.gguf": ("dense", 5992176896, "0f795ca0cbb908e0cf2b894b30103e21455b5a05346a7ef79da208540cfd2be3"), - **_NVFP4_SHARED}}, -} -# the first release engine with NVFP4 experts (a source build of this checkout has them whatever its number says) -NVFP4_ENGINE = (0, 1, 44) - -MODELS = { - # the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which - # the pack tool (tools/iq_pack.py) cannot prepare yet (#171) - "Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0, "families": ("qwen",)}, - "IQ2_XS": {"about": "2-bit i-quant, a little better quality, close in speed", "download_gb": 68.0, "ram_gb": 48, - "arena_gb": 35.5}, - "IQ3_XXS": {"about": "3-bit i-quant, better quality, slower (more CPU work per token)", "download_gb": 75.8, - "ram_gb": 60, "arena_gb": 42.9}, - # matches the full BF16 model on the published benchmarks; Swift 1.5 got an IQ3_S tier of its own (#1651) - "IQ3_S": {"about": "3.5-bit i-quant, the best quality (matches the full model), the slowest; needs a 64 GB PC " - "with little else running", "download_gb": 83.6, "ram_gb": 62, "arena_gb": 50.3}, - # the Coder release: 256 of the 512 experts kept (the ones code, tools and vision use), IQ2_S-IQ4_XS like IQ3_S - "IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4, - "ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)}, - # #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 - # UD-Q4_K_XL's; three shards. A regular choice from 0.1.39 (no longer experimental). Its 59.5 GB of experts: a - # 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. - # Images: the vision path has no restriction for this pack (the same base model and image encoder), so setup asks - "UD-IQ4_XS": {"about": "~4-bit i-quant (Unsloth Dynamic), between IQ3_S and UD-Q4_K_XL in quality; on a PC with " - "less than ~80 GB of RAM part of its experts are read from the SSD", - "download_gb": 93.7, "ram_gb": 48, "arena_gb": 59.5, "families": ("unsloth",), "budget": True, - "shards": 3, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00003.gguf", "engine": (0, 1, 38), - "vision": True}, - # GLM 5.3 Flash (docs/GLM.md): a GGUF read in place by its own engine (poly_setup). "arena_gb" is the routed - # experts; the ones the GPU does not hold come through the OS file cache. "ram_gb" is poly_ram_need() for a - # 32 GB card, an estimate: it has run with 120 GB of RAM only. A size may have its own repository ("hf"), - # expert profile and VRAM beside the experts ("vram_beside_gb", measured at 32K on that card). "draft": "own": - # the file carries the model's draft block; a size without the key gets the block from FAMILIES["glm"]["draft"]. - "3.0BIT": {"about": "the whole model: 3-bit GSQ-RCO experts, Q4_K attention", "download_gb": 113.6, - "ram_gb": 96, "arena_gb": 107.2, "families": ("glm",), "shards": 1, - "file": "GLM-5.3-Flash-GSQ-RCO-3.0bit-q4kattn.gguf"}, - # Unsloth's UD-IQ2_XXS: the whole model again, in the numbered files of a split GGUF. Its experts are i-quants, - # which go through the card faster and through the CPU more slowly than 3.0BIT's K-quants: on the 32 GB card - # it reads a 29K prompt at 1,060-1,080 tokens/s (3.0BIT: 820) and writes 50-52 tokens/s (59-66) - "UD-IQ2_XXS": {"about": "the whole model at about 2 bits (Unsloth): less RAM, reads faster, writes slower", - "download_gb": 101.8, "ram_gb": 82, "arena_gb": 92.5, "families": ("glm",), "shards": 4, - "file": "GLM-5.3-Flash-UD-IQ2_XXS-0000{i}-of-00004.gguf", "vram_beside_gb": 12.5, - "hf": hf("unsloth/GLM-5.3-Flash-GGUF") + "UD-IQ2_XXS/", "draft": "own"}, - # REAP50 (patrickbdevaney): 144 of each layer's 288 routed experts kept, so its experts are 72 GB. Expert - # numbers are its own: a profile of its own, and a draft block of its own, pruned with the layers - "REAP50-Q3_K_M": {"about": "half the routed experts (REAP50), 3-bit K-quant: less RAM", "download_gb": 78.8, - "ram_gb": 60, "arena_gb": 72.1, "families": ("glm",), "shards": 1, - "file": "GLM-5.3-Flash-REAP50-Q3_K_M.gguf", "vram_beside_gb": 11, - "hf": hf("patrickbdevaney/GLM-5.3-Flash-REAP50-GGUF"), - "profile": "expert-profile-glm-reap50.txt", "draft": "own"}, - # Unsloth's 4-bit file (docs/UNSLOTH_Q4.md); experimental until MODEL-UPDATE Phase 2. Its 77 GB of experts stay in - # RAM from ~94 GB of RAM (unsloth_budget); on a 64 GB PC the engine keeps a RAM budget of them - # (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD. It runs on AMD too (R9700: - # the quality yardstick and the decode/prompt numbers in docs/QUANTS.md), so it is no longer NVIDIA-only (#429). - "UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic): K-quant experts, between UD-IQ4_XS and UD-Q5_K_XL in quality", - "download_gb": 111.3, "ram_gb": 48, "arena_gb": 77.0, "families": ("unsloth",), "budget": True, - # #967 / MODEL-UPDATE: images run end to end with this file (CUDA: RTX A4000, GPU encoder; HIP: - # R9700, CPU encoder; the test picture's text and shapes as the IQ3_XXS pack answers them) - "vision": True}, - # MODEL-UPDATE: Unsloth's larger files (docs/QUANTS.md). The same GGUF-in-place mode: every expert in RAM where it - # fits with UNSLOTH_RESIDENT_BESIDE_GB more (unsloth_budget), else a RAM budget of them and the rest read from the - # SSD while it answers - so "ram_gb" is the all-in-RAM need, and below it setup asks first (default no). Their - # 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 - # 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). - "UD-Q5_K_XL": {"about": "5-bit (Unsloth Dynamic): Q5_K experts with Q8_0 downs, close to Q8_0 in quality", - "download_gb": 158.3, "ram_gb": 108, "arena_gb": 98.4, "families": ("unsloth",), "budget": True, - "shards": 6, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf", "engine": (0, 1, 44), - "vision": True}, - "UD-Q6_K_XL": {"about": "6-bit (Unsloth Dynamic): Q6_K experts with Q8_0 downs", - "download_gb": 169.2, "ram_gb": 118, "arena_gb": 109.2, "families": ("unsloth",), "budget": True, - "shards": 6, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf", "engine": (0, 1, 44), - "vision": True}, - "Q8_0": {"about": "8-bit, the reference quality (every expert Q8_0); for a 192 GB PC", - "download_gb": 188.2, "ram_gb": 136, "arena_gb": 128.3, "families": ("unsloth",), "budget": True, - "shards": 6, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf", "engine": (0, 1, 38), - "vision": True}, - # MODEL-UPDATE Phase 4: NVFP4 experts, ready-made packs (NVFP4_REPOS). 63.3 GiB (68.0 GB) of experts in the - # pack's experts.bin; the low-RAM mode reads them from there on a PC whose RAM does not hold them. NVIDIA only - # (the HIP and SYCL engines have no NVFP4 kernels). Images: both packs keep Qwen's vision tower unquantized, so the - # original's image encoder (ISTA's mmproj, the same file as for every Flash-Next model) reads pictures for them; - # checked end to end on an RTX 5070 and an RTX 3060 against IQ3_XXS's answers on the same picture. - "NVFP4": {"about": "4-bit NVFP4 experts, GPTQ (sergqwer's strata-nvfp4 pack); RTX 50 has FP4 tensor cores, other " - "NVIDIA cards run it at 8-bit precision", "download_gb": 128.0, "ram_gb": 80, "arena_gb": 68.0, - "families": ("nvfp4",), "nvidia_only": True, "vision": True, "repo": NVFP4_GPTQ_REPO, - "engine": NVFP4_ENGINE, - "license": "Qwen Community License 1.0 (Qwen3.8-Flash-Next's): https://huggingface.co/Qwen/Qwen3.8-Flash-Next"}, - "NVFP4-NVIDIA": {"about": "NVIDIA's own NVFP4 checkpoint (plain rounding), converted by sergqwer; the same size " - "and speed as NVFP4", "download_gb": 128.0, "ram_gb": 80, "arena_gb": 68.0, - "families": ("nvfp4",), "nvidia_only": True, "vision": True, "repo": NVFP4_NVIDIA_REPO, - "engine": NVFP4_ENGINE, - "license": "NVIDIA Open Model License (Licensed by NVIDIA Corporation under the NVIDIA Open Model " - "License) with Qwen3.8-Flash-Next's Qwen Community License 1.0: " - "https://huggingface.co/nvidia/Qwen3.8-Flash-Next-NVFP4"}, -} -# The experimental Unsloth file's four shards at the pinned revision: name -> (bytes, sha256), checked after the -# download (setup trusts no other model file by name and size alone either: check_shards reads their directories). -UNSLOTH_SHARDS = { - "Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf": - (10946624, "4448186216b3af4cc558bbce2c3213f01608f8f8b2e5267a9767971dd3ec8082"), - "Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf": - (49859583136, "3f342f1c1580473f1ee94ddd5b28206e8c07a70fa1a366f59d1d6c922919a6c9"), - "Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf": - (49376141504, "56758f40269cad5cd9b0d3d6fbae0f40f6d5be6de49e4ab392dbe83157d9cbd3"), - "Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf": - (12087983520, "753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a"), -} -# #621: UD-IQ4_XS's three shards at the same revision (sizes and SHA-256: the Hub's LFS pointers) -UNSLOTH_IQ4_XS_SHARDS = { - "Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf": - (10946624, "5ce89370720f8bf90890f439361282104c1aa1482d4013bb9a50923e758e71a4"), - "Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00003.gguf": - (49835229856, "577a38a2392b40ca2193cea502e1d92f60b8cd370675d308e0ec21885d9daaa7"), - "Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf": - (43836407744, "d4634e6d84f0ebb0940be15c90d3790bf6464e3dea3a1cddc567dc0e83ad8833"), -} -# 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 -# 2 and 3 are byte-identical across the three) -UNSLOTH_BIG_SHARDS = { - "Qwen3.8-Flash-Next-UD-Q5_K_XL-00001-of-00006.gguf": - (10946618, "610922cdb1afe1094e95d7a3e86b12ee33317ebbf7320ac9344e21b6ae4bb69f"), - "Qwen3.8-Flash-Next-UD-Q5_K_XL-00002-of-00006.gguf": - (682434912, "494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e"), - "Qwen3.8-Flash-Next-UD-Q5_K_XL-00003-of-00006.gguf": - (54400261312, "34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20"), - "Qwen3.8-Flash-Next-UD-Q5_K_XL-00004-of-00006.gguf": - (49990245824, "9ee6bbe462e6830864382d629101490625b1c95afa15492b7ad550c7bed2dd13"), - "Qwen3.8-Flash-Next-UD-Q5_K_XL-00005-of-00006.gguf": - (49882416192, "0b2437f661f584030cb5aeb8fb1bb70f6422518a6746bfcc0304167c7b6b8beb"), - "Qwen3.8-Flash-Next-UD-Q5_K_XL-00006-of-00006.gguf": - (3320101792, "55dd96c5ad0863b06b6393151b9ad0ac727b8d58a62e02a296ca5d5ddbfee4a3"), - "Qwen3.8-Flash-Next-UD-Q6_K_XL-00001-of-00006.gguf": - (10946624, "8bdc6bad55b6699f46f60708829932ff4018d7ac9bd309c388534fa31753bdb7"), - "Qwen3.8-Flash-Next-UD-Q6_K_XL-00002-of-00006.gguf": - (682434912, "494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e"), - "Qwen3.8-Flash-Next-UD-Q6_K_XL-00003-of-00006.gguf": - (54400261312, "34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20"), - "Qwen3.8-Flash-Next-UD-Q6_K_XL-00004-of-00006.gguf": - (49814108512, "0ea4b599880a5a52fcd9c188ba1443f646c69c96571904ddbd6a79246a01a997"), - "Qwen3.8-Flash-Next-UD-Q6_K_XL-00005-of-00006.gguf": - (49419317344, "9948e81ae8368144b135a7403d8c0f2cf9a6c2f9f692313865855b2832e696c9"), - "Qwen3.8-Flash-Next-UD-Q6_K_XL-00006-of-00006.gguf": - (14838313984, "e4ae255234f42b18012f6d6eec5bf615b57479b7e0a0233c47436a321ffeec3f"), - "Qwen3.8-Flash-Next-Q8_0-00001-of-00006.gguf": - (10946624, "2dabcbb53ca537a7947bc7d20414fd464eeaf4d66d43021b5b2556cc87544ad2"), - "Qwen3.8-Flash-Next-Q8_0-00002-of-00006.gguf": - (682434912, "494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e"), - "Qwen3.8-Flash-Next-Q8_0-00003-of-00006.gguf": - (54400261312, "34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20"), - "Qwen3.8-Flash-Next-Q8_0-00004-of-00006.gguf": - (49446841216, "bfa634025fabbd2658bf7694bc80b90e571699c768723f844c934c7ef06c691a"), - "Qwen3.8-Flash-Next-Q8_0-00005-of-00006.gguf": - (49668930400, "232a8f14cc0fa4262e7efe8593774b136fe40909e39c7a020342ddaa27259a97"), - "Qwen3.8-Flash-Next-Q8_0-00006-of-00006.gguf": - (34015618784, "538a93bca918064983409a41187ad4c68640f9aced6f29564da8f551bf86d7a5"), -} -UNSLOTH_ENGINE = (0, 1, 32) # the first engine setup configures for UD-Q4_K_XL (0.1.31 ran it by hand) -UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and the file cache the rest is read through -UNSLOTH_MIN_RAM_GB = 48 # the RAM-budget mode below which setup says an Unsloth file does not fit (UD-Q4_K_XL's floor) -# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will -# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor -# from the final context (final / 262144, at least 1) itself (below), keeps an explicit -# --rope-scaling/--rope-scale, and refuses an explicit --rope-scaling none there - the stock angles past -# the trained range are out of spec. -# 204800 (200K) sits between 128K and 256K: it is inside the trained 262144, so it needs no rope scaling and -# 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. -CONTEXTS = [8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288] -# The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. -FAMILIES = { - "qwen": {"title": "Qwen3.8-Flash-Next", "by": "Qwen; GSQ-RCO quants by ISTA-DASLab", - "about": "the original model", - "hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") + "{q}/", - "file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "", - "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), - "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next"}, - "swift": {"title": "Swift 1.5", "by": "UkisAI's fine-tune of Qwen3.8-Flash-Next", - "about": "thinks much shorter (-63% thinking tokens, 1.8x sooner answers by its authors' numbers)", - "hf": hf("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), - "file": "Swift-Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "swift-", - "mmproj_hf": hf("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), - "mmproj": "mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf", "name": "swift-1.5", - "license": "Swift Open License 1.0: https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"}, - # ISTA-DASLab's expert-pruned release: half of each layer's experts removed, chosen for code, agentic tool use and - # vision; its shard 2 (the n-gram table) and vision encoder are the original's files, shared with it - "coder": {"title": "Qwen3.8-Flash-Next Coder", "by": "ISTA-DASLab's coding version", - "about": "half the experts (code, tools, images kept): needs ~32 GB of RAM, faster; weaker outside coding", - "hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF") + "{q}/", - "file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "coder-", - "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF"), - "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-coder", - "profile": "expert-profile-coder.bin"}, - # 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 - # model (docs/QUANTS.md): regular choices since f-quants; the shard count and "vision" are per model (MODELS) - "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's 4- to 8-bit quantizations", - "about": "UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL or Q8_0 (94 to 188 GB downloads): every expert in " - "RAM from ~80 GB (UD-IQ4_XS) to ~136 GB (Q8_0) of RAM, else part of them read from the SSD", - "hf": hf("unsloth/Qwen3.8-Flash-Next-GGUF") + "{q}/", - "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf", "shards": 4, "tag": "unsloth-", - "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), - "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-unsloth", - "vision": True, "pack_args": ["--compat-bf16"], - "sha256": {**UNSLOTH_SHARDS, **UNSLOTH_IQ4_XS_SHARDS, **UNSLOTH_BIG_SHARDS}}, - # MODEL-UPDATE Phase 4: the original model with NVFP4 experts, as ready-made packs (NVFP4_REPOS): the files come - # as the engine reads them (no GGUF to pack), each size has its own repository ("repo" in MODELS) - "nvfp4": {"title": "Qwen3.8-Flash-Next (NVFP4)", "by": "NVFP4 packs by sergqwer (strata-nvfp4)", - "about": "4-bit NVFP4 experts, NVIDIA cards; a 128 GB download, ~80 GB of RAM to keep every expert in RAM", - "tag": "nvfp4-", "name": "qwen3.8-flash-next-nvfp4", "ready": True, - "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", - "mmproj_sha256": (907543008, "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0")}, - # GLM 5.3 Flash: another architecture (llama.cpp's glm5-next), run by strata-poly from its one GGUF - no pack, - # no image encoder. "engine": its setup is poly_setup, not main()'s steps (docs/GLM.md). "draft": the model's - # draft block in the data folder, one for every size whose file has none (tools/glm_draft_fetch.py) - "glm": {"title": "GLM 5.3 Flash", "by": "files from neuralll, Unsloth and patrickbdevaney", - "about": "another model, with its own engine: Linux, one NVIDIA card (run on 32 GB), 64-128 GB of RAM", - "hf": hf("neuralll/GLM-5.3-Flash-GSQ-RCO-3.0bit-Q4Kattn-GGUF"), - "file": "GLM-5.3-Flash-GSQ-RCO-3.0bit-q4kattn.gguf", "shards": 1, "tag": "glm-", - "name": "glm-5.3-flash", "engine": "poly", "vision": False, "experimental": True, - "profile": "expert-profile-glm.txt", - "draft": "mtp/glm-5.3-flash/draft-block.gguf", "draft_gb": 2.8, - "sha256": {"GLM-5.3-Flash-GSQ-RCO-3.0bit-q4kattn.gguf": - (113585695168, "5f03b74ffe7513479795ca60a0fd8c40cbb3101769672b2c91b3df01138d9f6d"), - "GLM-5.3-Flash-REAP50-Q3_K_M.gguf": - (78776759712, "5a865918aea87a362ff8ae419581a0447929bfd68534a44d1125b394c272762d"), - "GLM-5.3-Flash-UD-IQ2_XXS-00001-of-00004.gguf": - (9429888, "d9605eec5aa2c14fc9ccff1ba3341a1e9a1476b08714d41cd43d0e10a4db3f7a"), - "GLM-5.3-Flash-UD-IQ2_XXS-00002-of-00004.gguf": - (49896298080, "d51a3d9ca05022d53e71753df75ee64ed5fd4e47655650ae023e9717b3ec158d"), - "GLM-5.3-Flash-UD-IQ2_XXS-00003-of-00004.gguf": - (49248507840, "89180f13784dc1128586b98adf1ca876279881a20bc4f01747703ce352563372"), - "GLM-5.3-Flash-UD-IQ2_XXS-00004-of-00004.gguf": - (2690716000, "9e0ef47daa1fdffce3cf2ac1594ce4634d176ad018be6e692729757f38d5fbf6")}}, - # DeepSeek V4 Flash (llama.cpp's deepseek4) on strata-poly, from Unsloth's split GGUF; no draft block in it. Like - # GLM's sizes, "ram_gb" is poly_ram_need() for a 32 GB card and "vram_beside_gb" was measured there at 32K: it has - # run on an RTX 5090 with 120 GB of RAM only. "row_bytes": its caches keep compressed rows, 6,880 bytes a token. - "deepseek": {"title": "DeepSeek V4 Flash", "by": "DeepSeek; quantized by Unsloth", - "about": "another model on GLM's engine: Linux, one NVIDIA card (run on 32 GB), ~72 GB of RAM beside " - "it; a 91 GB download, no images", - "hf": hf("unsloth/DeepSeek-V4-Flash-0731-GGUF"), - "file": "DeepSeek-V4-Flash-0731-{q}-0000{i}-of-00003.gguf", "shards": 3, "tag": "dsv4-", "name": "deepseek-v4-flash", "engine": "poly", "vision": False, - "experimental": True, "row_bytes": 6880, - "models": {"UD-IQ2_XXS": {"about": "2-bit i-quant experts (Unsloth Dynamic), 3-bit and MXFP4 where " - "they write", "download_gb": 90.9, "ram_gb": 72, "arena_gb": 83.9, - "vram_beside_gb": 11.5, - "hf": hf("unsloth/DeepSeek-V4-Flash-0731-GGUF") + "UD-IQ2_XXS/"}}, - "sha256": {"DeepSeek-V4-Flash-0731-UD-IQ2_XXS-00001-of-00003.gguf": - (5257664, "c58c9d62eac7b62e9578b52613f425e48313d7212ab8d1d76caed8ea8de26595"), - "DeepSeek-V4-Flash-0731-UD-IQ2_XXS-00002-of-00003.gguf": - (49890588800, "65a113df6d4469f16db6882b6919e153c464c3c78c833f5e1b41a33803cdbd52"), - "DeepSeek-V4-Flash-0731-UD-IQ2_XXS-00003-of-00003.gguf": - (40964890464, "a69102ddfaf4a84426e11fdb66716654f4260dc3a1de3ade9fd50e006b8691d3")}}, - # The models strata-poly also runs, each from one GGUF (docs/BACKENDS.md): "engine": "poly" gives them - # poly_setup's steps. "models": the family's own sizes, as MODELS has them for the others: Unsloth calls a - # quantization the same for every model, so two families' sizes share a name. A size's "arena_gb" (its routed - # experts) is from its file, "vram_beside_gb" was measured on an RTX 5090 at 32K, and "row_bytes" is the VRAM a - # context token takes, measured from 8K to 131K there. "ram_gb" is poly_ram_need() for an 8 GB card. They ship - # no expert profile: the engine starts one. "draft_model": a file of the size's repository that guesses ahead - # for it, a model of its own; it is downloaded beside the model's and its VRAM is in "vram_beside_gb". - # "mmproj": the repository's image encoder, downloaded beside the model's file when images are wanted; - # "vision_vram_gb" is what it holds on the GPU once it has warmed up at 1,024 image tokens (measured there too). - # A family's first size is the one setup takes on a PC with the RAM for it, the second the one it takes with - # less, and the third is by name (poly_default()). "windows": installed by setup and run there, on one PC. - # "ran_on_gb": the smallest card it has run on, 32 GB without the key. "tail_skip": the engine's --tail-skip, - # for the family whose answers it moves no more than the Strata project's default moves its own (docs/BACKENDS.md). - # "laptop_tps": tokens/s written after a prompt that fills each context on the 8 GB laptop, where the family's - # differ from the others'. - # "batch_gb": the VRAM the engine's prompt batch takes for a second 1,024 tokens, measured on the RTX 5090; a card - # that holds every expert beside it reads with 2,048 (poly_batch()). "batch_from_gb": the family reads with 2,048 - # on any card from this much VRAM (GiB) on, where the 8 GB laptop read faster that way and wrote no slower. - # LFM2.5 (llama.cpp's lfm2moe): no draft block and no image encoder. QAD-Q4_0 is Liquid AI's own file, trained - # for that quantization; the other sizes are Unsloth's. - "lfm25": {"title": "LFM2.5-24B-A2B", "by": "Liquid AI; quantized by Unsloth and Liquid AI", - "about": "on the strata-poly engine: one NVIDIA card, Linux or Windows; a 15 GB file, ~20 GB of RAM " - "beside an 8 GB card; four other sizes too, no images", - "hf": hf("unsloth/LFM2.5-24B-A2B-GGUF"), "file": "LFM2.5-24B-A2B-{q}.gguf", "shards": 1, - "tag": "lfm25-", "name": "lfm2.5-24b-a2b", "engine": "poly", "vision": False, "experimental": True, - "windows": True, "ran_on_gb": 8, "row_bytes": 20480, "batch_gb": 0.4, "batch_from_gb": 7.5, - "laptop_tps": {32768: "69-74", 65536: "54-55", 131072: "35-37"}, - "models": {"UD-Q4_K_XL": {"about": "4-bit experts (Unsloth Dynamic), 5- and 6-bit where they write", - "download_gb": 14.9, "ram_gb": 20, "arena_gb": 14.0, "vram_beside_gb": 4.1}, - "UD-Q3_K_XL": {"about": "3-bit i-quant experts, 4-bit where they write: the least RAM", - "download_gb": 10.9, "ram_gb": 16, "arena_gb": 10.2, "vram_beside_gb": 3.9}, - "QAD-Q4_0": {"about": "Liquid AI's 4-bit file, trained for that quantization", - "download_gb": 13.6, "ram_gb": 18, "arena_gb": 12.9, "vram_beside_gb": 3.8, - "hf": hf("LiquidAI/LFM2.5-24B-A2B-GGUF")}, - "UD-Q6_K_XL": {"about": "6-bit experts, 8-bit where they write", - "download_gb": 21.9, "ram_gb": 27, "arena_gb": 20.9, "vram_beside_gb": 4.4}, - "Q8_0": {"about": "8-bit throughout: the closest to the model as trained", - "download_gb": 25.5, "ram_gb": 31, "arena_gb": 24.4, "vram_beside_gb": 4.5}}, - "sha256": {"LFM2.5-24B-A2B-UD-Q4_K_XL.gguf": - (14876901632, "a235d23638cc5549cb1ff61da7522c8a7e97f056f27093462a1e56f35aba91d8"), - "LFM2.5-24B-A2B-UD-Q3_K_XL.gguf": - (10947100928, "d54834c785c7e265f1cb7375e47aa6f55a0b7cfab75816254c4d2e0c82fd5efc"), - "LFM2.5-24B-A2B-QAD-Q4_0.gguf": - (13578190880, "d1c03f73ecaf61017d70419eec9e5dc0b05d50ae26c23d522829b934fbabf8a5"), - "LFM2.5-24B-A2B-UD-Q6_K_XL.gguf": - (21861204224, "abcb7e21e006eb4c826a2b75fb91c0804db7b20f908a61beeebdbdd07c88f41d"), - "LFM2.5-24B-A2B-Q8_0.gguf": - (25493733344, "97cd912b01124793a69ddebc309abbbad7ebb38ac2fb9c2bc55dfc1ad9d1809e")}}, - "qwen36": {"title": "Qwen3.6-35B-A3B", "by": "Qwen; quantized by Unsloth", - "about": "on the strata-poly engine: one NVIDIA card, Linux or Windows; a 17 GB file, ~21 GB of RAM " - "beside an 8 GB card; a smaller and a larger size too", - "hf": hf("unsloth/Qwen3.6-35B-A3B-MTP-GGUF"), "file": "Qwen3.6-35B-A3B-{q}.gguf", "shards": 1, - "tag": "qwen36-", "name": "qwen3.6-35b-a3b", "engine": "poly", "vision": True, "experimental": True, - "windows": True, "ran_on_gb": 8, "tail_skip": 6, "batch_gb": 0.5, - "row_bytes": 26624, "mmproj_hf": hf("unsloth/Qwen3.6-35B-A3B-MTP-GGUF"), "mmproj": "mmproj-F16.gguf", - "vision_gb": 0.9, "vision_vram_gb": 1.6, - "models": {"UD-Q3_K_M": {"about": "3-bit experts (Unsloth Dynamic), its draft block in the file", - "download_gb": 17.1, "ram_gb": 21, "arena_gb": 14.6, - "vram_beside_gb": 4.8, "draft": "own"}, - "UD-Q2_K_XL": {"about": "2- and 3-bit i-quant experts (Unsloth Dynamic): the least RAM", - "download_gb": 12.6, "ram_gb": 17, "arena_gb": 10.8, - "vram_beside_gb": 4.2, "draft": "own"}, - "UD-Q4_K_M": {"about": "4-bit experts (Unsloth Dynamic), 5- and 6-bit where they write", - "download_gb": 22.7, "ram_gb": 27, "arena_gb": 20.1, - "vram_beside_gb": 4.7, "draft": "own"}}, - "sha256": {"Qwen3.6-35B-A3B-UD-Q3_K_M.gguf": - (17104402720, "8966dd0cd8c543c4228490a2a8b0e0814fc4f1e6a8e199ceed4de6754ae7b8e1"), - "Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf": - (12574128416, "ed7cda7e38985b4fcff76475865135039641d2bfbac3c169df15ca770f37fb0c"), - "Qwen3.6-35B-A3B-UD-Q4_K_M.gguf": - (22663387424, "0b21525e972670ed59e1812e170b27c26355381f0656ecc4e25617ece7dac58b"), - "mmproj-F16.gguf": - (899283584, "71f3cbc1f7cc0f30d09d41cfa924c0060827ebc33bf15ace7e86661e856f0160")}}, - "ornith": {"title": "Ornith 1.5 35B-A3B", "by": "ornith-ai; APEX quantization by mudler", - "about": "Qwen3.6-35B-A3B's architecture, other weights; a 17 GB file, ~22 GB of RAM beside an 8 GB card; " - "a smaller and a larger size too", - "hf": hf("mudler/Ornith-1.5-35B-A3B-APEX-MTP-GGUF"), "file": "Ornith-1.5-35B-A3B-{q}.gguf", - "shards": 1, "tag": "ornith-", "name": "ornith-1.5-35b-a3b", "engine": "poly", "vision": True, - "experimental": True, "windows": True, "ran_on_gb": 8, "row_bytes": 26624, - "mmproj_hf": hf("mudler/Ornith-1.5-35B-A3B-APEX-MTP-GGUF"), "mmproj": "mmproj.gguf", "vision_gb": 0.9, - "vision_vram_gb": 1.6, - "models": {"APEX-I-COMPACT": {"about": "3- and 4-bit K-quant experts (APEX), its draft block in the file", - "download_gb": 17.4, "ram_gb": 22, "arena_gb": 15.8, - "vram_beside_gb": 4.2, - "file": "Ornith-1.5-35B-A3B-APEX-MTP-I-Compact.gguf", "draft": "own"}, - "APEX-I-MINI": {"about": "2- and 3-bit experts (APEX): the least RAM", - "download_gb": 14.4, "ram_gb": 18, "arena_gb": 12.9, - "vram_beside_gb": 3.9, - "file": "Ornith-1.5-35B-A3B-APEX-MTP-I-Mini.gguf", "draft": "own"}, - "APEX-I-QUALITY": {"about": "4- to 6-bit experts (APEX)", - "download_gb": 23.7, "ram_gb": 28, "arena_gb": 21.6, - "vram_beside_gb": 4.4, - "file": "Ornith-1.5-35B-A3B-APEX-MTP-I-Quality.gguf", "draft": "own"}}, - "sha256": {"Ornith-1.5-35B-A3B-APEX-MTP-I-Compact.gguf": - (17437861408, "67e6cdff678e67180d3cd4eef55277277563319057de287b8855c4d1fbff4165"), - "Ornith-1.5-35B-A3B-APEX-MTP-I-Mini.gguf": - (14366220832, "09c342594abf0cb0cda9e899977956b61e37da79b5e5ffbe77874512dbe78148"), - "Ornith-1.5-35B-A3B-APEX-MTP-I-Quality.gguf": - (23718411808, "2cedb760ebafb9f4943b4eac92628306110fc04eeea45dae2e1396aad626e691"), - "mmproj.gguf": - (899283200, "e277123529451fbcff6d880ad5bd7ada999f9d5e6339ba3639d06c5cef4763b1")}}, - "gemma4": {"title": "Gemma 4 26B-A4B", "by": "Google; quantized by Unsloth", - "about": "on the strata-poly engine too; a 13 GB file, ~18 GB of RAM beside an 8 GB card; a smaller and a " - "larger size too", - "hf": hf("unsloth/gemma-4-26B-A4B-it-GGUF"), "file": "gemma-4-26B-A4B-it-{q}.gguf", "shards": 1, - "tag": "gemma4-", "name": "gemma-4-26b-a4b", "engine": "poly", "vision": True, "experimental": True, - "windows": True, "ran_on_gb": 8, - "row_bytes": 28672, "mmproj_hf": hf("unsloth/gemma-4-26B-A4B-it-GGUF"), "mmproj": "mmproj-F16.gguf", - "vision_gb": 1.2, "vision_vram_gb": 2.4, "vision_most": 1024, - "models": {"UD-Q3_K_M": {"about": "3-bit experts (Unsloth Dynamic), and Google's draft model for it", - "download_gb": 13.2, "ram_gb": 18, "arena_gb": 10.3, - "vram_beside_gb": 5.8, - "draft_model": "MTP/mtp-gemma-4-26B-A4B-it-Q8_0.gguf"}, - "UD-Q2_K_XL": {"about": "2-bit i-quant experts (Unsloth Dynamic): the least RAM; the same " - "draft model", - "download_gb": 11.0, "ram_gb": 15, "arena_gb": 8.7, - "vram_beside_gb": 4.6, - "draft_model": "MTP/mtp-gemma-4-26B-A4B-it-Q8_0.gguf"}, - "UD-Q4_K_M": {"about": "4- and 5-bit experts (Unsloth Dynamic); the same draft model", - "download_gb": 17.4, "ram_gb": 21, "arena_gb": 14.3, - "vram_beside_gb": 5.3, - "draft_model": "MTP/mtp-gemma-4-26B-A4B-it-Q8_0.gguf"}}, - "sha256": {"gemma-4-26B-A4B-it-UD-Q3_K_M.gguf": - (12728497888, "811882f6df81c8ea204a5d382f196d6bd601245091786912d4c70df41cdfa052"), - "gemma-4-26B-A4B-it-UD-Q2_K_XL.gguf": - (10546934240, "2a1d26dfe6ea00a467940a5728316af6edb366bbdba950d65b85d232392fb658"), - "gemma-4-26B-A4B-it-UD-Q4_K_M.gguf": - (16947541728, "f2c28b3dc4776931ac6f879e11f203dec637ea0f14267a86ec8f6165f63f293f"), - "mtp-gemma-4-26B-A4B-it-Q8_0.gguf": - (461766816, "6326fb9f5e487aa8dcdd313a091e3c67724cb2a666ec3b7d2895b5b26d93ed1b"), - "mmproj-F16.gguf": - (1193058784, "418a6d8723067cd712235facbbc5cba6c8fbbd413fc1292d2aace5a027d5a42f")}}, - "tiel": {"title": "Tiel Coder 35B-A3B", "by": "peculiar-ragdoll, from ornith-ai's Ornith 1.5", - "about": "Ornith 1.5 quantized for coding, with the Sharp chat template; a 17 GB file, ~21 GB of RAM " - "beside an 8 GB card; a smaller and a larger size too", - "hf": hf("peculiar-ragdoll/Tiel-Coder-35B-A3B-GGUF-MTP"), "file": "Tiel-Coder-35B-A3B-MTP-{q}.gguf", - "shards": 1, "tag": "tiel-", "name": "tiel-coder-35b-a3b", "engine": "poly", "vision": True, - "experimental": True, "windows": True, "ran_on_gb": 8, "row_bytes": 26624, - "mmproj_hf": hf("peculiar-ragdoll/Tiel-Coder-35B-A3B-GGUF-MTP"), "mmproj": "mmproj-BF16.gguf", - "vision_gb": 0.9, "vision_vram_gb": 1.6, - "models": {"UD-Q3_K_XL": {"about": "3-bit i-quant experts, 4-bit where they write; its draft block in " - "the file", - "download_gb": 17.2, "ram_gb": 21, "arena_gb": 14.6, - "vram_beside_gb": 4.7, "draft": "own"}, - "UD-IQ3_XXS": {"about": "2-bit i-quant experts, 3-bit where they write: the least RAM", - "download_gb": 13.6, "ram_gb": 18, "arena_gb": 11.5, - "vram_beside_gb": 4.4, "draft": "own"}, - "UD-Q4_K_XL": {"about": "4-bit experts, 5- and 6-bit where they write", - "download_gb": 22.7, "ram_gb": 27, "arena_gb": 20.0, - "vram_beside_gb": 4.8, "draft": "own"}}, - "sha256": {"Tiel-Coder-35B-A3B-MTP-UD-Q3_K_XL.gguf": - (17234935648, "46b8fbeba6e888c9a101e49cc717baa9bb8dfa0d203ec7b3185288159543ec14"), - "Tiel-Coder-35B-A3B-MTP-UD-IQ3_XXS.gguf": - (13600579424, "a4d8ffc7f030466c67db289543871a8f9e6d5340241b300c09fbaf16642273ca"), - "Tiel-Coder-35B-A3B-MTP-UD-Q4_K_XL.gguf": - (22749880160, "54f46c4ce544c225122b0f066c2336f10404be7bc53b0cc94d1dbbc5e826bdc1"), - "mmproj-BF16.gguf": - (902822016, "d9ce31026d1cb1f3f8d5152e2e2a014d9d2b302b6c93a7dc07bb0a0487f52837")}}, - # The same architecture as Qwen3.6, OpenBMB's weights: 40 layers of 256 experts, 8 to a token, and a picture - # encoder of its own: MiniCPM-V 4.6's under the newer name minicpmv4_7, which the pinned llama.cpp answers - # (#29416). The files carry no draft block, so no size has "draft"; its answers are one token at a - # time. "vram_beside_gb" and the smallest size's RAM were measured on an RX 7600 (8 GB) at 32K; - # "vision_vram_gb" is Qwen3.6's grown by the size of this mmproj, as the encoder ran on the CPU here. - "minicpmv": {"title": "MiniCPM-V 4.7 35B-A3B", "by": "OpenBMB", - "about": "Qwen3.6-35B-A3B's architecture, OpenBMB's weights, and it reads pictures too; a 22 GB " - "file, ~25 GB of RAM beside an 8 GB card; a smaller and a larger size too", - "hf": hf("openbmb/MiniCPM-V-4.7-35B-A3B-gguf"), "file": "MiniCPM-V-4_7-35B-A3B-{q}.gguf", - "shards": 1, "tag": "minicpmv-", "name": "minicpm-v-4.7-35b-a3b", "engine": "poly", "vision": True, - "experimental": True, "windows": True, "ran_on_gb": 8, "row_bytes": 26624, - "mmproj_hf": hf("openbmb/MiniCPM-V-4.7-35B-A3B-gguf"), "mmproj": "mmproj-model-f16.gguf", - "vision_gb": 1.1, "vision_vram_gb": 2.0, - "models": {"Q4_K_M": {"about": "4-bit experts (K-quant), 5- and 6-bit where they write", - "download_gb": 21.2, "ram_gb": 25, "arena_gb": 19.5, "vram_beside_gb": 3.4}, - "mix_q3gud_im": {"about": "3- and 4-bit experts (imatrix mix): the least RAM", - "download_gb": 15.5, "ram_gb": 19, "arena_gb": 13.8, - "vram_beside_gb": 3.4}, - "Q6_K": {"about": "6-bit experts (K-quant)", - "download_gb": 28.5, "ram_gb": 31, "arena_gb": 26.4, "vram_beside_gb": 3.4}}, - "sha256": {"MiniCPM-V-4_7-35B-A3B-Q4_K_M.gguf": - (21166255040, "c729ae6c7bb16dd5b362cdb925c7fb09d744c95601f62b0f45ce51efb55bfe95"), - "MiniCPM-V-4_7-35B-A3B-mix_q3gud_im.gguf": - (15503944928, "6bfeefbfc723ab6fe557fcea28b31253e14128efe8d8d5774e3256a547b3a946"), - "MiniCPM-V-4_7-35B-A3B-Q6_K.gguf": - (28513556672, "159ce7d2fe4aab95233096ad007c23d86d99dd6c4a20d3f7c31e990d09aa71b7"), - "mmproj-model-f16.gguf": - (1119575840, "bff3b688e14c300eca273092c37c50a0ddfcc2054e079af1a0480edeed5d20f1")}}, -} -MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" -# Qwen3.6-35B-A3B (GGUF architecture qwen35moe), Unsloth's GGUFs with the MTP block: a family with an engine path of its -# own (src/qwen35; `strata` switches to it from the file's architecture). No pack, no expert profile, no separate MTP -# draft layer: the engine reads the GGUF as it is, keeps every expert it can in VRAM and computes the rest on the CPU -# (the hybrid mode), and drafts with the file's own MTP block. Not in FAMILIES (whose entries are Flash-Next files with -# packs): OWN_PATH_FAMILIES, offered in the same menu and installed by install_own_path. NVIDIA (CUDA) and AMD (HIP) -# only: the Intel Arc (SYCL) engine refuses it. -QWEN36_FILES = { - "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf": (22853663008, "55983c5a75a1ab969824077b3bb3de4146e82a9234072b48ad4e8f92ad3fe9f1"), - "Qwen3.6-35B-A3B-UD-Q6_K_XL.gguf": (32611711264, "35fce994cd36104a7dc1bd8a4bdf13778145664c00fdef6773aebc9246e5019c"), - "Qwen3.6-35B-A3B-Q8_0.gguf": (37801097504, "c1283d8b80c3e38b2735ddbc9766d3b3126f44d6c484be419d4e101d09a76131"), - "mmproj-F16.gguf": (899283584, "71f3cbc1f7cc0f30d09d41cfa924c0060827ebc33bf15ace7e86661e856f0160"), -} -# PolyStrata: FAMILIES has "qwen36" too (the strata-poly engine, smaller sizes for 8 GB cards), so this one is -# "qwen36-strata", with a tag of its own: choices_from_config() tells the two families' configs apart by the tag. -OWN_PATH_FAMILIES = { - "qwen36-strata": {"title": "Qwen3.6-35B-A3B", "by": "Qwen; GGUFs with the MTP layer by Unsloth", "arch": "qwen35moe", - "about": "on the Strata project's own engine (4- to 8-bit, 32 GB of RAM or more): 35B mixture of experts " - "with 3B active (256 experts, top-8), a smaller cousin of Qwen3.8-Flash-Next with the same " - "tokenizer", - "hf": hf("unsloth/Qwen3.6-35B-A3B-MTP-GGUF"), "file": "Qwen3.6-35B-A3B-{q}.gguf", "tag": "qwen36s-", - "mmproj_hf": hf("unsloth/Qwen3.6-35B-A3B-MTP-GGUF"), "mmproj": "mmproj-F16.gguf", - "name": "qwen3.6-35b-a3b", "license": "Apache 2.0: https://huggingface.co/Qwen/Qwen3.6-35B-A3B", - # RAM: the engine keeps a copy of every expert in RAM when they do not all fit in VRAM (the hybrid mode), - # 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 - # card, 18.75 GiB of experts pinned) - "models": {"UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), the smallest", "ram_gb": 32}, - "UD-Q6_K_XL": {"about": "6-bit (Unsloth Dynamic), closer to the full model", "ram_gb": 44}, - "Q8_0": {"about": "8-bit, the closest to the full model", "ram_gb": 52}}, - "sha256": QWEN36_FILES, - # the engine's KV cache per context token: 10 attention layers + the MTP block, 2 KV heads x 256, K and - # V in fp32 (strata-q36) - "kv_bytes_per_token": 11 * 2 * 256 * 2 * 4, - "mtp": 2, # drafts per step (greedy requests): measured best on the R9700 - # pictures: Unsloth's mmproj (the same projector family as Flash-Next's: qwen3vl_merger) through - # strata-vision; a parallel slot's session: its KV cache (kv_bytes_per_token) and the recurrent state of - # the 30 GDN layers (state_gb) - "vision": True, "state_gb": 0.07} -} -PREVIEW_FAMILIES = OWN_PATH_FAMILIES # the earlier name (tools and tests that import it) -# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README -ESP_VECTOR = ROOT / "data" / "experimental-speed-projection" / "Qwen3.8-Flash-Next-experimental-speed-projection.gguf" -# the image encoder on the GPU (~1.2 GB at 1024 image tokens) warms up before the engine starts, so the engine -# sizes its expert slots around it and the default reserve (700 MiB) is enough; engines before 0.1.2 need more -VISION_GPU_SMALL_RESERVE_MIB = 1000 # the tip for images on a <= 12 GB card (the engine's LOW line asked ~1003) -VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 700}, - "cpu": {"max_tokens": 300, "reserve_mib": 700}} -EXE = "strata.exe" if WIN else "strata" -VEXE = "strata-vision.exe" if WIN else "strata-vision" -# The engine of GLM 5.3 Flash and of the models that are read from one GGUF (docs/BACKENDS.md), in a folder of its -# own like the CUDA 12 engine's, so the ready-made engine beside it stays as it was downloaded. On Windows it comes -# ready-made when the latest release was built from this checkout's engine source, and is compiled here otherwise. -# It was called strata-glm, after its first model, and an install from then has that name and folder in its run -# config (poly_config(), update_poly_engine()). -POLY_EXE = "strata-poly.exe" if WIN else "strata-poly" -# The ready-made one (tools/make_poly_release.py): an asset named after the source_hash() of the engine and the -# encoder in it (poly_asset()), so a checkout finds the build of its own source or none. STRATA_POLY_PREBUILT_URL: -# another folder, a local one too. -POLY_PREBUILT_URL = os.environ.get("STRATA_POLY_PREBUILT_URL", - "https://github.com/VecSzn/PolyStrata/releases/latest/download/") -POLY_ASSET = "strata-poly-windows-x64-{src}.zip" -# A model of strata-poly that reads pictures has its image encoder on the GPU from this much VRAM (GiB), and on the -# CPU below it: the encoder holds 1.6 to 2.4 GB there, which a smaller card needs for the model -POLY_VISION_GPU_GB = 15.5 -ENGINE_POLY_DIR = "engine-poly" -OLD_POLY_EXE = "strata-glm.exe" if WIN else "strata-glm" -OLD_ENGINE_POLY_DIR = "engine-glm" -POLY_CONTEXTS = [8192, 32768, 65536, 131072] -GLM_ROW_BYTES = 28160 # VRAM per context token: a row in each of the 11 sparse attention layers' caches -GLM_VRAM_BESIDE_GB = 12 # what is not expert cache on a 32 GB card at 32K (weights, caches, buffers, reserve): - # the 3.0BIT file's; a size with other dense weights has its own "vram_beside_gb" -POLY_RAM_BESIDE_GB = 10 # RAM beside the experts in the file cache: the OS, the server, the engine's buffers -POLY_CONV_CACHE_MIB = 8192 # --conversation-cache-mib when setup turns it on -# 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 -# engine, opened only for those models; an engine without it runs them on the FP16 prompt path -KQ_LIB = "strata_kq.dll" if WIN else "libstrata_kq.so" - - -# ------------------------------------------------------------------------------------------------ output -def say(msg=""): - print(msg, flush=True) - - -def step(n, title): - say() - say(f"=== Step {n}: {title} ===") - - -def ok(msg): - say(f" [ok] {msg}") - - -def warn(msg): - say(f" [!] {msg}") - - -def fail(msg, hint=None): - say(f"\n [X] {msg}") - if hint: - say(f" {hint}") - say("\nSetup stopped. Fix the item above and run it again - everything already done is kept and skipped.") - sys.exit(1) - - -def flush_typed_ahead() -> None: - """#841: keys pressed while setup was busy (a download, a build) are not answers to the next question: Enter pressed - to "wake" a slow step answered "Go on anyway?" with its default. Dropped before a question is asked, on a terminal - only (a pipe or a test keeps its input).""" - try: - if not sys.stdin.isatty(): - return - if WIN: - import msvcrt - while msvcrt.kbhit(): - msvcrt.getwch() - else: - import termios - termios.tcflush(sys.stdin.fileno(), termios.TCIFLUSH) - except (ImportError, OSError, ValueError, AttributeError): - pass - - -def ask(question, choices, default, yes): - if yes: - return default - flush_typed_ahead() - while True: - try: - a = input(f"{question} [{default}]: ").strip() - except EOFError: - fail("input ended before a setup answer was received", - "run setup in a terminal, or pass --yes to accept the recommended answers") - if not a: - return default - if a.lower() in [c.lower() for c in choices]: - return next(c for c in choices if c.lower() == a.lower()) - say(f" please answer one of: {', '.join(choices)}") - - -def run(cmd, cwd=None, env=None, check=True, quiet=False): - say(" > " + " ".join(str(c) for c in cmd)) - r = subprocess.run([str(c) for c in cmd], cwd=cwd, env=env, - stdout=subprocess.PIPE if quiet else None, stderr=subprocess.STDOUT if quiet else None, - text=True) - if check and r.returncode != 0: - if quiet and r.stdout: - say(r.stdout[-4000:]) - fail(f"command failed (exit {r.returncode}): {Path(str(cmd[0])).name}") - return r - - -def out(cmd): - try: - return subprocess.run(cmd, capture_output=True, text=True, timeout=60).stdout - except (OSError, subprocess.TimeoutExpired): - return "" - - -def done(path: Path) -> bool: - """A step's finish mark: .done exists (written only after the step completed).""" - return path.with_name(path.name + ".done").exists() - - -def mark(path: Path, text=""): - """Write the finish mark. A folder that cannot be written (--gguf-dir on a read-only share, #570) only costs the - mark: setup says so and goes on (the step is repeated on the next run), it does not stop.""" - try: - path.with_name(path.name + ".done").write_text(text or time.strftime("%Y-%m-%d %H:%M"), encoding="utf-8") - except OSError as e: - warn(f"the finish mark of {path.name} cannot be written ({e}): the next run does this step again") - - -# ------------------------------------------------------------------------------------------------ the PC -def _memory_status(): - """Windows' GlobalMemoryStatusEx: RAM, and the commit limit (ullTotalPageFile = RAM + page file).""" - class MS(ctypes.Structure): - _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), - ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), - ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), - ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), - ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] - m = MS() - m.dwLength = ctypes.sizeof(MS) - ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)) - return m - - -def container_ram_gb(): - """A container's memory limit in GB, None without one (Linux cgroup v2).""" - try: - v = open("/sys/fs/cgroup/memory.max").read().strip() - except OSError: - return None - return int(v) / 2**30 if v.isdigit() else None - - -def ram_gb(): - if WIN: - return _memory_status().ullTotalPhys / 2**30 - for line in open("/proc/meminfo"): - if line.startswith("MemTotal"): - # inside a container this is the host's RAM: a pod with 120 GB of a 1 TB machine reads 1 TB - return min(int(line.split()[1]) * 1024 / 2**30, container_ram_gb() or float("inf")) - return 0.0 - - -_MM_KEY = r"SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" - - -def _mm_multi_sz(name): - """A REG_MULTI_SZ value of Memory Management, None when it cannot be read. PagingFiles is what the Virtual memory - dialog set; ExistingPageFiles is where the page files are now.""" - try: - import winreg - with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _MM_KEY) as k: - v, _t = winreg.QueryValueEx(k, name) - except (ImportError, OSError): - return None - return [x for x in v if x] if isinstance(v, list) else None - - -def parse_paging_file(line: str): - """One PagingFiles entry ("C:\\pagefile.sys 16000 64000", "C:\\pagefile.sys 0 0", "?:\\pagefile.sys"): (drive, - initial MB, maximum MB), both -1 when Windows manages the size and the drive '?' when it manages every drive; - None for anything else.""" - s = line.strip() - if len(s) < 2 or s[1] != ":": - return None - parts = s.split() - try: - initial, maximum = (int(parts[1]), int(parts[2])) if len(parts) >= 3 else (-1, -1) - except ValueError: - initial, maximum = -1, -1 - if maximum <= 0: - initial, maximum = -1, -1 - return s[0].upper(), initial, maximum - - -PAGE_FILE_FIXED_MB = 65536 # the advice: a fixed size (initial = maximum) of 64 GB, the size #60's PC started with - - -def _drive_mb(drive: str): - """(free MB, the page file's size now in MB) of a drive, None when it cannot be read. The page file is locked: - its size comes from the directory entry.""" - root = f"{drive}:\\" - try: - du = shutil.disk_usage(root) - except OSError: - return None - current = 0 - try: - with os.scandir(root) as it: - for e in it: - if e.name.lower() == "pagefile.sys": - current = e.stat(follow_symlinks=False).st_size - break - except OSError: - pass - return du.free / 2**20, current / 2**20 - - -def page_file_setting(): - """The page files Windows is set to use (PagingFiles, what the Virtual memory dialog writes): [(drive, initial MB, - maximum MB, MB now, the drive's free MB)], the sizes -1 for a system-managed file; "?:" (every drive automatic) is - the drive ExistingPageFiles names. None off Windows or when the setting cannot be read.""" - if not WIN: - return None - lines = _mm_multi_sz("PagingFiles") - if lines is None: - return None - auto = [] # "?:\pagefile.sys": where Windows keeps it now, else C: - for s in _mm_multi_sz("ExistingPageFiles") or []: - i = s.find(":") - if i > 0: - auto.append(s[i - 1].upper()) - auto = auto or [(os.environ.get("SystemDrive") or "C:")[0].upper()] - files = [] - for line in lines: - e = parse_paging_file(line) - if e is None: - continue - drive, initial, maximum = e - for d in (auto if drive == "?" else [drive]): - free, now = _drive_mb(d) or (0.0, 0.0) - files.append((d, initial, maximum, now, free)) - return files - - -def page_file_grows(files) -> bool: - """Whether Windows grows one of these page files on demand: system-managed, or an initial size below the maximum.""" - return any(maximum <= 0 or initial < maximum for _d, initial, maximum, _now, _free in files or []) - - -def page_file_gb(): - """The page files' size (GB) that is there for sure on Windows, None elsewhere. The graphics card's memory needs - room there too: under Windows' driver model every allocation on the card is also charged to the commit (RAM + page - file), so with the page file off or tiny the engine cannot use the free VRAM (issue #60). What counts is the size - the files have now (the commit limit minus RAM), or a file's configured initial size when that is larger (within - its drive's free space) - never what a file may grow to: a page file Windows grows on demand may not grow in time - while the card's memory is charged (#60: "System managed" and 4096-32768 MB still failed, a fixed 64 GB worked).""" - if not WIN: - return None - m = _memory_status() - mb = max(0.0, (m.ullTotalPageFile - m.ullTotalPhys) / 2**20) - files = page_file_setting() - if files: - mb = max(mb, sum(max(now, min(max(initial, 0), now + free)) for _d, initial, _m, now, free in files)) - return mb / 1024 - - -def page_file_advice(pf: float, files) -> str: - """Step 1's warning for a page file below 4 GB (issue #60): a fixed size, and why when the setting (`files`, - page_file_setting) has Windows grow it on demand.""" - grows = ("It is set to grow on demand (\"System managed\" or an initial size below the maximum), and a growing " - "page file may not grow in time for the card's memory (#60: \"System managed\" and 4096-32768 MB still " - "failed, a fixed 64 GB worked). ") if page_file_grows(files) else "" - return (f"Windows' page file is {pf:.1f} GB: the graphics card's memory needs room there too (issue #60), so the " - f"model may not start or may use less VRAM. {grows}Set a fixed size: System > About > Advanced system " - "settings > Performance > Advanced > Virtual memory > Change, untick \"Automatically manage\", Custom size " - f"with initial and maximum size {PAGE_FILE_FIXED_MB} MB, Set, then restart Windows") - - -def cpu_cores(): - """#642: (performance cores, efficiency cores) of a hybrid CPU (Intel 12th gen+, AMD Zen 5 + Zen 5c), counted - as the engine's pool counts them (detect_cpu_topology: physical cores, by Windows' EfficiencyClass or Linux's - cpu_capacity); None on a CPU whose cores are all alike, or when the OS does not say.""" - classes = [] # one entry per physical core: its efficiency/capacity class - try: - if WIN: - k32 = ctypes.windll.kernel32 - n = ctypes.c_ulong(0) - k32.GetLogicalProcessorInformationEx(0, None, ctypes.byref(n)) # RelationProcessorCore: the size - if not n.value: - return None - buf = ctypes.create_string_buffer(n.value) - if not k32.GetLogicalProcessorInformationEx(0, buf, ctypes.byref(n)): - return None - raw, at = buf.raw[:n.value], 0 - while at + 10 <= len(raw): # SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX: Relationship, Size, then - rel, size = struct.unpack_from("= top * 9 else 0 for c in classes] - return classes - - -def cpulist(text: str) -> set: - """A kernel cpulist ("0-7,16") as a set of CPU numbers.""" - out = set() - for part in text.strip().split(","): - lo, _, hi = part.strip().partition("-") - if lo.isdigit(): - out.update(range(int(lo), int(hi or lo) + 1)) - return out - - -def linux_hybrid_pmu(root: str = "/sys/devices"): - """#798: (P-core CPUs, E-core CPUs) from Intel's hybrid PMU lists (cpu_core/cpus, cpu_atom/cpus), or None on a CPU - that has no such lists.""" - try: - p = cpulist((Path(root) / "cpu_core" / "cpus").read_text(encoding="utf-8")) - e = cpulist((Path(root) / "cpu_atom" / "cpus").read_text(encoding="utf-8")) - except OSError: - return None - return (p, e) if p and e else None - - -def hybrid_pool_workers(cores) -> int | None: - """#642 (Hardin22's measurement): on a hybrid CPU the expert pool runs best on the P-cores but the host loop's one - plus HALF of the E-cores - an E-core runs the expert kernels ~2.2x slower and each layer waits for its slowest - part (i9-14900KF, 8P + 16E: 15 workers decoded 165 / 116 tok/s against 106 / 84 with all 23). Only on a CPU with - more E-cores than P-cores: on an i7-13700KF (8P + 8E, docs/AMD_HIP.md's gfx1030 report) all 15 workers decoded - 38-42 tok/s against 36 with 8, so there the engine's own count stays. None: the engine's own default (one worker - per physical core but the host's) stays.""" - if not cores: - return None - p, e = cores - if e <= p: - return None - return max(1, p - 1 + e // 2) - - -def recommend_pool_workers(args: list) -> list: - """`args` with setup's recommended `--pool-workers` for a hybrid CPU, unless they set one already (a calibration's - measured count, or the user's own). A recommendation: the config line can be edited or removed.""" - n = hybrid_pool_workers(cpu_cores()) - if n is None or "--pool-workers" in args: - return args - p, e = cpu_cores() - ok(f"hybrid CPU ({p} performance + {e} efficiency cores): {n} CPU expert workers - the performance cores and half " - "of the efficiency cores (--pool-workers in the config; START-HERE --calibrate measures it on this PC)") - return [*args, "--pool-workers", str(n)] - - -def linux_sockets(sys_root: str = "/sys"): - """(sockets, physical cores per socket) from the kernel's topology files, or None when they do not say.""" - cores = {} - for cpu in (Path(sys_root) / "devices" / "system" / "cpu").glob("cpu[0-9]*"): - pkg, core = cpu / "topology" / "physical_package_id", cpu / "topology" / "core_id" - try: - cores.setdefault(pkg.read_text(encoding="utf-8").strip(), set()).add(core.read_text(encoding="utf-8").strip()) - except OSError: - return None - return (len(cores), min(len(c) for c in cores.values())) if cores else None - - -def cpu_sockets(): - """(sockets, physical cores per socket); None when unknown. Windows: the packages and cores that - GetLogicalProcessorInformationEx lists (RelationProcessorPackage 3, RelationProcessorCore 0).""" - try: - if not WIN: - return linux_sockets() - k32 = ctypes.windll.kernel32 - counts = {} - for rel in (0, 3): - n = ctypes.c_ulong(0) - k32.GetLogicalProcessorInformationEx(rel, None, ctypes.byref(n)) - if not n.value: - return None - buf = ctypes.create_string_buffer(n.value) - if not k32.GetLogicalProcessorInformationEx(rel, buf, ctypes.byref(n)): - return None - raw, at, c = buf.raw[:n.value], 0, 0 - while at + 8 <= len(raw): - size = struct.unpack_from(" list[str]: - """Bench #674 #707 (2-socket Xeons: 17-18 workers beat 35 by ~20%): a tip to keep the expert pool on one socket's - cores, one fewer for the host loop. Nothing is written to the config.""" - if not sockets or sockets[0] < 2 or sockets[1] < 3: - return [] - n = sockets[1] - 1 - return [f"tip: this PC has {sockets[0]} CPU sockets of {sockets[1]} cores. Expert workers on the other socket have " - f"been measured slower than fewer, local ones (35 vs 17-18 on 2-socket Xeons): try --pool-workers {n} in " - "the config's args (START-HERE --calibrate measures it on this PC)"] - - -def cpu_info(): - """(name, avx2, avx512): avx512 means everything PolyStrata's fast AVX-512 kernels use (F, BW, VL, VNNI, VBMI), - the same test the engine makes (cpu_avx512_ok), not just AVX-512F.""" - name, avx2, avx512 = platform.processor() or "unknown CPU", False, False - if WIN: - pf = ctypes.windll.kernel32.IsProcessorFeaturePresent - avx2 = bool(pf(40)) or _cpuid_avx2() # PF_AVX2_INSTRUCTIONS_AVAILABLE, else the CPU itself (#159) - n = out(["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_Processor).Name"]).strip() - name = n or name - avx512 = bool(pf(41)) and _cpuid_avx512_full() - else: - try: - txt = open("/proc/cpuinfo").read() - flags = set(re.search(r"^flags\s*:\s*(.*)$", txt, re.M).group(1).split()) - avx2 = "avx2" in flags - avx512 = {"avx512f", "avx512bw", "avx512vl", "avx512_vnni", "avx512vbmi"} <= flags - m = re.search(r"^model name\s*:\s*(.*)$", txt, re.M) - name = m.group(1) if m else name - except OSError: - pass - return name, avx2, avx512 - - -def _cpuid_floor() -> str: - """Below AVX2 (Windows): "avx" when the CPU has AVX and the OS saves the YMM registers, "sse4.2" with SSE4.2 and - POPCNT, else "".""" - try: - regs = (ctypes.c_uint32 * 4)() - _run_stub(bytes([0x53, 0x49, 0x89, 0xC8, 0x89, 0xD0, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; eax=edx; ecx=0; cpuid - 0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08, # [r8]=eax, [r8+4]=ebx, [r8+8]=ecx - 0x41, 0x89, 0x50, 0x0C, 0x5B, 0xC3]), # [r8+12]=edx; pop rbx - ctypes.addressof(regs), 1) - ecx1 = regs[2] - if (ecx1 >> 27) & 1 and (ecx1 >> 28) & 1: # OSXSAVE, AVX - xcr0 = (ctypes.c_uint32 * 2)() - _run_stub(bytes([0x49, 0x89, 0xC8, 0x31, 0xC9, 0x0F, 0x01, 0xD0, # r8=rcx; ecx=0; xgetbv - 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, 0xC3]), ctypes.addressof(xcr0)) - if xcr0[0] & 6 == 6: - return "avx" - return "sse4.2" if (ecx1 >> 20) & 1 and (ecx1 >> 23) & 1 else "" - except Exception: - return "" - - -def cpu_floor(avx2: bool) -> str: - """The experimental older-CPU build this PC needs (#394 #595 #623): "" with AVX2 (the normal engine), "avx" (Sandy / - Ivy Bridge, AMD Bulldozer), "none" (SSE4.2 + POPCNT: Nehalem, Westmere), or "unsupported". STRATA_ISA_FLOOR=avx| - none asks for that build on any PC (testing it on a newer one).""" - forced = os.environ.get("STRATA_ISA_FLOOR", "").strip().lower() - if forced in ("avx", "none"): - return forced - if avx2: - return "" - if WIN: - f = _cpuid_floor() - else: - try: - txt = open("/proc/cpuinfo").read() - flags = set(re.search(r"^flags\s*:\s*(.*)$", txt, re.M).group(1).split()) - except (OSError, AttributeError): - flags = set() - f = "avx" if "avx" in flags else "sse4.2" if {"sse4_2", "popcnt"} <= flags else "" - return {"avx": "avx", "sse4.2": "none"}.get(f, "unsupported") - - -def _cpuid_avx512_full() -> bool: - """Windows has no feature bit for VNNI / VBMI: ask the CPU (CPUID leaf 7) through a tiny machine-code stub.""" - try: - code = bytes([0x53, 0x49, 0x89, 0xC8, 0xB8, 0x07, 0x00, 0x00, 0x00, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; cpuid(7,0) - 0x41, 0x89, 0x18, 0x41, 0x89, 0x48, 0x04, 0x5B, 0xC3]) # [r8]=ebx,[r8+4]=ecx; pop rbx - k32 = ctypes.windll.kernel32 - k32.VirtualAlloc.restype = ctypes.c_void_p - buf = k32.VirtualAlloc(None, len(code), 0x3000, 0x40) - if not buf: - return False - ctypes.memmove(buf, code, len(code)) - regs = (ctypes.c_uint32 * 2)() - ctypes.CFUNCTYPE(None, ctypes.c_void_p)(buf)(ctypes.addressof(regs)) - ebx, ecx = regs[0], regs[1] - need_ebx = (1 << 16) | (1 << 30) | (1 << 31) # F, BW, VL - need_ecx = (1 << 1) | (1 << 11) # VBMI, VNNI - return (ebx & need_ebx) == need_ebx and (ecx & need_ecx) == need_ecx - except Exception: - return False - - -def _run_stub(code: bytes, *args) -> None: - """Runs a few bytes of x64 machine code (Windows calling convention: the arguments in rcx, rdx).""" - k32 = ctypes.windll.kernel32 - k32.VirtualAlloc.restype = ctypes.c_void_p - k32.VirtualFree.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32) - buf = k32.VirtualAlloc(None, len(code), 0x3000, 0x40) - if not buf: - raise OSError("VirtualAlloc failed") - try: - ctypes.memmove(buf, code, len(code)) - ctypes.CFUNCTYPE(None, *[ctypes.c_void_p] * len(args))(buf)(*args) - finally: - k32.VirtualFree(buf, 0, 0x8000) - - -def _cpuid_avx2() -> bool: - """AVX2 asked from the CPU (CPUID leaf 7 EBX bit 5), with the OS saving the YMM registers (OSXSAVE + XCR0): - Windows' IsProcessorFeaturePresent(PF_AVX2) says no on some PCs whose CPU has it (a Ryzen 9 3950X, #159).""" - try: - def cpuid(leaf): - regs = (ctypes.c_uint32 * 4)() - _run_stub(bytes([0x53, 0x49, 0x89, 0xC8, 0x89, 0xD0, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; eax=edx; ecx=0; cpuid - 0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08, # [r8]=eax, [r8+4]=ebx, [r8+8]=ecx - 0x41, 0x89, 0x50, 0x0C, 0x5B, 0xC3]), # [r8+12]=edx; pop rbx - ctypes.addressof(regs), leaf) - return list(regs) - if cpuid(0)[0] < 7: - return False - ecx1 = cpuid(1)[2] - if not (ecx1 >> 27) & 1 or not (ecx1 >> 28) & 1: # OSXSAVE, AVX - return False - xcr0 = (ctypes.c_uint32 * 2)() - _run_stub(bytes([0x49, 0x89, 0xC8, 0x31, 0xC9, 0x0F, 0x01, 0xD0, # r8=rcx; ecx=0; xgetbv - 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, 0xC3]), ctypes.addressof(xcr0)) - if xcr0[0] & 6 != 6: # the OS saves XMM and YMM - return False - return bool((cpuid(7)[1] >> 5) & 1) - except Exception: - return False - - -def gpus(): - """Every NVIDIA GPU, numbered as nvidia-smi numbers them (by PCI bus, the order the engine is told to use).""" - s = out(["nvidia-smi", "--query-gpu=index,name,memory.total,compute_cap,driver_version", - "--format=csv,noheader,nounits"]) - found = [] - for line in s.strip().splitlines(): - try: - idx, name, mem, cc, drv = [x.strip() for x in line.split(",")] - found.append({"index": int(idx), "name": name, "vram_gb": float(mem) / 1024.0, "arch": cc.replace(".", ""), - "driver": drv}) - except ValueError: - continue - return found - - -def gpu_drives_display(g) -> bool: - """#779: True when nvidia-smi says this card has a display attached (display_active Enabled): its desktop needs - VRAM too, and a full expert cache beside it has crashed laptops.""" - text = out(["nvidia-smi", "-i", str(g.get("index", 0)), "--query-gpu=display_active", "--format=csv,noheader"]) - return text.strip().lower() == "enabled" - - -def gpu_compute_mode(index: int) -> str: - """#1445: nvidia-smi's compute mode for this card ("Default", "Exclusive_Process", "Prohibited", ...); "" when it - does not say.""" - return out(["nvidia-smi", "-i", str(index), "--query-gpu=compute_mode", "--format=csv,noheader"]).strip() - - -def compute_mode_warning(index: int, mode: str) -> str | None: - """#1445: the warning for a card that is not in the Default compute mode, or None. In Exclusive_Process only one - process may hold a CUDA context, so the engine, the vision encoder and the tuning run cannot share the card - ("CUDA-capable device(s) is/are busy or unavailable"); Prohibited allows none. A warning only: it is the - administrator's setting, PolyStrata never changes it.""" - if not mode or mode.lower() == "default" or mode.lower().startswith("n/a") or mode.lower().startswith("[n/a"): - return None - return (f"GPU {index} is in the compute mode {mode}, not Default: a second process cannot use the card while " - "the first holds it, so the vision encoder or the tuning run can fail with \"CUDA-capable device(s) is/are " - f"busy or unavailable\". If it does, set it back with: sudo nvidia-smi -i {index} -c DEFAULT") - - -def pcie_link(index: int) -> dict | None: - """The NVIDIA card's PCIe link: {"gen": the generation card and board both run (an idle card drops to a lower - one, so the current generation is not asked), "gpu_gen", "host_gen", "width", "max_width"}; None when nvidia-smi - does not say.""" - s = out(["nvidia-smi", "-i", str(index), "--query-gpu=pcie.link.gen.max,pcie.link.gen.gpumax,pcie.link.gen.hostmax," - "pcie.link.width.current,pcie.link.width.max", "--format=csv,noheader,nounits"]) - try: - gen, gpu_gen, host_gen, width, max_width = (int(x.strip()) for x in s.strip().splitlines()[0].split(",")) - except (ValueError, IndexError): - return None - return {"gen": gen, "gpu_gen": gpu_gen, "host_gen": host_gen, "width": width, "max_width": max_width} - - -PCIE_GBPS = {1: 0.25, 2: 0.5, 3: 0.985, 4: 1.97, 5: 3.94} # GB/s per lane, each direction - - -def pcie_lines(link: dict) -> tuple[str, str | None]: - """(the ok line, a warning or None) for step 1. The copy rate the engine measures is about 75% of the link's.""" - lim = [] - if link["gpu_gen"] > link["gen"]: - lim.append(f"the card supports {link['gpu_gen']}.0, the board {link['host_gen']}.0") - line = f"PCIe: {link['gen']}.0 x{link['width']}" + (f" ({'; '.join(lim)})" if lim else "") - rate = PCIE_GBPS.get(link["gen"], 0) * link["width"] - if 0 < rate < 12: - 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 " - "experts are copied over it); the engine measures the link at start for the output speed") - warn_line = None - if link["width"] < link["max_width"]: - # (#912) the width is read now, and some cards and laptops narrow the link while idle: a hint, not a verdict - warn_line = (f"the GPU's PCIe link reads {link['width']} of its {link['max_width']} lanes right now (some cards " - "narrow it when idle); if it stays narrow under load: is it in the right slot (the one wired " - "x16), fully seated, and not sharing lanes with an M.2 drive? (the BIOS can say)") - return line, warn_line - - -GPU_PICK = None # --gpu N (issue #51); None: the card with the most VRAM -SPLIT_MIN_VRAM_GB = 8 # a card sharing a model holds the dense weights and its own - # prompt buffers too (docs/MULTI_GPU.md) -SPLIT_PROMPT_VRAM_GB = 12 # #448: a split stage lends a prompt chunk's buffers from its - # own cache; below this one cannot fund a 4096-token chunk - # (a 10 GB RTX 3080 beside a 32 GB card: 512 tokens, prompts - # 6.2x slower), while the big card alone could - - -def cc(g) -> str: - return f"{g['arch'][:-1]}.{g['arch'][-1]}" - - -OLD_GPUS = None # why Pascal / Volta cards are admitted in this run (old_gpus_opt_in), None: they are not - - -def experimental_sm60() -> bool: - """#295: STRATA_EXPERIMENTAL_SM60=1 admits Pascal (6.x) and Volta (7.0) cards, run by the experimental CUDA 12 - engine (-DSTRATA_EXPERIMENTAL_SM60=ON). So does naming such a card (--gpu N / --gpus), --cuda 12, or a PC that - has no newer card (old_gpus_opt_in).""" - return os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1" or OLD_GPUS is not None - - -def sm60_card(arch) -> bool: - return 60 <= int(arch) <= 70 - - -def old_gpus_opt_in(found, named=(), cuda=None, other=False): - """Why this run may use Pascal / Volta cards (the experimental CUDA 12 engine), or None. The cards are an opt-in: - the user named one (`named`: --gpu / --gpus), asked for --cuda 12, set STRATA_EXPERIMENTAL_SM60=1, or the PC has - no card the ready-made engine runs on and no supported AMD card (`other`; it used to stop there). A PC with a - newer card keeps recommending it.""" - old = [g for g in found if sm60_card(g["arch"])] - if not old: - return None - if os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1": - return "STRATA_EXPERIMENTAL_SM60=1" - if str(cuda) == "12": - return "--cuda 12" - picked = [g for g in old if g["index"] in set(named)] - if picked: - return "you chose " + ", ".join(f"GPU {g['index']} ({g['name']})" for g in picked) - if not other and not any(int(g["arch"]) >= CUDA13_MIN_ARCH for g in found): - return "it is the only kind of NVIDIA GPU in this PC" - return None - - -def named_gpus(gpu, gpus) -> list: - """The card numbers --gpu / --gpus name (an unreadable value: none; parse_gpus says what is wrong later).""" - try: - if gpus and str(gpus).strip().lower() != "all": - return [int(x) for x in str(gpus).split(",") if x.strip()] - return [int(gpu)] if gpu is not None else [] - except ValueError: - return [] - - -def cuda_choice(archs, cuda=None, poly=False): - """The CUDA toolkit of one model's engine: (12 or 13, why). 13 (the ready-made engine) unless a card is older - than CUDA 13 supports (Pascal / Volta: CUDA 13 cannot compile for them) - one engine runs per model, so its oldest - card decides. `cuda` (--cuda 12|13) overrides it; setup recommends, it does not refuse (the caller warns).""" - archs = sorted({int(x) for x in archs}) - old = [a for a in archs if a < CUDA13_MIN_ARCH] - if str(cuda) == "13": - return 13, ("--cuda 13 (as you chose)" + (f"; CUDA 13 has no code for sm_{old[0]}: the engine will not run " - "on that card" if old else "")) - if str(cuda) == "12": # #220 is the Qwen engine's prompt path, not strata-poly's - crashed = archs and archs[-1] >= 120 and not poly - return 12, "--cuda 12 (as you chose" + ("; RTX 50 (sm_120) engines built with CUDA 12.8 crashed on long " - "prompts, #220" if crashed else "") + ")" - if old: - return 12, (f"sm_{old[0]} is older than CUDA 13 supports (it dropped Pascal and Volta): this model runs the " - "experimental CUDA 12 engine") - return 13, None - - -def engine_dir(toolkit=13) -> Path: - """The folder of the engine a model runs: engine/ (CUDA 13, or HIP), engine-cuda12/ (the experimental one).""" - return ROOT / (ENGINE12_DIR if int(toolkit) == 12 else "engine") - - -def config_toolkit(cfg: dict) -> int: - """12 when a model config runs the experimental CUDA 12 engine (its exe is in engine-cuda12/), else 13.""" - return 12 if cfg.get("cuda") == 12 or Path(str(cfg.get("exe", ""))).parent.name == ENGINE12_DIR else 13 - - -def gpu_problem(g, together=False): - """Why PolyStrata cannot use this card, in plain words (None: it can).""" - if int(g["arch"]) < 75 and not (sm60_card(g["arch"]) and experimental_sm60()): - return (f"not supported - older than the RTX 20 series (compute capability {cc(g)}; PolyStrata needs 7.5 or " - "newer" + ("; experimental: choose it with --gpu " + str(g["index"]) + " (the CUDA 12 engine, " - "docs/OLDER_GPUS.md)" if sm60_card(g["arch"]) else "") + ")") - if together and g["vram_gb"] < SPLIT_MIN_VRAM_GB - 0.5: - return (f"not supported together with other GPUs - {g['vram_gb']:.0f} GB of VRAM (a card sharing the model " - f"needs {SPLIT_MIN_VRAM_GB} GB or more)") - return None - - -def gpu_rank(g): - """The order cards share a model in: the newest generation first (it gets the first layers and most of the - work), then the most VRAM.""" - return (-int(g["arch"]), -round(g["vram_gb"]), g["index"]) - - -def gpu_name(g) -> str: - return f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB)" - - -def gpu_table(found) -> None: - say(" Your NVIDIA GPUs:") - for g in found: - p = gpu_problem(g) - say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + ("can be used" if p is None else p)) - - -def together_ok(found) -> list: - """The cards that can share one model, in the order they would (empty if fewer than two).""" - ok_ = sorted([g for g in found if gpu_problem(g, together=True) is None], key=gpu_rank) - return ok_ if len(ok_) >= 2 else [] - - -def split_short(cards) -> list: - """#448: the later cards of a split that would cap its prompt chunk below what the first card alone reads (a card - under SPLIT_PROMPT_VRAM_GB beside one that has it). Empty: the split is recommended as before.""" - if len(cards) < 2 or cards[0]["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5: - return [] - return [g for g in cards[1:] if g["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5] - - -def split_short_note(g) -> str: - return (f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB) is too small to lend a split its prompt buffers: " - "it would cap prompt reading at 512-2048-token chunks, several times slower than the first card alone " - "(#448). It can serve as a helper expert cache instead (docs/SECOND_GPU.md)") - - -def parse_gpus(text, found) -> list: - """--gpus / --gpu with several: "0,2" or "all" (every card that can share the model).""" - if str(text).strip().lower() == "all": - sel = [g["index"] for g in together_ok(found)] - if not sel: - gpu_table(found) - fail("--gpus all: this PC does not have two GPUs PolyStrata can use together") - return sel - try: - sel = [int(x) for x in str(text).split(",") if x.strip()] - except ValueError: - fail(f"--gpus takes GPU numbers as nvidia-smi numbers them, e.g. --gpus 0,2 (or --gpus all), not {text!r}") - if len(sel) < 2 or len(set(sel)) != len(sel): - fail("--gpus takes two or more different GPUs, e.g. --gpus 0,2 (one GPU: --gpu 0)") - return sel - - -def check_gpus(sel, found, what="", yes=False, named=False) -> None: - """Stops with a plain message when a chosen card is missing or cannot be used, and says what can. named: the user - named these cards (--gpus 0,1, or a config that has them): a card that is only short of VRAM for sharing the model - is then a risk to confirm, not a stop (the owner's rule; --yes with the named cards is the consent).""" - together = len(sel) > 1 - for i in sel: - g = next((x for x in found if x["index"] == i), None) - p = "not found on this PC" if g is None else gpu_problem(g, together) - if p is None: - continue - if named and g is not None and gpu_problem(g) is None: # it runs PolyStrata; only its VRAM is small - confirm_risk(f"GPU {i} ({g['name']}) has {g['vram_gb']:.0f} GB of VRAM: a card sharing the model needs " - f"{SPLIT_MIN_VRAM_GB} GB or more (it holds the dense weights of its layers and its own prompt " - "buffers), so the model may not start, or run slower than without it", True, yes, - f"GPU {i} ({g['name']}) {what}is not used together with other GPUs: {p}", - "leave it out of --gpus, or answer y to use it anyway", " Use it anyway?") - warn(f"GPU {i} ({g['name']}) is used together with the others, as you chose") - continue - say() - gpu_table(found) - can = together_ok(found) - single = [x for x in found if gpu_problem(x) is None] - ones = " or ".join(f"--gpu {x['index']}" for x in single) - both = "--gpus " + ",".join(str(x["index"]) for x in can) if can else "" - hint = ((f"use these together: {both}" + (f" (or one card: {ones})" if not together else "")) if can else - f"use one card: {ones}" if single else "PolyStrata needs an NVIDIA RTX 20 series or newer card") - fail(f"GPU {i}{'' if g is None else ' (' + g['name'] + ')'} {what}cannot be used: {p}", hint) - - -def engine_archs(toolkit=13): - """The GPU generations the installed engine has code for: (archs, ptx), or None when there is none.""" - info = engine_dir(toolkit) / "BUILD.json" - try: - meta = json.loads(info.read_text(encoding="utf-8")) - except (OSError, ValueError): - return None - return [int(x) for x in meta.get("archs", [])], bool(meta.get("ptx")) - - -def engine_archs_hip(): - """The AMD architectures the installed HIP engine was compiled for ("gfx1201", ...), or None.""" - try: - meta = json.loads((ROOT / "engine" / "BUILD.json").read_text(encoding="utf-8")) - except (OSError, ValueError): - return None - return [str(x) for x in meta.get("archs", [])] if meta.get("backend") == "hip" else None - - -def engine_runs_on(g, toolkit=13) -> bool: - ea = engine_archs(toolkit) - if ea is None or not ea[0]: - return True - archs, ptx = ea - return int(g["arch"]) in archs or (ptx and int(g["arch"]) > max(archs)) - - -def start_gpus(text): - """--gpus when starting an installed model: NVIDIA cards as nvidia-smi numbers them, or on a PC whose AMD cards - are the ones PolyStrata can use, AMD cards as setup lists them ("all": every supported AMD card).""" - if not text: - return None - found = gpus() - if str(text).strip().lower() == "all" and not WIN and not together_ok(found): - amd = amd_gpus() - if len([g for g in amd if amd_problem(g) is None]) >= 2: - return [g["index"] for g in amd_parse_gpus("all", amd)] - if not found and not WIN: # #1594: no NVIDIA card, AMD ones: "1,0" names those, as setup lists them - amd = amd_gpus() - if amd: - return [g["index"] for g in amd_parse_gpus(text, amd)] - return parse_gpus(text, found) - - -def choose_gpus(a, found) -> list: - """Which cards this install uses: --gpus / --gpu, or asked when two or more can share the model (the two best - together recommended), else the supported card with the most VRAM. Returns their numbers, the main one first.""" - if a.gpus: - sel = parse_gpus(a.gpus, found) - check_gpus(sel, found, yes=a.yes, named=str(a.gpus).strip().lower() != "all") - return sel - if a.gpu is not None: - check_gpus([a.gpu], found) - return [a.gpu] - single = sorted([g for g in found if gpu_problem(g) is None], key=lambda x: (-round(x["vram_gb"]), x["index"])) - if not single: - gpu_table(found) - fail("none of your GPUs can run PolyStrata", "it needs an NVIDIA RTX 20 series or newer (compute capability 7.5+)") - can = together_ok(found) - if not can: - return [single[0]["index"]] - say() - say(f" PolyStrata can run the model on one GPU, or share it across {'these' if len(can) > 2 else 'both'}: then each" - " card holds the") - say(" experts of its own layers, so together they hold about twice as many, and prompts are read about 20%") - say(" faster (details: docs/MULTI_GPU.md). A much slower extra card can also make it slower.") - opts = [can[:2]] + ([can] if len(can) > 2 else []) + [[g] for g in single] - # #448: a pair whose second card cannot lend a 4096-token chunk recommends the first card alone (still offered) - short = split_short(can[:2]) - rec = next(i for i, o in enumerate(opts, 1) if o == [can[0]]) if short else 1 - for i, o in enumerate(opts, 1): - label = (" + ".join(gpu_name(g) for g in o) + " together") if len(o) > 1 else gpu_name(o[0]) + " only" - say(f" {i}) {label}" + (" (recommended)" if i == rec else "")) - for g in found: - if gpu_problem(g, together=True) is not None: - say(f" (GPU {g['index']}, {g['name']}: {gpu_problem(g, together=True)})") - for g in short: - say(f" ({split_short_note(g)})") - pick = opts[int(ask("Which GPUs?", [str(i) for i in range(1, len(opts) + 1)], str(rec), a.yes or a.check)) - 1] - return [g["index"] for g in pick] - - -def split_mmap(cfg: dict) -> bool: - """#364 #384: the low-RAM mode's resident variant (--resident-experts) has no layer split yet. A config with it - that runs on several GPUs reads the experts the GPUs do not hold through the OS file cache instead - (--mmap-experts: the placement those reports measured 1.3-1.6x faster than one GPU), said plainly - the engine - used to refuse the pair. #642: the engines from RESIDENT_SPLIT_ENGINE run it on a split, so it is kept. True - when the config changed.""" - a = cfg.get("args", []) - if "--resident-experts" not in a or resident_split(): - return False - a[a.index("--resident-experts")] = "--mmap-experts" - warn("the low-RAM mode's resident variant (--resident-experts) has no layer split yet: on several GPUs the experts " - "the GPUs do not hold are read through the OS file cache (--mmap-experts) instead, and RAM can fill up to 0 " - "free during long prompts. One GPU keeps them in RAM (steady RAM use): START-HERE --setup, or --gpu N for a " - "start") - return True - - -def family_models(family: str) -> dict: - """A family's sizes, each name with what MODELS says of a size. A family may name its own ("models").""" - fam = FAMILIES[family] - return fam["models"] if "models" in fam else \ - {m: d for m, d in MODELS.items() if family in d.get("families", ("qwen", "swift"))} - - -def model_file(fam: dict, model: str, i: int) -> str: - """Shard i's file name: the family's pattern, or the model's own (#621: UD-IQ4_XS has three shards, not four).""" - return fam.get("models", MODELS).get(model, {}).get("file", fam["file"]).format(q=model, i=i) - - -def model_shards(fam: dict, model: str) -> int: - return fam.get("models", MODELS).get(model, {}).get("shards", fam.get("shards", 2)) - - -def budget_model(cfg: dict) -> str: - """The Unsloth model a config with a RAM budget runs, from its --native shard's name (UD-Q4_K_XL by default).""" - a = cfg.get("args", []) - native = Path(a[a.index("--native") + 1]).name.upper() if "--native" in a and a.index("--native") + 1 < len(a) \ - else "" - return next((m for m, d in MODELS.items() if d.get("budget") and f"-{m}-" in native), "UD-Q4_K_XL") - - -def unsloth_split_need_gb(model="UD-Q4_K_XL") -> float: - """#498: the RAM UD-Q4_K_XL needs on several GPUs, where it has no RAM budget (the engine refuses - --resident-budget-gib with a layer split): its GGUF files and UNSLOTH_RAM_LEFT_GB more (~135 GB). Measured safe - 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.""" - return MODELS[model]["download_gb"] + UNSLOTH_RAM_LEFT_GB - - -def split_budget(cfg: dict, yes: bool = False, explicit: bool = False) -> bool: - """#498: a UD-Q4_K_XL config (its RAM budget, --resident-budget-gib) started on several GPUs. The engine refused - the budget with a layer split (it exited with code 2), so the split runs without it - all the experts loaded into - RAM at start - where the RAM holds the GGUFs and 24 GB more; else setup says so and asks (#737: a recommendation, - not a wall - 128 GB ran it fine): a "no" stops, before the config is saved; `explicit` (--gpus) with --yes goes on. - #642: the engines from RESIDENT_SPLIT_ENGINE keep the resident RAM copy on a split - every card's cache left out - of it, the rest ranked by the whole expert profile - and the budget is that copy's size, so it is kept, as - split_mmap keeps --resident-experts. True when the config changed.""" - a = cfg.get("args", []) - if "--resident-budget-gib" not in a or resident_split(): - return False - model = budget_model(cfg) - need, ram = unsloth_split_need_gb(model), ram_gb() - if ram < need: - confirm_risk(f"{model} cannot share its RAM budget across GPUs (the engine has no layer split with it), and " - f"without the budget it needs ~{need:.0f} GB of RAM (its GGUF files and {UNSLOTH_RAM_LEFT_GB} GB " - f"more); this PC has {ram:.0f} GB. The estimate is a worst case: a 128 GB PC ran it (#737), but " - "it may page or stall here.", explicit, yes, - f"{model} on several GPUs needs ~{need:.0f} GB of RAM; this PC has {ram:.0f} GB", - "start it on one GPU: START-HERE.bat --gpu N (Linux: ./setup.sh --gpu N)") - i = a.index("--resident-budget-gib") - del a[i:i + 2] - ok(f"{model} on several GPUs: no RAM budget (the engine has none with a layer split) - all its experts are " - "loaded into RAM from the model files at start, and the files pass through the OS file cache (#498)") - return True - - -REMOTE_EXPERT_OPT = "--remote-expert-opt" -HELPER_CACHE_FLAGS = ("--expert-cache-device1", "--expert-cache-device2", "--expert-cache-device3") - - -def recommend_remote_expert_opt(cfg: dict, off: bool = False) -> None: - """0.1.39b (#578): a config on two or more GPUs with a helper cache gets --remote-expert-opt - the helper expert caches - (--expert-cache-device1..3) then stay complementary to the main GPU's, return their rows already weighted and skip - the CPU's activation quantization where no expert is left to it (dual RTX 4090: +63% mixed, +132% code over the - plain helper path). The engine uses it only with a helper cache; a layer split runs as before. A recommendation: - `off` (setup's --no-remote-expert-opt) or "remote_expert_opt": false in the config keeps it out, and a single-GPU - config is not touched.""" - if not isinstance(cfg.get("gpu"), list) or len(cfg["gpu"]) < 2: - return - args = cfg.setdefault("args", []) - if off or cfg.get("remote_expert_opt") is False: - if REMOTE_EXPERT_OPT in args: - args.remove(REMOTE_EXPERT_OPT) - return - # #1352: --pipeline-windows (the first card starts the next window) is switched off by --remote-expert-opt (the - # helper caches), so a config that asks for it keeps its pipeline: one of the two, not both (docs/MULTI_GPU.md) - pw = args.index("--pipeline-windows") if "--pipeline-windows" in args else -1 - if pw >= 0 and pw + 1 < len(args) and args[pw + 1] != "0": - if REMOTE_EXPERT_OPT in args: - warn("--pipeline-windows and --remote-expert-opt are both in this config: the engine turns the pipeline off " - "beside the helper caches. Keep one - remove --remote-expert-opt for the pipeline " - "(docs/MULTI_GPU.md, #1352)") - else: - ok("multi-GPU: --pipeline-windows is set, so --remote-expert-opt is not added (the helper caches turn the " - "pipeline off; docs/MULTI_GPU.md)") - return - # #1447: the flag acts only on the helper caches (--expert-cache-device1..3); without one the engine builds nothing - # from it, and a plain layer split gained a flag that says "helpers" for no reason. Setup adds it only beside a - # helper cache; a flag already in the config stays (the user's, or an earlier setup's - harmless). - if not any(a.split("=", 1)[0] in HELPER_CACHE_FLAGS for a in args): - return - if REMOTE_EXPERT_OPT not in args: - args.append(REMOTE_EXPERT_OPT) - ok("multi-GPU: --remote-expert-opt (helper expert caches complementary to the main GPU's, #578; " - "--no-remote-expert-opt leaves it out)") - - -def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: - """Starting a model set up for one card on a PC with two or more that can share it: asked once (the answer is - saved in its config).""" - if isinstance(cfg.get("gpu"), list) or cfg.get("gpus_asked"): - return cfg - found = gpus() - can = together_ok(found) - if not can: - return cfg - # #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: - # the engines from RESIDENT_SPLIT_ENGINE keep the budget on both cards, so any RAM is offered them (one GPU stays - # the recommendation, the tested setup) - budget = "--resident-budget-gib" in cfg.get("args", []) - if budget and not resident_split() and ram_gb() < unsloth_split_need_gb(budget_model(cfg)): - return cfg - pair = can[:2] - cfg["gpus_asked"] = True - # #364 #384: the resident low-RAM variant stays on one card unless the user says otherwise (its RAM use is steady); - # #642: the engines from RESIDENT_SPLIT_ENGINE keep it on both cards, so they are offered as for any config - resident = "--resident-experts" in cfg.get("args", []) and not resident_split() - say() - say(" This PC has " + " and ".join(gpu_name(g) for g in pair) + ": PolyStrata can share the model across both.") - say(" Together they hold about twice the model's experts and read prompts about 20% faster (docs/MULTI_GPU.md).") - if resident: - say(" This model runs in the low-RAM mode with its experts kept in RAM, on one GPU (recommended: steady RAM") - say(" use). On both, the experts the GPUs do not hold are read through the OS file cache instead: faster in") - say(" two reports (#364, #384), but RAM can fill up to 0 free during long prompts.") - if budget and resident_split(): - say(f" This model ({budget_model(cfg)}) runs on one GPU with a RAM budget of its experts (recommended: the tested") - say(" setup). On both it keeps the budget: each card caches the experts of its own layers, and the RAM holds") - say(" the hottest of the rest (#642).") - elif budget: - say(f" This model ({budget_model(cfg)}) runs on one GPU with a RAM budget of its experts (recommended: the tested") - say(" setup). On both it has no budget: all its experts are loaded into RAM at start, which this PC's RAM") - say(" holds - about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s).") - short = split_short(pair) # #448: one card recommended (asked "n" by default), as for --resident - for g in short: - say(f" {split_short_note(g)}.") - tk = config_toolkit(cfg) - missing = [g for g in pair if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))] - if missing: - say(" The installed engine has no code for " + ", ".join(g["name"] for g in missing) + ": to use them " - "together, run START-HERE.bat --setup --gpus " + ",".join(str(g["index"]) for g in pair)) - elif ask(" Use both from now on? (you can change it later: START-HERE.bat --gpu N for one card)", - ["y", "n"], "n" if resident or short or budget else "y", yes) == "y": - cfg["gpu"] = [g["index"] for g in pair] - cfg["layer_split"] = cfg.get("layer_split") or "auto" - split_mmap(cfg) - split_budget(cfg) - recommend_remote_expert_opt(cfg) - ok("from now on this model runs on " + " + ".join(gpu_name(g) for g in pair)) - else: - ok("staying on one GPU (START-HERE.bat --gpus " + ",".join(str(g["index"]) for g in pair) + " switches)") - write_config(cfg_path, cfg) - return cfg - - -def gpu_info(pick=None): - """The GPU PolyStrata runs on: `pick` (nvidia-smi's number) if given, else the one with the most VRAM (ties: the - lower number). None when there is no NVIDIA GPU. The dict also says how many there are ("count").""" - found = gpus() - if not found: - return None - pick = GPU_PICK if pick is None else pick - if pick is not None: - g = next((x for x in found if x["index"] == pick), None) - if g is None: - fail(f"there is no GPU {pick}: " + ", ".join(f"{x['index']} = {x['name']}" for x in found)) - else: - g = max(found, key=lambda x: (round(x["vram_gb"]), -x["index"])) - return {**g, "count": len(found)} - - -def find_nvcc(below=None): - """The newest CUDA toolkit's nvcc and its (major, minor); with `below`, the newest older than that version. - #601: STRATA_NVCC= is the only one considered (a newer toolkit beside it that cannot build on this - PC - CUDA 12.9 with glibc 2.43 - is not taken instead).""" - pick = os.environ.get("STRATA_NVCC") - if pick: - if not Path(pick).exists(): - warn(f"STRATA_NVCC={pick}: no such file; looking for a CUDA toolkit as usual") - else: - v = re.search(r"release (\d+)\.(\d+)", out([pick, "--version"])) - ver = (int(v.group(1)), int(v.group(2))) if v else None - if ver and below is not None and ver >= below: - warn(f"STRATA_NVCC={pick} is CUDA {ver[0]}.{ver[1]}; this build needs one older than " - f"{below[0]}.{below[1]}") - return (None, None) - return (pick, ver) if ver else (None, None) - cands = [shutil.which("nvcc")] - for var in ("CUDA_PATH", "CUDA_HOME"): # CUDA_HOME: Linux's usual name (#601) - if os.environ.get(var): - cands.append(str(Path(os.environ[var]) / "bin" / ("nvcc.exe" if WIN else "nvcc"))) - if WIN: - base = Path(r"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA") - if base.exists(): - cands += [str(p / "bin" / "nvcc.exe") for p in sorted(base.iterdir(), reverse=True)] - else: - cands += [str(p / "bin" / "nvcc") for p in sorted(Path("/usr/local").glob("cuda*"), reverse=True)] - cands += [str(p / "bin" / "nvcc") for p in sorted(Path("/opt").glob("cuda*"), reverse=True)] # Arch (#46) - best = (None, None) - for c in dict.fromkeys(cands): # every toolkit found; the newest wins - if c and Path(c).exists(): - v = re.search(r"release (\d+)\.(\d+)", out([c, "--version"])) - ver = (int(v.group(1)), int(v.group(2))) if v else None - if ver and (below is None or ver < below) and (best[1] is None or ver > best[1]): - best = (c, ver) - return best - - -def find_vcvars(cuda_v=None): - """Visual Studio's vcvars64.bat. #985: CUDA 13.0-13.2 accept Visual Studio 2019 and 2022 only, so a newer one - (2026 = version 18) is taken only with CUDA 13.3 or newer (`cuda_v`, the toolkit's (major, minor)), or when it - has the 2022 compiler in it. - - The version range is CUDA's requirement alone, so a caller with no CUDA (`cuda_v is None`) asks vswhere for no - range at all: the CPU image encoder is built by MSVC, which is happy with any version (tools/hip/build_windows.bat - already calls vswhere that way). With the range applied to every caller, a machine whose only C++ tools are - Visual Studio 2026 gets None back and nothing can be built there (#881). STRATA_VCVARS= picks one - by hand, for an install vswhere cannot use.""" - override = os.environ.get("STRATA_VCVARS") - if override: - v = Path(override) - return v if v.exists() else None - vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Microsoft Visual Studio/Installer/vswhere.exe" - if not vswhere.exists(): - return None - - def newest(*versions): - p = out([str(vswhere), "-latest", "-products", "*", *versions, "-requires", - "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"]).strip() - v = Path(p) / "VC/Auxiliary/Build/vcvars64.bat" if p else None - return v if v and v.exists() else None - - if cuda_v is None: - return newest() - # A Visual Studio the toolkit does not accept, installed next to one it does, must not be picked ("unsupported - # Microsoft Visual Studio version"). A newer one alone will do when it has the 2022 compiler in it (the v143 - # toolset), which vcvars_toolset() asks it for. - upper = "19.0" if tuple(cuda_v) >= (13, 3) else "18.0" - v = newest("-version", f"[16.0,{upper})") - if v is None: - v = newest() - if v is not None and not vcvars_toolset(v): - return None - return v - - -def vcvars_toolset(vcvars) -> str: - """What vcvars64.bat of a Visual Studio newer than 2022 is called with to set up its 2022 compiler - (" -vcvars_ver=14.44.35207"); "" for 2019 and 2022, whose own compiler is the one, and for a newer one that - was installed without that toolset.""" - def version(name): - try: - return (Path(vcvars).parent / name).read_text().strip() - except OSError: - return "" - - own, v143 = version("Microsoft.VCToolsVersion.default.txt"), version("Microsoft.VCToolsVersion.v143.default.txt") - m = re.match(r"14\.(\d+)\.", own) - return f" -vcvars_ver={v143}" if m and int(m.group(1)) >= 50 and re.fullmatch(r"14\.[34]\d\.\d+", v143) else "" - - -def find_tool(name): - """cmake or ninja: the one pip installed next to this Python, else one on PATH. The system's own can be older - than CMakeLists.txt takes: Ubuntu 22.04 has cmake 3.22, and the engine asks for 3.24.""" - file = name + (".exe" if WIN else "") - for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent): - if (d / file).exists(): - return str(d / file) - p = shutil.which(name) - if p: - return p - c = Path.home() / ".local" / "bin" / file - return str(c) if c.exists() else None - - -def free_gb(path): - path.mkdir(parents=True, exist_ok=True) - return shutil.disk_usage(path).free / 1e9 - - -# ------------------------------------------------------------------------------------------------ downloads -def drop_archive(z: Path) -> None: - """An unpacked or refused engine archive and its .done mark go: a refused one kept them, and every later run - reused it ("already downloaded") instead of the published one (PR #324).""" - z.unlink(missing_ok=True) - z.with_name(z.name + ".done").unlink(missing_ok=True) - - -def download(url, dst: Path, what=None): - """Resumable HTTP(S) download with a progress line; `file://` and plain paths are copied (tests, mirrors). - A finished file gets a .done mark, so a later run skips it without asking the server.""" - dst.parent.mkdir(parents=True, exist_ok=True) - if dst.exists() and done(dst): - ok(f"{what or dst.name} already downloaded") - return - if not url.startswith(("http://", "https://")): - src = Path(url[7:] if url.startswith("file://") else url) - if not src.exists(): - fail(f"not found: {src}") - shutil.copyfile(src, dst) - mark(dst) - ok(f"{what or dst.name} copied") - return - ms = ms_file(url) if model_source() == "modelscope" else None - if ms is not None: - if reachable(ms_url(*ms), timeout=30): - url = ms_url(*ms) - else: - warn(f"{what or dst.name}: ModelScope does not answer; downloading it from {hf_endpoint()}") - ms = None - part = dst.with_name(dst.name + ".part") - total = 0 - for attempt in range(5): - try: - req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}) - total = int(urllib.request.urlopen(req, timeout=60).headers.get("Content-Length", 0)) - break - except urllib.error.HTTPError as e: - if e.code == 404 and hf_unpinned(url) != url: # #214: the pinned revision is gone from the repository - warn(f"{what or dst.name}: not at the pinned revision any more; downloading the repository's " - "current file") - url = hf_unpinned(url) - continue - if attempt == 4: - fail(f"cannot reach {url.split('/')[2]} ({e})", - "check your internet connection and run it again" + source_hint(url)) - time.sleep(5) - except OSError as e: - if attempt == 4: - fail(f"cannot reach {url.split('/')[2]} ({e})", - "check your internet connection and run it again" + source_hint(url)) - time.sleep(5) - if dst.exists() and total and dst.stat().st_size == total: # finished by an older setup (no mark yet) - mark(dst) - ok(f"{what or dst.name} already downloaded") - return - have = part.stat().st_size if part.exists() else 0 - for attempt in range(30): - if total and have >= total: # stopped after the last byte, before the rename: nothing to - break # ask for (a range past the end is a 416, retried 30 times) - try: - req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={have}-"}) - with urllib.request.urlopen(req, timeout=60) as r, open(part, "ab" if have else "wb") as f: - if have and r.status != 206: # the server ignored the range: start over - f.seek(0) - f.truncate() - have = 0 - last = 0.0 - while True: - b = r.read(8 << 20) - if not b: - break - f.write(b) - have += len(b) - if time.time() - last > 2: - last = time.time() - size = f"{have / 1e9:6.2f} / {total / 1e9:.2f} GB ({100 * have / total:.0f}%)" if total \ - else f"{have / 1e6:7.1f} MB" - print(f"\r {what or dst.name}: {size} ", end="", flush=True) - print() - if not total or have >= total: - break - except OSError as e: - print() - warn(f"download interrupted ({e}); retrying in 10 s ...") - time.sleep(10) - if total and part.stat().st_size != total: - fail(f"could not finish downloading {dst.name}: {part.stat().st_size:,} bytes on disk, the server says {total:,}", - "check your internet connection and run it again (the download resumes where it stopped)") - part.replace(dst) - meta = ms_meta(*ms) if ms is not None else None - if meta is not None and meta[1]: - verify_sha256(dst, meta[0], meta[1]) # ModelScope's published hash; kept in the finish mark - else: - if ms is not None: - warn(f"{what or dst.name}: ModelScope publishes no SHA-256 for it: the file is not verified") - mark(dst) - ok(f"{what or dst.name} downloaded") - - -def whole_shard(s: Path) -> bool: - """A shard as long as its own tensor directory says (check_shards' test, without stopping setup).""" - sys.path.insert(0, str(ROOT / "tools")) - from gguf_reader import GGUFFile - try: - g = GGUFFile(s) - return s.stat().st_size >= g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors), - default=0) - except (OSError, ValueError, struct.error): - return False - - -SHARD_NAME = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$") - - -def gguf_dir_shards(folder: Path, fam: dict, model: str) -> list[Path]: - """--gguf-dir's shards (#305): every -0000i-of-0000N file of the model, N read from the first shard's name as the - engine and tools/iq_pack.py do. The published name first; else the one first shard in the folder whose name has - the size in it (an upload split or named differently: -00001-of-00003, Unsloth's ...-00001-of-00004.gguf). A - missing shard is check_shards' error later, as before.""" - first = folder / model_file(fam, model, 1) - if not first.exists(): - found = sorted(p for p in folder.glob("*-00001-of-*.gguf") if SHARD_NAME.search(p.name)) - mine = [p for p in found if model.lower() in p.name.lower()] - pick = mine if mine else found - if len(pick) == 1: - first = pick[0] - m = SHARD_NAME.search(first.name) - total = int(m.group(2)) if m else 1 - if not m or total < 1: - return [first] - stem = first.name[:m.start()] - return [first.with_name("%s-%05d-of-%05d.gguf" % (stem, i, total)) for i in range(1, total + 1)] - - -# #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, ...) -GGUF_QUANT = re.compile(r"(? str | None: - """#444: the quantization a GGUF's name says, when it is one PolyStrata cannot run (not a setup size); else None.""" - m = GGUF_QUANT.search(name) - return m.group(1) if m and m.group(1).upper() not in MODELS and not name.lower().startswith("mmproj") else None - - -def gguf_choice(name: str) -> tuple | None: - """#444: (--family, --model) whose published first shard this file is, or None (the Coder's IQ1_M is named like - the original's sizes: the size tells them apart).""" - for f, d in FAMILIES.items(): - if d.get("ready"): # ready-made packs (NVFP4): no GGUF shards to match - continue - for m in MODELS: - if f in MODELS[m].get("families", ("qwen", "swift")) and name == model_file(d, m, 1): - return f, m - return None - - -def gguf_dir_problem(folder: Path, first: Path, fam: dict, model: str) -> tuple | None: - """#444: (message, hint) when --gguf-dir has no file setup can use for this choice: the chosen shard is a GGUF - PolyStrata cannot run (Unsloth's UD-IQ3_XXS taken for IQ3_XXS by its name), or it is missing and the folder holds - other GGUFs - then the hint names the --family/--model of the usable ones. None otherwise (a missing shard in a - folder without GGUFs stays check_shards' "missing").""" - bad = gguf_unsupported(first.name) if first.exists() else None - if bad: - return f"{first.name} is {bad}, a GGUF PolyStrata cannot run", SUPPORTED_GGUFS - if first.exists(): - return None - firsts = sorted(p.name for p in folder.glob("*.gguf") - if not p.name.lower().startswith("mmproj") and (not SHARD_NAME.search(p.name) - or SHARD_NAME.search(p.name).group(1) == "00001")) - usable = list(dict.fromkeys(c for c in map(gguf_choice, firsts) if c)) - unusable = [n for n in firsts if gguf_unsupported(n)] - if not usable and not unusable: - return None - hint = SUPPORTED_GGUFS - if unusable: - hint += ".\n Not usable here: " + ", ".join(unusable) - if usable: - hint += ".\n Usable here: " + ", ".join(f"--family {f} --model {m}" for f, m in usable) - return f"{folder} has no {fam['title']} {model} file", hint - - -def verify_sha256(s: Path, size: int, sha: str) -> None: - """A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark, - so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again.""" - m = s.with_name(s.name + ".done") - if m.exists() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace"): - return - have = s.stat().st_size if s.exists() else -1 - if have != size: - fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)") - say(f" checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...") - h = hashlib.sha256() - with open(s, "rb") as f: - while True: - b = f.read(16 << 20) - if not b: - break - h.update(b) - if h.hexdigest() != sha: - s.unlink(missing_ok=True) - m.unlink(missing_ok=True) - fail(f"{s.name} has the wrong SHA-256 ({h.hexdigest()}, expected {sha}): deleted", - "run setup again to download it again") - mark(s, f"sha256 {sha}") - - -def ready_files(model: str) -> list: - """A ready-made pack's files (NVFP4_REPOS): (role, repo, revision, path, bytes, sha256) each.""" - repo = MODELS[model]["repo"] - t = NVFP4_REPOS[repo] - return [(role, repo, t["revision"], path, size, sha) for path, (role, size, sha) in t["files"].items()] - - -def ready_where(models_dir: Path, f) -> Path: - """Where one of them goes: /--/ (the repository's layout, so the - pack folder is whole as the engine reads it).""" - return Path(models_dir) / f[1].replace("/", "--") / f[3] - - -def ready_paths(model: str, models_dir: Path) -> dict: - """What the engine is given: the pack folder and the dense, PLE and embedding GGUFs.""" - out = {} - for f in ready_files(model): - p = ready_where(models_dir, f) - if f[0] == "pack" and p.name == "index.txt": - out["pack"] = p.parent - elif f[0] in ("dense", "ple", "embd"): - out[f[0]] = p - return out - - -def ready_verified(p: Path, sha: str) -> bool: - """Downloaded whole and checked: its finish mark holds the pinned SHA-256 (verify_sha256).""" - m = p.with_name(p.name + ".done") - try: - return p.is_file() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace") - except OSError: - return False - - -def ready_fetch(model: str, models_dir: Path) -> None: - """Every file of a ready-made pack: already here and checked; the same file (by SHA-256) checked for another - ready-made pack, linked instead of downloaded (the PLE table and the embedding); or downloaded from its pinned - revision and checked against its size and SHA-256 (a wrong file is deleted and setup stops).""" - others = [(ready_where(models_dir, g), g[5]) for m in MODELS if MODELS[m].get("repo") for g in ready_files(m)] - for f in ready_files(model): - dst, size, sha = ready_where(models_dir, f), f[4], f[5] - if ready_verified(dst, sha): - ok(f"{f[3]} already downloaded") - continue - src = next((p for p, s in others if s == sha and p != dst and ready_verified(p, s)), None) - if src is not None and not dst.exists(): - try: - dst.parent.mkdir(parents=True, exist_ok=True) - os.link(src, dst) - mark(dst, f"sha256 {sha}") - ok(f"{f[3]}: the same file as {src} (linked, not downloaded again)") - continue - except OSError: - pass # another drive: downloaded - download(f"{hf_endpoint()}/{f[1]}/resolve/{f[2]}/{f[3]}", dst, f"{f[1].split('/')[-1]}: {f[3]}") - verify_sha256(dst, size, sha) - - -def resident_budget_gib(model, ram, kv_ram_gb=0.0) -> int: - """UD-Q4_K_XL: the GiB of experts the engine keeps in RAM (--resident-budget-gib): the RAM (GiB, ram_gb()) less - 24 for the OS, the engine and the file cache the other experts are read through, less a KV cache streamed to - RAM; at most all of them, at least 8. 64 GB: 40, the measured setting (docs/UNSLOTH_Q4.md).""" - gib = round(ram) - UNSLOTH_RAM_LEFT_GB - math.ceil(kv_ram_gb) - return max(8, min(gib, int(MODELS[model]["arena_gb"] / 1.073741824))) - - -# MODEL-UPDATE Phase 2: Unsloth's files keep every expert in RAM (a pinned arena, as ISTA's files do) where the experts -# and this much more fit the PC's RAM; the RAM budget (--resident-budget-gib: the hottest experts in RAM, the rest read -# from the GGUF in place) only below that. The rule and the 16 GiB are sergqwer's fork (sergqwer/strata-nvfp4, -# 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 -# 4.9 s with every expert in RAM, against 118 tokens/s and 30 s in the budget mode. -UNSLOTH_RESIDENT_BESIDE_GB = 16 - - -def unsloth_budget(model, ram, gpu=None, asked=None) -> bool: - """Does setup write the RAM-budget mode (--resident-budget-gib) for this Unsloth file: asked for (--resident-budget-gib - 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 - measured on discrete cards only), or its experts with UNSLOTH_RESIDENT_BESIDE_GB beside them do not fit this PC's RAM - (GiB, ram_gb()). Else every expert is kept in RAM, as for ISTA's files.""" - return asked is not None or bool((gpu or {}).get("uma")) or \ - ram < MODELS[model]["arena_gb"] / 1.073741824 + UNSLOTH_RESIDENT_BESIDE_GB - - -UNSLOTH_IMAGES_MIN_VRAM_GB = 15.5 # a 16 GB card: the GPU encoder's ~1.4 GB is under a tenth of it - - -def unsloth_images_default(model, family, ram, gpu=None) -> bool: - """MODEL-UPDATE: is "images on" setup's default answer for this choice: Unsloth's files (the same base model and - image encoder as ISTA's, run end to end on CUDA and on HIP), on an NVIDIA card of 16 GB or more (the GPU encoder - keeps ~1.4 GB free) or, on AMD, wherever every expert stays in RAM (the CPU encoder takes no VRAM). Smaller cards - keep "no" as the default (asked, as for the other families).""" - if family != "unsloth" or not MODELS.get(model, {}).get("budget") or MODELS[model].get("vision") is False: - return False - g = gpu or {} - if str(g.get("arch", "")).startswith("gfx"): - return not unsloth_budget(model, ram, g) and not WIN - return g.get("vram_gb", 0.0) >= UNSLOTH_IMAGES_MIN_VRAM_GB - - -IMAGES_GPU_ENCODER_MIN_VRAM_GB = 23.5 # #2406: below this the images answer "yes" gets the CPU encoder (a card of 12-16 GB: the GPU - # encoder's ~1.1-1.4 GB is ~850 expert slots lost, 3-5% of decode and prompt on P100 / A4000 - # 16 GB (Linux, IQ3_S / IQ3_XXS), and 35-60% on an RTX 4080 SUPER under Windows as reported) - - -def flash_vision_encoder(asked: str, gpu: dict) -> str: - """#2406: which encoder a Flash-Next images answer gets on NVIDIA. "yes" (the question's y, or --vision yes) means the - 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 - keeps the ~1 GB of VRAM for experts. --vision gpu is always kept (with a note on a small card); --vision cpu is kept.""" - vram = float((gpu or {}).get("vram_gb") or 0.0) - small = 0 < vram < IMAGES_GPU_ENCODER_MIN_VRAM_GB - if asked == "gpu" and small: - 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% " - "of decode on 16 GB cards, more on some Windows PCs, #2406): kept as you chose; --vision cpu reads pictures " - "on the CPU instead (a few seconds each)") - if asked == "yes": - return "cpu" if small else "gpu" - return asked - - -UMA_EXPERTS = 24576 # the Flash-Next model's experts (48 layers x 512): the most an expert cache can hold - - -def uma_expert_cache(model, ram, budget_gib, kv_ram_gb=0.0): - """#1715: on a unified-memory APU (Strix Halo) the GPU's expert cache and the RAM budget of experts are both RAM. - `--expert-cache auto` sizes the cache from the memory the OS can give back at start, which counts all the RAM the - 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 - there setup writes a number, not `auto`: the RAM less UNSLOTH_RAM_LEFT_GB less the budget (and a KV cache streamed - 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 - (the config keeps `auto`). A recommendation: the number is in the config's args, and --expert-cache N there sets it.""" - slot_gib = MODELS[model]["arena_gb"] * 1e9 / UMA_EXPERTS * 1.1 / 2**30 - room = ram - UNSLOTH_RAM_LEFT_GB - budget_gib - math.ceil(kv_ram_gb) - slots = min(UMA_EXPERTS, int(room / slot_gib)) - return slots if slots >= 256 else None - - -def budget_choice(model, ram, asked) -> float: - """S4: UD-Q4_K_XL's RAM budget: --resident-budget-gib N as given, else the recommendation (resident_budget_gib). - More than the recommendation is kept, with what it risks (the owner's rule: setup recommends, it never forces).""" - rec = resident_budget_gib(model, ram) - if asked is None: - return rec - if asked > rec: - warn(f"a {asked:g} GiB RAM budget is more than setup recommends for this PC ({rec} GiB: the RAM less " - f"{UNSLOTH_RAM_LEFT_GB} GB for the OS, the engine and the file cache that reads the other experts). Kept " - "as you chose: the engine clamps it to the RAM it finds free at start (less 4 GB), and the file cache " - "gets less room - it may be slower, or run the PC out of RAM under load") - return int(asked) if asked == int(asked) else asked - - -def check_shards(shards): - """Every shard present and whole, or setup stops naming the file and the numbers. Whole means as long as - its own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part - renamed by hand, a download finished by an older setup) otherwise passes as a model file and the engine - fails much later, at the first tensor that runs past the end.""" - sys.path.insert(0, str(ROOT / "tools")) - from gguf_reader import GGUFFile - for s in shards: - if not s.exists(): - fail(f"missing {s}") - try: - g = GGUFFile(s) - except (ValueError, struct.error) as e: - fail(f"{s.name} is not a whole GGUF shard ({e})", "delete it and run setup again") - need = g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors), default=0) - have = s.stat().st_size - if not g.tensors: - # #2346: a metadata-only shard (Unsloth's UD-Q5_K_XL 00001, 10,946,618 bytes) ends at its header: the - # alignment padding before an empty data section is not in the file, so data_start can be past its end - need = min(need, have) - if have < need: - fail(f"{s.name} is short: {have:,} of {need:,} bytes ({need - have:,} missing)", - "delete it and run setup again (or copy the whole file into --gguf-dir)") - if len(g.tensors) == 1 and have - need >= 64: # (a few bytes may be the last tensor's alignment padding) - # #657: a shard that holds one tensor (the PLE table) is exactly as long as that tensor; extra bytes are a - # damaged or wrong file that the engine would refuse at start ("PLE table size mismatch") - fail(f"{s.name} is longer than its tensor: {have:,} bytes, {need:,} expected ({have - need:,} extra)", - f"delete {s.name} and its .done mark and run setup again") - - -def get_llama_cpp(vision=False): - """llama.cpp at the pinned commit (ggml for the build, gguf-py for the tools, mtmd for images), as a zip: no git. - `vision`: the image encoder's own newer checkout (VISION_LLAMA_CPP_COMMIT); the engines never use it.""" - if vision and VISION_LLAMA_CPP_COMMIT == LLAMA_CPP_COMMIT: - vision = False - commit = VISION_LLAMA_CPP_COMMIT if vision else LLAMA_CPP_COMMIT - llama = ROOT / "third_party" / (f"llama.cpp-{commit[:7]}" if vision else "llama.cpp") - if (llama / "ggml" / "CMakeLists.txt").exists() and (llama / "gguf-py").is_dir(): - return llama - z = ROOT / "third_party" / f"llama.cpp-{commit[:7]}.zip" - download(VISION_LLAMA_CPP_ZIP if vision else LLAMA_CPP_ZIP, z, "llama.cpp source") - tmp = ROOT / "third_party" / "_unpack" - shutil.rmtree(tmp, ignore_errors=True) - try: - with zipfile.ZipFile(z) as f: - # llama.cpp's own web UI (tools/ui) is not used, and its deep paths passed Windows' 260-character limit in a - # folder like Downloads\PolyStrata-main\PolyStrata-main (#206) - f.extractall(tmp, [m for m in f.namelist() if "/tools/ui/" not in m]) - except zipfile.BadZipFile: - # #1797: do not let the .done mark make every later run reuse a damaged source archive. - try: - drop_archive(z) - except OSError as e: - warn(f"cannot remove damaged {z.name} ({e}): delete it and its .done mark before running setup again") - raise - top = next(tmp.iterdir()) - shutil.rmtree(llama, ignore_errors=True) - # PR #63: on Windows a rename can fail with PermissionError while an antivirus scanner still holds a file of the - # fresh unpack; shutil.move falls back to copy-and-delete, and a few retries let the scanner finish. The target - # is `llama` itself - moving into its parent would keep the zip's `llama.cpp-` folder name. - for attempt in range(5): - try: - shutil.move(str(top), str(llama)) - break - except PermissionError: - if attempt == 4: - raise - shutil.rmtree(llama, ignore_errors=True) # a partial copy from the failed attempt - time.sleep(2) - shutil.rmtree(tmp, ignore_errors=True) - z.unlink(missing_ok=True) - z.with_name(z.name + ".done").unlink(missing_ok=True) - return llama - - -def req_name(line: str) -> str: - """The distribution name of a requirement line ("numpy==2.5.3; python_version >= '3.12'" -> "numpy").""" - return re.split(r"[\s<>=!~;\[]", line.strip(), maxsplit=1)[0].lower().replace("_", "-") - - -def requirement_lines(path: Path | None = None) -> list[str]: - """requirements.txt's requirements, comments and blank lines left out.""" - lines = [] - for raw in (path or REQUIREMENTS).read_text(encoding="utf-8").splitlines(): - line = raw.split("#", 1)[0].strip() - if line: - lines.append(line) - return lines - - -def _installed(name: str) -> bool: - try: - import importlib.metadata as md - md.distribution(name) - return True - except Exception: - return False - - -def pip_install(packages, what): - """pip install into .venv, skipped when the same list was installed before. An install from before the pinned - requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the - pinned dependencies it already has count as installed.""" - stamp = Path(sys.prefix) / ".strata-pip.json" - have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else [] - bare = {p.lower() for p in have if req_name(p) == p.lower()} - need = [p for p in packages if p not in have and req_name(p) not in bare - and not (bare and "==" in p and _installed(req_name(p)))] - if not need: - ok(f"{what} already installed") - return - say(f" Installing {what} ...") - run([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", *need]) - stamp.write_text(json.dumps(sorted(set(have) | set(need)), indent=0)) - ok(f"{what} installed") - - -def cuda_lib_dirs(toolkit=13): - """Where pip put NVIDIA's CUDA libraries (nvidia/cu13/bin/x86_64 on Windows, nvidia/cu13/lib on Linux). - toolkit 12: the CUDA 12 wheels' cuBLAS and runtime, in two folders (nvidia/cublas/bin, nvidia/cuda_runtime/bin).""" - if int(toolkit) == 12: - patterns = ("cublas64_12.dll", "cudart64_12.dll") if WIN else ("libcublas.so.12*", "libcudart.so.12*") - else: - patterns = ("cublas64_13.dll",) if WIN else ("libcublas.so.13*",) - dirs = [] - for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}: - for pattern in patterns: - for hit in (sp / "nvidia").rglob(pattern) if (sp / "nvidia").is_dir() else []: - if hit.parent not in dirs: - dirs.append(hit.parent) - return [str(d) for d in dirs] - - -# ------------------------------------------------------------------------------------------------ AMD -# The RX 7900 XT / XTX (gfx1100) and the RX 9070 series / Radeon AI PRO R9700 (gfx1201) on Linux, through the HIP -# backend (docs/AMD_HIP.md); the RX 7800 XT / 7700 XT (gfx1101, #254) and the RX 9060 XT (gfx1200, #256) were run by -# 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; -# a system ROCm 7 in /opt/rocm is used when it has hipcc and hipBLAS) and the engine is compiled here for the cards. -# No images yet. -ROCM_INDEXES = {"gfx1100": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", # TheRock's wheels per GPU family - "gfx1101": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", - "gfx1102": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", - "gfx1200": "https://rocm.nightlies.amd.com/v2/gfx120X-all/", - "gfx1201": "https://rocm.nightlies.amd.com/v2/gfx120X-all/", - "gfx1030": "https://rocm.nightlies.amd.com/v2/gfx103X-all/", - "gfx1031": "https://rocm.nightlies.amd.com/v2/gfx103X-all/", - "gfx1151": "https://rocm.nightlies.amd.com/v2/gfx1151/", # Strix Halo (docs/STRIX_HALO.md) - "gfx1150": "https://rocm.nightlies.amd.com/v2/gfx1150/", # Strix Point: only with STRATA_EXPERIMENTAL_GFX1150=1 - "gfx1103": "https://rocm.nightlies.amd.com/v2/gfx110X-all/"} # Radeon 780M: only with STRATA_EXPERIMENTAL_GFX1103=1 -# The TheRock nightly indexes are pruned and move on, and each GPU family's index holds its own range (#1103: gfx103X-all -# 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 -# version for every card cannot work. The wheel is chosen per index (the family): a preferred version, tried first; when -# 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). -# STRATA_ROCM_VERSION still forces one exact version (no lookup). -ROCM_VERSION_DEFAULT = "7.10.0a20251120" # what PolyStrata's HIP build was tested with (gfx120X, gfx110X) -ROCM_FAMILY_PINS = {"gfx103X-all": "7.13.0a20260515", # #1103: 7.13.0a20260515 runs; the 7.14 nightlies time out - "gfx110X-all": "7.10.0a20251121", # the experimental gfx1103: this index has no ...20251120 - "gfx1151": "7.14.0a20260608"} # #1267: 7.14.0a20260529 to 20260608 run on kernel 7.2.8; the 7.10 wheel segfaults -ROCM_VERSION_OVERRIDE = os.environ.get("STRATA_ROCM_VERSION") or None -ROCM_VERSION = ROCM_VERSION_OVERRIDE or ROCM_VERSION_DEFAULT # kept for callers that read one version -ROCM_SYSTEM_MIN = (7, 0) # an older system ROCm is passed over for the wheels (gfx1201 needs ROCm 6.4 or newer) -# STRATA_EXPERIMENTAL_GFX1103=1 (opt-in, unsupported): the Radeon 780M / 760M / 740M iGPU (Ryzen 7040 / 8040, gfx1103) is taken -# as a unified-memory AMD card like Strix Halo, with the native dot4 and gfx11 WMMA kernels, the gfx1103 exact speed switches -# and a hipBLASLt table when one matches (measured on one machine: Ryzen 7 8745HS). Unset: unchanged. -GFX1103_OPT_IN = os.environ.get("STRATA_EXPERIMENTAL_GFX1103") == "1" -# STRATA_EXPERIMENTAL_GFX1150=1 (opt-in, unvalidated): the Radeon 890M / 880M iGPU (Ryzen AI 300, Strix Point, gfx1150) -# is taken as a unified-memory AMD card like Strix Halo. The engine builds and runs for gfx1150 from 0.1.40.2 (#1217; -# tools/hip/gfx1150-hipblaslt-100401.txt is calibrated on it), but no release ships a ready-made Windows engine for it: -# build one with `STRATA_HIP_ARCHS=gfx1150 tools\hip\build_windows.bat` and start setup with `--prebuilt dist\`. -# Unset: unchanged. -GFX1150_OPT_IN = os.environ.get("STRATA_EXPERIMENTAL_GFX1150") == "1" -AMD_ARCHS = ("gfx1100", "gfx1101", "gfx1102", "gfx1200", "gfx1201", "gfx1030", "gfx1031", "gfx1151") \ - + (("gfx1103",) if GFX1103_OPT_IN else ()) + (("gfx1150",) if GFX1150_OPT_IN else ()) -# The exact (bit-identical) speed switches the engine turns on by default on gfx1151 (src/core/arch_defaults.cpp), less -# STRATA_HCD_EXACT: that one copies the gfx1151 hipBLASLt table's solutions 1176 / 1177, and the gfx1103 table -# (tools/hip/gfx1103-hipblaslt-100401.txt) picks others, so it would only report that it cannot run. A gfx1103 install -# takes them from here (setup writes them into the config's "env"), the same way the table is written: one 780M measured -# the same greedy answers with all 17 on and with all 17 off, +13% to +15% prompt and decode +3.2% (the decode half -# alone). The engine keeps gfx1103 out of its own arch defaults (src/core/arch_defaults_test.cpp asserts it stays -# empty), so this keeps the default path byte-identical. -GFX1103_SWITCHES = { - # prompt - "STRATA_GDN_HEAD": "1", "STRATA_GDN_PP": "2", "STRATA_GDN_CONVL2": "1", "STRATA_GDN_NOY": "1", - "STRATA_CVEC_FUSE": "1", "STRATA_PF_PAD": "1", - # decode - "STRATA_Q8_PACKED": "1", "STRATA_Q6_PACKED": "1", "STRATA_MMVF_ROWS": "1", "STRATA_ATTN_LANECELL": "1", - "STRATA_EXPERT_V2": "1", "STRATA_TSUM": "1", "STRATA_LFUSE": "1", "STRATA_GDN_SPLIT": "1", - "STRATA_QFUSE": "1", "STRATA_PLE_BATCH": "1", "STRATA_SH_STREAM": "1", -} -# The same set for a gfx1150 install (Radeon 890M / 880M): less STRATA_HCD_EXACT as well, because a gfx1150 table picks other -# solutions than the gfx1151 one. The Radeon 890M report (docs/AMD_HIP.md; bench/results/2026-10-07-community-gfx1150) measured the -# 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 -# for gfx1150 (src/core/arch_defaults_test.cpp asserts gfx1150 stays empty), so this keeps the default path byte-identical. -GFX1150_SWITCHES = dict(GFX1103_SWITCHES) -AMD_NAMES = {"gfx1100": "AMD Radeon RX 7900 series (gfx1100)", # when sysfs has no product name - "gfx1101": "AMD Radeon RX 7800 XT / 7700 XT (gfx1101)", - "gfx1102": "AMD Radeon RX 7600 / 7600 XT (gfx1102)", - "gfx1200": "AMD Radeon RX 9060 series (gfx1200)", - "gfx1201": "AMD Radeon RX 9070 series / AI PRO R9700 (gfx1201)", - "gfx1030": "AMD Radeon RX 6800 / 6900 series (gfx1030)", - "gfx1031": "AMD Radeon RX 6700 XT series (gfx1031)", - "gfx1151": "AMD Radeon 8060S / 8050S / 8040S (Ryzen AI Max, Strix Halo, gfx1151)", - # integrated Radeons of other Ryzen families: named so they are not taken for Strix Halo (not supported) - "gfx1150": "AMD Radeon 890M / 880M (Ryzen AI 300, Strix Point, gfx1150)", - "gfx1152": "AMD Radeon 860M / 840M (Ryzen AI 300, Krackan Point, gfx1152)", - "gfx1103": "AMD Radeon 780M / 760M / 740M (Ryzen 7040 / 8040, Phoenix / Hawk Point, gfx1103)"} -AMD_CARDS = ("the RX 7900 XT / XTX (gfx1100), RX 7800 XT / 7700 XT (gfx1101), RX 9060 XT (gfx1200) and " - "RX 9070 / 9070 XT / Radeon AI PRO R9700 (gfx1201), and the RX 6800 / 6900 series (gfx1030) and RX 6700 XT " - "(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, " - "gfx1151: experimental, docs/STRIX_HALO.md)") - - -def rocm_index(arch): - return os.environ.get("STRATA_ROCM_INDEX") or ROCM_INDEXES[arch] - - -def rocm_family(index): - """The family name of a TheRock index url (.../v2/gfx103X-all/ -> gfx103X-all).""" - return index.rstrip("/").rsplit("/", 1)[-1] - - -def rocm_vkey(version): - """Sort key of a TheRock version: 7.13.0a20260515 -> (7, 13, 0, 20260515); None when it is not one.""" - m = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)(?:[a-z]+(\d+))?", version) - return tuple(int(g or 0) for g in m.groups()) if m else None - - -def rocm_index_versions(html): - """The versions of the `rocm` package that a TheRock index page (/rocm/) lists, oldest first.""" - return sorted({m for m in re.findall(r"rocm-(\d+\.\d+\.\d+(?:[a-z]+\d+)?)\.(?:tar\.gz|whl)", html or "") - if rocm_vkey(m)}, key=rocm_vkey) - - -def rocm_pick(available, preferred): - """(version, note) for an index that lists `available`: `preferred` when it is there, else the newest of the same - 7.x line, else the newest of the same major (the note says so); `preferred` unchanged when the list is empty (the - index could not be read: pip then reports its own error) or nothing of that major exists (the note says so).""" - if not available or preferred in available: - return preferred, None - want = rocm_vkey(preferred) - for same, what in ((lambda k: k[:2] == want[:2], "line"), (lambda k: k[0] == want[0], "major")): - hits = [v for v in available if same(rocm_vkey(v))] - if hits: - got = max(hits, key=rocm_vkey) - return got, (f"ROCm {preferred} is not on this index any more: using {got}, the newest of the same {what} " - f"(set STRATA_ROCM_VERSION to choose another)") - return preferred, (f"ROCm {preferred} is not on this index and nothing of its major version is: " - f"{available[0]} to {available[-1]} are (set STRATA_ROCM_VERSION to one of them)") - - -def rocm_wanted(index, listing=None): - """(ROCm wheel version, warning or None) for a TheRock index (see ROCM_FAMILY_PINS). `listing` is the index - page's html (None: fetched from /rocm/; a failed fetch keeps the preferred version).""" - if ROCM_VERSION_OVERRIDE: - version, note = ROCM_VERSION_OVERRIDE, None - else: - preferred = ROCM_FAMILY_PINS.get(rocm_family(index), ROCM_VERSION_DEFAULT) - if listing is None: - try: - req = urllib.request.Request(index.rstrip("/") + "/rocm/", headers={"User-Agent": "strata-setup"}) - with urllib.request.urlopen(req, timeout=30) as r: - listing = r.read().decode("utf-8", "replace") - except (OSError, ValueError): - listing = "" - version, note = rocm_pick(rocm_index_versions(listing), preferred) - if rocm_family(index) == "gfx1151" and (rocm_vkey(version) or (9, 0))[:2] < (7, 11): - note = ((note + "; ") if note else "") + ( - "the ROCm 7.10 wheels segfault in the HSA runtime on a Strix Halo with a new kernel (7.2.8, #1267): " - "the 7.14 line (docs/STRIX_HALO.md) is the one that works") - return version, note - - -# Strix Halo (Ryzen AI Max 380 / 385 / 390 / 395 + PRO: Radeon 8040S / 8050S / 8060S, RDNA 3.5, gfx1151) and the other -# integrated Radeons it must never be taken for. pci.ids lists ONE device id for the whole Strix Halo family -# ("1586 Strix Halo [Radeon Graphics / Radeon 8050S Graphics / Radeon 8060S Graphics]"; the 8040S shares it: the -# three differ by their CU count, 40 / 32 / 16, not by id). Aurora's real answers (tools/test_setup_strix_halo.py): -# KFD gfx_target_version 110501, vendor_id 4098, device_id 5510 (0x1586), simd_count 80. -STRIX_HALO_ARCH = "gfx1151" -STRIX_HALO_PCI_IDS = frozenset({0x1586}) -AMD_IGPU_PCI = {0x1586: "gfx1151", # Strix Halo - 0x150E: "gfx1150", # Strix Point: Radeon 880M / 890M - 0x1114: "gfx1152", 0x1902: "gfx1152", # Krackan Point (Krackan2): Radeon 840M / 860M - 0x15BF: "gfx1103", 0x15C8: "gfx1103", 0x164F: "gfx1103", # Phoenix: Radeon 740M / 760M / 780M - 0x1900: "gfx1103", 0x1901: "gfx1103"} # Hawk Point -STRIX_HALO_BY_SIMDS = {80: "8060S", 64: "8050S", 32: "8040S"} # KFD simd_count (2 per CU): 40 / 32 / 16 CUs -UMA_OS_LEFT_GB = 6 # the share of the unified memory kept for the OS: what the engine's device_free_bytes() leaves - - -def gfx_arch_is(arch, name) -> bool: - """include/strata/kernels/gfx_arch.hpp's gfx_arch_is: `arch` (gcnArchName, "gfx1151" or "gfx1151:sramecc-:xnack-") - is exactly `name`, never a prefix: gfx1150 and gfx1152 are not gfx1151 (and gfx1151 is not gfx115).""" - arch = str(arch or "") - return arch == name or arch.startswith(name + ":") - - -def is_strix_halo(g) -> bool: - return isinstance(g, dict) and gfx_arch_is(g.get("arch"), STRIX_HALO_ARCH) - - -def is_uma_apu(g) -> bool: - """A unified-memory AMD APU whose "VRAM" is a BIOS carve-out plus shared system memory: Strix Halo (gfx1151), and - the opt-in gfx1150 (Strix Point) / gfx1103 (Phoenix / Hawk Point) iGPUs. Everything else is a discrete card.""" - arch = g.get("arch") if isinstance(g, dict) else None - return (is_strix_halo(g) - or (GFX1150_OPT_IN and gfx_arch_is(arch, "gfx1150")) - or (GFX1103_OPT_IN and gfx_arch_is(arch, "gfx1103"))) - - -def amd_apply_uma(g: dict, gtt_gb: float = 0.0, ram: float | None = None) -> dict: - """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 - maintainers' box) and the GPU also reaches shared system memory (Linux: the GTT pool, `mem_info_gtt_total`, half the - RAM unless the kernel was told otherwise; Windows: "shared GPU memory", half the RAM). The shared part IS the RAM - the model's experts live in, so it is not extra room beside the RAM. g gets: uma, dedicated_gb (the carve-out: the - only part that adds to the RAM, which the low-RAM mode counts) and vram_gb = the memory the GPU can use in all - (the carve-out plus the shared pool less what the OS keeps), which sizes the context and the parallel slots.""" - if g.get("uma") or not is_uma_apu(g): - return g - ram = ram_gb() if ram is None else ram - carve = max(0.0, float(g.get("vram_gb") or 0.0)) - shared = gtt_gb if gtt_gb > 0 else ram / 2 - shared = max(0.0, min(shared, ram - UMA_OS_LEFT_GB)) - g.update({"uma": True, "dedicated_gb": carve, "shared_gb": shared, "vram_gb": carve + shared}) - return g - - -def low_ram_vram(g) -> float: - """The GPU memory the low-RAM mode may count as room beside the RAM: a discrete card's VRAM; an APU's BIOS - carve-out only (its shared memory is the RAM itself).""" - return g.get("dedicated_gb", 0.0) if g.get("uma") else g["vram_gb"] - - -def amd_mem_text(g) -> str: - """How setup says a card's memory: "24 GB VRAM", or for an APU its unified memory.""" - if g.get("uma"): - return (f"unified memory: {g['dedicated_gb']:.1f} GB BIOS carve-out + {g['shared_gb']:.0f} GB shared with the " - f"RAM, {g['vram_gb']:.0f} GB usable by the GPU") - return f"{g['vram_gb']:.0f} GB VRAM" - - -STRIX_HALO_FAMILY, STRIX_HALO_MODEL = "unsloth", "UD-IQ4_XS" # the model docs/STRIX_HALO.md measures -STRIX_HALO_MIN_GB = 80 # UD-IQ4_XS keeps all of its experts in memory from ~80 GB (its menu line says so) - - -RECOMMENDED_SIZES = {"qwen": ("IQ3_S",), "swift": ("IQ3_S",), "unsloth": ("UD-Q4_K_XL", "UD-IQ4_XS")} # owner's pick, 0.1.44 - - -def recommended_size(family: str, names: list, ram: float) -> str: - """The size the menu pre-selects (and --yes takes): the family's recommended size when this PC's RAM fits it - (UD-Q4_K_XL before UD-IQ4_XS), else the largest size that fits, else the first. Recommend, never force: every - other size stays a choice.""" - for m in RECOMMENDED_SIZES.get(family, ()): - if m in names and ram >= MODELS[m]["ram_gb"]: - return m - fitting = [m for m in names if ram >= MODELS[m]["ram_gb"]] - if fitting: - return max(fitting, key=lambda m: MODELS[m]["download_gb"]) - return "UD-IQ4_XS" if family == "unsloth" and "UD-IQ4_XS" in names else names[0] - - -def size_tag(family: str, m: str, installed: str | None = None) -> str: - rec, have = m in RECOMMENDED_SIZES.get(family, ()), m == installed - return " (recommended, installed)" if rec and have else " (recommended)" if rec else " (installed)" if have else "" - - -def installed_size(family: str, names: list, have: list) -> str | None: - """0.1.44.1: the size of this family that is already installed (the most recently used config first), or None. Setup - run again (SETUP.bat, --setup) pre-selects it: the 0.1.44 recommendation (IQ3_S, about 15% slower than IQ3_XXS and - 7 GB more RAM) is for a first install, and Enter must not move an installed model to another size.""" - for c in have: - try: - ch = choices_from_config(c) - except (OSError, ValueError, KeyError, TypeError, IndexError): - continue - if ch.get("family") == family and ch.get("model") in names: - return ch["model"] - return None - - -def unsloth_default_env(family: str, model: str, hip: bool, in_budget: bool) -> dict: - """0.1.44 (owner, review-quants.md section 5): the run-config "env" setup writes for Unsloth's files. - 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 - or better than the FP16 path's; UD-Q4_K_XL keeps it opt-in. STRATA_HC_Q8=1 on CUDA for the UD-* files (the - GGUF's own Q8_0 hyper-connection projections, closer to the file and faster; the GSQ-RCO packs are untouched). - STRATA_ROUTE_TAIL_SKIP=0 where every expert is in RAM (the skip costs KL there); the RAM-budget mode keeps it.""" - env = {} - if family != "unsloth": - return env - if model in ("UD-Q5_K_XL", "UD-Q6_K_XL"): - env["STRATA_MMQ_KQ"] = "1" - if not hip and model.startswith("UD-"): - env["STRATA_HC_Q8"] = "1" - if not in_budget: - env["STRATA_ROUTE_TAIL_SKIP"] = "0" - return env - - -def menu_families(hip: bool) -> list: - """The families the model menu lists, in menu order. The NVFP4 packs run on NVIDIA cards only (the AMD and Intel - engines have no NVFP4 kernels), so on those the menu does not offer them; `--family nvfp4` still says why not.""" - return [f for f in FAMILIES if not (hip and FAMILIES[f].get("ready"))] - - -def nvfp4_card_note(gpu) -> str: - """What the NVFP4 menu line says about this NVIDIA card: RTX 50 (Blackwell, sm_120) has FP4 tensor cores; on older - RTX cards the experts run at 8-bit precision, which measured slower than UD-IQ4_XS (docs/NVFP4.md).""" - try: - arch = int((gpu or {}).get("arch") or 0) - except (TypeError, ValueError): - arch = 0 - if arch >= 120: - return "native FP4 on this card" - return "runs, but UD-IQ4_XS is faster on this card" - - -def nvfp4_cpu_note(avx2: bool, avx512: bool) -> str: - """What the NVFP4 menu line and the install step say about this CPU (#2347). Its experts that stay on the CPU run - on AVX-512 rows when the CPU has them, else on AVX2 rows (bit-equal to ggml's AVX2 dot). Measured (docs/NVFP4.md): - 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 - tokens a window (Ryzen 7 255: 58.9 vs 58.7 GB/s) and ~12% apart at four. A note only: nothing is refused.""" - if avx512 or not avx2: - return "" # no AVX2 at all: the older-CPU build's own warning says it - return ("this CPU has no AVX-512, so NVFP4's CPU rows run on AVX2: about as fast when memory-bound, up to ~12% " - "slower on 4-token windows") - - -def family_menu_note(family: str, hip: bool, gpu, avx2: bool = True, avx512: bool = True) -> str: - """The card-, CPU- and RAM-dependent tail of a family's line in the model menu.""" - if family == "nvfp4": - d = MODELS["NVFP4"] - cpu = nvfp4_cpu_note(avx2, avx512) - return (f" [{nvfp4_card_note(gpu)}; {d['download_gb']:.0f} GB download, ~{d['ram_gb']} GB of RAM keeps every " - "expert in RAM" + (f"; {cpu}" if cpu else "") + "]") - if family == "unsloth" and hip: - return " [UD-IQ4_XS is the 4-bit choice on AMD and Intel cards; NVFP4 runs on NVIDIA only]" - return "" - - -def strix_halo_recommends(gpu, ram) -> bool: - """Is UD-IQ4_XS the recommended model here: a Strix Halo whose unified memory (the OS's RAM plus the BIOS carve-out) - holds it - the model docs/STRIX_HALO.md measures. A recommendation only: the menus still list every size.""" - return is_strix_halo(gpu) and bool(gpu.get("uma")) and ram + gpu.get("dedicated_gb", 0.0) >= STRIX_HALO_MIN_GB - - -def amd_device_access_problem(dev="/dev", access=os.access, listing=glob.glob) -> str | None: - """Linux AMD: /dev/kfd and the render nodes must be readable and writable by this user (the render / video groups). - None when they are, else a sentence for the user. A missing /dev/kfd is not this problem (no driver / no ROCm).""" - kfd = os.path.join(dev, "kfd") - if not os.path.exists(kfd): - return None - bad = [kfd] if not access(kfd, os.R_OK | os.W_OK) else [] - bad += [n for n in sorted(listing(os.path.join(dev, "dri", "renderD*"))) if not access(n, os.R_OK | os.W_OK)] - if not bad: - return None - return (f"this user cannot open {', '.join(bad)}: ROCm will find no GPU and the engine will fail with 'no ROCm-capable " - "device' although nothing else holds the GPU. Add your user to the render and video groups: " - "sudo usermod -aG render,video $USER, then log out and in again") - - -def gfx1103_notes(gpu, ram) -> list[str]: - """What setup tells the owner of a Radeon 780M / 760M / 740M (Phoenix / Hawk Point, gfx1103, unified memory): never - the Strix Halo text, which is about another chip (gfx1151). Opt-in only (STRATA_EXPERIMENTAL_GFX1103=1).""" - notes = [f" Radeon 780M / 760M class (gfx1103, Ryzen 7040 / 8040): the CPU and the GPU share one memory pool ({ram:.0f} GB " - f"seen by the OS + a {gpu.get('dedicated_gb', 0.0):.1f} GB BIOS carve-out), so the model's experts live in " - "that pool and the expert cache is sized from the memory the OS can give back."] - notes.append(" " + ("The engine is compiled here for gfx1103" if not WIN else "This GPU has no ready-made Windows engine") - + " with the native dot4 and WMMA kernels and the 780M's exact speed switches" - + " (experimental opt-in, STRATA_EXPERIMENTAL_GFX1103=1; measured on one machine, not validated on a real " - "card): see docs/AMD_HIP.md and docs/RADEON_780M.md. This is not a Strix Halo.") - if not WIN and gpu.get("shared_gb", 0) < 0.75 * ram - 1: - notes.append(f"!the GPU can reach {gpu.get('shared_gb', 0):.0f} GB of shared memory (the GTT pool; the kernel's " - "default is about half of the RAM). The kernel option ttm.pages_limit raises it; setup changes no " - "host setting - a bigger model needs the room, a smaller one runs as it is") - return notes - - -def gfx1150_notes(gpu, ram) -> list[str]: - """What setup tells the owner of a Radeon 890M / 880M (Ryzen AI 300, Strix Point, gfx1150, unified memory): never - the Strix Halo text, which is about another chip (gfx1151). Opt-in only (STRATA_EXPERIMENTAL_GFX1150=1).""" - notes = [f" Radeon 890M / 880M class (gfx1150, Strix Point): the CPU and the GPU share one memory pool ({ram:.0f} GB " - f"seen by the OS + a {gpu.get('dedicated_gb', 0.0):.1f} GB BIOS carve-out), so the model's experts live in " - "that pool and the expert cache is sized from the memory the OS can give back."] - notes.append(" " + ("The engine is compiled here for gfx1150" if not WIN else - "Windows has no ready-made engine for gfx1150: build one with STRATA_HIP_ARCHS=gfx1150 " - "tools\\hip\\build_windows.bat and start setup with --prebuilt dist\\") - + " (experimental opt-in, STRATA_EXPERIMENTAL_GFX1150=1, unvalidated: docs/AMD_HIP.md).") - if not WIN and gpu.get("shared_gb", 0) < 0.75 * ram - 1: - notes.append(f"!the GPU can reach {gpu.get('shared_gb', 0):.0f} GB of shared memory (the GTT pool; the kernel's " - "default is about half of the RAM). The kernel option ttm.pages_limit raises it; setup changes no " - "host setting - a bigger model needs the room, a smaller one runs as it is") - return notes - - -def igpu_notes(gpu, ram) -> list[str]: - """The unified-memory notes for exactly this chip: Strix Halo (gfx1151) or the gfx1150 / gfx1103 opt-in, nothing else.""" - if is_strix_halo(gpu): - return strix_halo_notes(gpu, ram) - if GFX1150_OPT_IN and gfx_arch_is(gpu.get("arch"), "gfx1150"): - return gfx1150_notes(gpu, ram) - if gfx_arch_is(gpu.get("arch"), "gfx1103"): - return gfx1103_notes(gpu, ram) - return [] - - -def strix_halo_notes(gpu, ram) -> list[str]: - """What setup tells a Strix Halo owner (a leading "!" = a warning): the unified memory, the build, the guide, and the - memory settings that give the GPU room. Nothing is changed or refused: recommend, never force.""" - notes = [f" Strix Halo (gfx1151, Ryzen AI Max): the CPU and the GPU share one memory pool ({ram:.0f} GB seen by the " - f"OS + a {gpu.get('dedicated_gb', 0.0):.1f} GB BIOS carve-out), so the model's experts live in that pool " - "and the expert cache is sized from the memory the OS can give back, not from the carve-out."] - notes.append(" " + ("The engine is compiled here for gfx1151" if not WIN else "Windows uses the ready-made AMD engine, " - "which must be built for gfx1151") - + " (experimental, measured on one machine): see docs/STRIX_HALO.md.") - if not WIN and gpu.get("shared_gb", 0) < 0.75 * ram - 1: - notes.append(f"!the GPU can reach {gpu.get('shared_gb', 0):.0f} GB of shared memory (the GTT pool; the kernel's " - f"default is about half of the RAM). docs/STRIX_HALO.md boots with ttm.pages_limit and " - "ttm.page_pool_size to give it most of the RAM; setup changes no host setting - a bigger model " - "needs the room, a smaller one runs as it is") - if gpu.get("dedicated_gb", 0.0) > 16: - notes.append(f"!the BIOS carve-out is {gpu['dedicated_gb']:.0f} GB: that memory is taken from the OS, while the GPU " - "reaches the shared memory anyway. A small carve-out (the BIOS's default or 512 MB - 2 GB) leaves " - "the RAM to the model") - if strix_halo_recommends(gpu, ram): - notes.append(f" Recommended model: {STRIX_HALO_MODEL} (the one docs/STRIX_HALO.md measures); the menus list the " - "others.") - return notes - - -def amd_rank(g): - """The order setup picks a card in, best first: a discrete card before an APU (its own GDDR is faster than the - shared LPDDR5X), then the most memory. A Strix Halo beside a Radeon RX / PRO card is therefore left to --gpu N.""" - return (bool(g.get("uma")), -round(g["vram_gb"]), g["index"]) - - -def amd_pci_devices(sysfs="/sys") -> list[dict]: - """The AMD (vendor 0x1002) display devices the kernel lists in /sys/class/drm/card*/device, as [{"pci_id", - "vram_gb", "gtt_gb", "arch"}] with the arch AMD_IGPU_PCI knows ("" when it does not). The KFD topology answers the - same without ROCm; this one only names a card the topology does not list (a kernel without /dev/kfd).""" - found = [] - base = Path(sysfs) / "class/drm" - if not base.is_dir(): - return found - for card in sorted(base.glob("card[0-9]*")): - if not card.name[4:].isdigit(): - continue - try: - dev = card / "device" - if int((dev / "vendor").read_text().strip(), 16) != 0x1002: - continue - did = int((dev / "device").read_text().strip(), 16) - except (OSError, ValueError): - continue - row = {"pci_id": did, "arch": AMD_IGPU_PCI.get(did, ""), "vram_gb": 0.0, "gtt_gb": 0.0} - for key, f in (("vram_gb", "mem_info_vram_total"), ("gtt_gb", "mem_info_gtt_total")): - try: - row[key] = int((dev / f).read_text()) / 2 ** 30 - except (OSError, ValueError): - pass - found.append(row) - return found - - -def amd_gpus(sysfs="/sys"): - """AMD GPUs from the kernel's KFD topology (the amdgpu driver; no ROCm needed), numbered as HIP numbers them: - the GPU nodes in order, the CPU nodes skipped. Integrated GPUs are listed too (not supported). - sysfs: the tree to read (tools/test_setup_amd.py passes a mocked one). Windows: amd_gpus_win.""" - if WIN: - return amd_gpus_win() - base = Path(sysfs) / "class/kfd/kfd/topology/nodes" - found = [] - if not base.is_dir(): - return found - for node in sorted((p for p in base.iterdir() if p.name.isdigit()), key=lambda p: int(p.name)): - try: - props = {} - for line in (node / "properties").read_text().splitlines(): - k, _, v = line.partition(" ") - props[k] = v.strip() - ver = int(props.get("gfx_target_version") or 0) - if ver == 0 or int(props.get("simd_count") or 0) == 0: - continue - except (OSError, ValueError): - continue - arch = f"gfx{ver // 10000}{(ver // 100) % 100:x}{ver % 100:x}" - dev = Path(sysfs) / f"class/drm/renderD{props.get('drm_render_minor', '')}/device" - try: - vram = int((dev / "mem_info_vram_total").read_text()) / 2 ** 30 - except (OSError, ValueError): - vram = 0.0 - try: - name = (dev / "product_name").read_text().strip() or f"AMD Radeon ({arch})" - except OSError: - name = f"AMD Radeon ({arch})" - if name == f"AMD Radeon ({arch})" and arch in AMD_NAMES: - name = AMD_NAMES[arch] - if gfx_arch_is(arch, STRIX_HALO_ARCH) and int(props.get("simd_count") or 0) in STRIX_HALO_BY_SIMDS: - name = (f"AMD Radeon {STRIX_HALO_BY_SIMDS[int(props['simd_count'])]} " - "(Ryzen AI Max, Strix Halo, gfx1151)") # the CU count tells the 8060S / 8050S / 8040S apart - try: - gtt = int((dev / "mem_info_gtt_total").read_text()) / 2 ** 30 - except (OSError, ValueError): - gtt = 0.0 - g = {"index": len(found), "name": name, "vram_gb": vram, "arch": arch, "driver": "amdgpu", "vendor": "amd"} - try: - g["pci_id"] = int((dev / "device").read_text().strip(), 16) - except (OSError, ValueError): - pass - found.append(amd_apply_uma(g, gtt)) # Strix Halo: unified memory (carve-out + shared) - return found - - -def amd_problem(g): - if g["arch"] not in AMD_ARCHS: - return (f"not supported - PolyStrata's AMD backend runs on {AMD_CARDS} only, this is {g['arch']}" - + (" (an integrated Radeon, not Strix Halo)" if g["arch"] in ("gfx1150", "gfx1152", "gfx1103") else "")) - if g.get("cannot_run"): # Windows: the installed engine's own check (--list-devices) - return g["cannot_run"] - return None - - -def amd_gpus_win() -> list[dict]: - """Windows: the AMD GPUs as the HIP runtime numbers them once the HIP engine is installed (hip_devices), else in - the display-adapter order (amd_gpus_windows).""" - hip = hip_devices() - if not hip: - return amd_gpus_windows() - halo = [g for g in hip if is_uma_apu(g)] - if halo: # an APU: the HIP runtime's figure is not the BIOS carve-out - reg = [r for r in amd_gpus_windows() if is_uma_apu(r)] - for k, g in enumerate(halo): - reported = g["vram_gb"] - g["vram_gb"] = reg[k]["dedicated_gb"] if k < len(reg) else 0.0 - amd_apply_uma(g) - g["vram_gb"] = max(g["vram_gb"], reported) - return hip - - -def amd_parse_gpus(text, amd) -> list: - """--gpus with AMD cards, numbered as HIP numbers them (setup's list): "1,0", or "all" (every supported card, the - most VRAM first). Every chosen card must be one PolyStrata supports (AMD_ARCHS; they may be of different - architectures: the engine is compiled for each). Returns the cards, the main one first.""" - usable = [g for g in amd if amd_problem(g) is None] - if str(text).strip().lower() == "all": - sel = [g["index"] for g in sorted(usable, key=amd_rank)] - else: - try: - sel = [int(x) for x in str(text).split(",") if x.strip()] - except ValueError: - fail(f"--gpus takes AMD GPU numbers as setup lists them, e.g. --gpus 1,0 (or --gpus all), not {text!r}") - if len(sel) < 2 or len(set(sel)) != len(sel): - fail("--gpus takes two or more different GPUs, e.g. --gpus 1,0 (one GPU: --gpu 1)", - "this PC has " + (f"{len(usable)} AMD card{'s' if len(usable) != 1 else ''} PolyStrata can use" - + (": " + ", ".join(f"GPU {g['index']} ({g['name']})" for g in usable) if usable else ""))) - byid = {g["index"]: g for g in amd} - for i in sel: - g = byid.get(i) - p = "not found on this PC" if g is None else amd_problem(g) - if p is not None: - fail(f"AMD GPU {i}{'' if g is None else ' (' + g['name'] + ')'} cannot be used: {p}", - ("use these together: --gpus " + ",".join(str(x["index"]) for x in usable)) if len(usable) >= 2 else - ("use one card: --gpu " + str(usable[0]["index"])) if usable else f"the AMD backend runs on {AMD_CARDS}") - return [byid[i] for i in sel] - - -# ------------------------------------------------------------------------------------------------ AMD on Windows -# Windows has no KFD topology: the cards are found from the display adapters (Win32_VideoController: the ones present, -# with their PCI ids) and the display-class registry (each adapter's 64-bit VRAM size), before any AMD software is -# needed. The engine is the ready-made HIP one (WIN_HIP_ASSET: strata.exe, strata-device.exe and the ROCm libraries it -# loads, built by tools/hip/build_windows.bat); it needs only the AMD driver. Once it is installed, the cards are -# numbered as the HIP runtime numbers them (`strata-device --list-devices`): an integrated Radeon takes HIP's device 0 -# and pushes the discrete card to 1, which the display-adapter order does not show (#325). -WIN_HIP_ASSET = "strata-windows-x64-hip.zip" -WIN_HIP_MIN_ENGINE = max(MIN_ENGINE, (0, 1, 33)) # the first release with a Windows HIP engine -WIN_AMD_DRIVER = "https://www.amd.com/en/support/download/drivers.html" -# PCI device ids (VEN_1002) of the cards the AMD backend knows; the names below cover a card whose id is not listed -_WIN_AMD_DID = {0x744C: "gfx1100", 0x7448: "gfx1100", 0x745E: "gfx1100", # RX 7900 XTX/XT/GRE, W7900, W7800 - 0x747E: "gfx1101", # RX 7800 XT / 7700 XT - 0x7480: "gfx1102", # RX 7600 / 7600 XT - 0x7590: "gfx1200", # RX 9060 XT - 0x7550: "gfx1201", 0x7551: "gfx1201", # RX 9070 / 9070 XT, AI PRO R9700 - 0x73BF: "gfx1030", 0x73AF: "gfx1030", 0x73A5: "gfx1030", # RX 6800 / 6800 XT / 6900 XT / 6950 XT - 0x73DF: "gfx1031", # RX 6700 XT / 6750 XT / 6800M (#881) - **AMD_IGPU_PCI} # Ryzen APUs: 0x1586 = Strix Halo (gfx1151) -_WIN_AMD_NAME = ((re.compile(r"\b80[456]0S\b", re.I), "gfx1151"), # Radeon 8060S / 8050S / 8040S - (re.compile(r"\b8[89]0M\b", re.I), "gfx1150"), # Radeon 890M / 880M - (re.compile(r"\b8[46]0M\b", re.I), "gfx1152"), # Radeon 860M / 840M - (re.compile(r"\b7[468]0M\b", re.I), "gfx1103"), # Radeon 780M / 760M / 740M - (re.compile(r"\b9070\b|R9700", re.I), "gfx1201"), - (re.compile(r"\b9060\b", re.I), "gfx1200"), - (re.compile(r"RX\s*7900|W7900|W7800", re.I), "gfx1100"), - (re.compile(r"RX\s*7800|RX\s*7700(?!\s*S)|W7700", re.I), "gfx1101"), - (re.compile(r"RX\s*7600|W7600|W7500", re.I), "gfx1102"), - (re.compile(r"RX\s*6800(?!\s*[MS])|RX\s*6900|RX\s*6950|W6800", re.I), "gfx1030")) -_DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" - - -def _win_display_adapters() -> list[dict]: - """The display adapters present ({"name", "pnp"}), from Win32_VideoController.""" - ps = ("Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name + '|' + $_.PNPDeviceID + '|' + " - "$_.AdapterRAM }") - text = out(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps]) - found = [] - for line in text.splitlines(): - parts = line.strip().split("|") - if len(parts) >= 2 and parts[1]: - ram = parts[2] if len(parts) > 2 else "" - found.append({"name": parts[0].strip(), "pnp": parts[1].strip(), - "ram": int(ram) if ram.strip().isdigit() else 0}) - return found - - -def _win_display_registry() -> list[dict]: - """Each display driver instance's description, matching PCI id and VRAM size (the 64-bit value; the WMI one stops - at 4 GB), from the display-class registry key - readable without admin.""" - found = [] - try: - import winreg - cls = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _DISPLAY_CLASS) - except (ImportError, OSError): - return found - i = 0 - while True: - try: - sub = winreg.EnumKey(cls, i) - except OSError: - break - i += 1 - if not sub.isdigit(): - continue - try: - key = winreg.OpenKey(cls, sub) - except OSError: - continue - vals = {} - for name in ("DriverDesc", "MatchingDeviceId", "HardwareInformation.qwMemorySize", "DriverVersion"): - try: - vals[name] = winreg.QueryValueEx(key, name)[0] - except OSError: - pass - found.append(vals) - return found - - -def _pci_device_id(text: str) -> int | None: - m = re.search(r"VEN_1002&DEV_([0-9A-F]{4})", str(text or ""), re.I) - return int(m.group(1), 16) if m else None - - -def win_amd_arch(device_id: int | None, name: str) -> str: - """A Windows AMD adapter's architecture from its PCI device id, else its name; "" when it is none PolyStrata knows - (an integrated Radeon, an older card).""" - if device_id in _WIN_AMD_DID: - return _WIN_AMD_DID[device_id] - return next((a for rx, a in _WIN_AMD_NAME if rx.search(name or "")), "") - - -def amd_gpus_windows(adapters=None, registry=None) -> list[dict]: - """The AMD display adapters present, in display-adapter order (setup's numbering until the HIP engine is - installed), with the arch PolyStrata would run them as ("" = unknown: listed, not supported). adapters / registry: - tools/test_setup_amd.py passes mocked ones.""" - adapters = _win_display_adapters() if adapters is None else adapters - registry = _win_display_registry() if registry is None else registry - if not adapters: # no WMI answer: the registry alone (it can list removed cards) - adapters = [{"name": r.get("DriverDesc", ""), "pnp": r.get("MatchingDeviceId", ""), "ram": 0} for r in registry] - used = set() - found = [] - for ad in adapters: - did = _pci_device_id(ad.get("pnp")) - if did is None: - continue # not an AMD (VEN_1002) PCI device - vram, driver = 0.0, "" - for k, r in enumerate(registry): # the same card's driver instance: its 64-bit VRAM size - if k in used or _pci_device_id(r.get("MatchingDeviceId")) != did: - continue - if r.get("DriverDesc") and ad.get("name") and r["DriverDesc"].strip() != ad["name"].strip(): - continue - used.add(k) - mem = r.get("HardwareInformation.qwMemorySize") - if isinstance(mem, bytes): - mem = int.from_bytes(mem[:8], "little") - vram = int(mem) / 2 ** 30 if isinstance(mem, int) and mem > 0 else 0.0 - driver = str(r.get("DriverVersion") or "") - break - if vram == 0.0 and ad.get("ram", 0) > 0: - vram = ad["ram"] / 2 ** 30 # WMI's 32-bit figure (at most 4 GB) - arch = win_amd_arch(did, ad.get("name", "")) - name = ad.get("name") or AMD_NAMES.get(arch, f"AMD Radeon (device {did:04X})") - g = {"index": len(found), "name": name, "vram_gb": vram, "arch": arch or f"unknown (PCI {did:04X})", - "driver": driver or "amd", "vendor": "amd", "pci_id": did} - found.append(amd_apply_uma(g)) # Strix Halo: the registry's figure is the BIOS carve-out only - return found - - -def engine_env(eng: Path) -> dict: - """The environment for running an installed engine's own programs (`strata --families`, `strata-device - --list-devices`): the ready-made Windows HIP engine keeps hipblas.dll / libhipblaslt.dll in its rocm/bin, which the - loader finds through PATH only (#2372: a launch without it shows a "not found" dialog per DLL and prints nothing).""" - env = dict(os.environ) - dirs = [str(d) for d in hip_lib_dirs(eng)] - if dirs: - env["PATH"] = os.pathsep.join(dirs + [env.get("PATH", "")]) - return env - - -def hip_devices(probe: Path | None = None, text: str | None = None) -> list[dict] | None: - """The GPUs the HIP runtime enumerates, numbered as HIP_VISIBLE_DEVICES numbers them, from the installed engine's - `strata-device --list-devices`; None when there is no HIP engine here or it does not answer. text: its output - (tests).""" - if text is None: - probe = probe or ROOT / "engine" / ("strata-device.exe" if WIN else "strata-device") - try: - hip_engine = json.loads((probe.parent / "BUILD.json").read_text(encoding="utf-8")).get("backend") == "hip" - except (OSError, ValueError): - hip_engine = False - if not probe.exists() or not hip_engine: - return None - try: - hip_runtime_beside_exe(probe.parent) # #468 #461: not the driver's System32 copy - r = subprocess.run([str(probe), "--list-devices"], capture_output=True, text=True, timeout=120, - cwd=str(probe.parent), env=engine_env(probe.parent)) - except (OSError, subprocess.TimeoutExpired): - return None - if r.returncode != 0: - return None - text = r.stdout - found = [] - for line in text.splitlines(): - m = re.match(r"device\s+(\d+):\s*(.*)$", line.strip()) - if m: - found.append({"index": int(m.group(1)), "name": m.group(2).strip(), "vram_gb": 0.0, "arch": "", - "driver": "hip", "vendor": "amd"}) - continue - if not found: - continue - a = re.match(r"arch\s+(gfx[0-9a-f]+)\s*,\s*([\d.]+)\s*GiB", line.strip()) - if a and not found[-1]["arch"]: - found[-1]["arch"], found[-1]["vram_gb"] = a.group(1), float(a.group(2)) - elif line.strip().startswith("cannot run:"): - found[-1]["cannot_run"] = line.strip()[len("cannot run:"):].strip() - for g in found: - if not g["arch"]: - g["arch"] = "unknown" - if g["arch"] in AMD_NAMES and g["name"] in ("", "AMD Radeon Graphics"): - g["name"] = AMD_NAMES[g["arch"]] - return found - - -def hip_lib_dirs(eng: Path) -> list[Path]: - """Where the ready-made Windows HIP engine's ROCm DLLs are (its BUILD.json "lib_dirs", relative to engine/).""" - try: - rel = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("lib_dirs") or [] - except (OSError, ValueError): - rel = [] - return [eng / d for d in rel if (eng / d).is_dir()] - - -# #468 #461: the HIP runtime the ready-made engine was built with, next to strata.exe. Windows looks for an imported -# DLL in the exe's folder, then System32, and only then on PATH (where rocm/bin is): an AMD driver that installs its own -# amdhip64_7.dll in System32 won, and the bundled rocBLAS/hipBLAS ran on that runtime - an access violation (W7900) or -# hipErrorInvalidDeviceFunction (7900 XTX) on the first prompt. Only the runtime and the compiler it loads by name: -# rocBLAS/hipBLASLt stay in rocm/bin, where they find their kernel libraries and ../.kpack. -HIP_RUNTIME_DLLS = ("amdhip64_*.dll", "amd_comgr*.dll") - - -def hip_runtime_closure(d: Path) -> list[str]: - """The DLLs of `d` (the engine's rocm/bin) that amdhip64_7.dll and amd_comgr.dll need, the two included, read from - their PE import tables and followed recursively (tools/hip/dll_closure.py). #461: amdhip64_7.dll imports - rocm_kpack.dll, which imports the MSVC runtime; with only the two DLLs beside strata.exe the full-path load fails - (error 126), Windows falls back to System32's copy of the runtime, and the first big prompt dies with - hipErrorInvalidDeviceFunction. Falls back to the names above when the helper cannot be read.""" - roots = sorted({p.name for pat in HIP_RUNTIME_DLLS for p in d.glob(pat)}) - try: - sys.path.insert(0, str(ROOT / "tools" / "hip")) - from dll_closure import dll_closure - return dll_closure(d, roots) - except Exception: # noqa: BLE001 - a missing helper must not stop setup - return roots - finally: - if str(ROOT / "tools" / "hip") in sys.path: - sys.path.remove(str(ROOT / "tools" / "hip")) - - -def hip_runtime_beside_exe(eng: Path) -> None: - """Copy the bundled HIP runtime DLLs and everything they import from rocm/bin next to the engine's exes when - missing or different (a 0.1.34 install, whose zip had them in rocm/bin only, is fixed on its next start; a - 0.1.40.2 install, which got only the two runtime DLLs, gets rocm_kpack.dll and the C++ runtime now, #461).""" - for d in hip_lib_dirs(eng): - for name in hip_runtime_closure(d): - src = d / name - dst = eng / src.name - try: - if dst.exists() and dst.stat().st_size == src.stat().st_size and \ - dst.stat().st_mtime >= src.stat().st_mtime: - continue - shutil.copy2(src, dst) - except OSError as e: # e.g. the engine is running and holds the old copy - warn(f"could not put {src.name} next to the AMD engine ({e}); if the engine stops on its first " - "request, close PolyStrata and run START-HERE.bat again") - - -def hip_match(card: dict, listed: list[dict], hip: list[dict]) -> dict | None: - """The HIP device that is setup's `card` (from `listed`, the display-adapter order): the k-th device of the same - architecture, k = the card's rank among the listed cards of that architecture. None when HIP has no such card.""" - same = [g["index"] for g in listed if g["arch"] == card["arch"]] - k = same.index(card["index"]) if card["index"] in same else 0 - cand = [g for g in hip if g["arch"] == card["arch"]] - return cand[k] if k < len(cand) else None - - -def hip_card(eng: Path, gpu: dict, listed: list[dict]) -> dict: - """Windows: setup's chosen AMD card as the installed HIP engine numbers it (HIP_VISIBLE_DEVICES), checked by the - engine itself before the model download: an integrated Radeon is HIP's device 0 (#325), and a PC without a - working AMD driver stops here with what to install.""" - hip = hip_devices(eng / "strata-device.exe") - hint = (f"install or update the AMD driver (AMD Software: Adrenalin Edition) from {WIN_AMD_DRIVER}, restart the " - f"PC and run this again; {eng / 'strata-device.exe'} --list-devices shows what the HIP runtime sees") - if not hip: - fail("the AMD HIP runtime finds no GPU (the ready-made engine's device check)", hint) - m = hip_match(gpu, listed, hip) if gpu.get("driver") != "hip" else \ - next((x for x in hip if x["index"] == gpu["index"]), None) - if m is None: - fail(f"the HIP runtime does not list your {gpu['name']} ({gpu['arch']})", hint) - if amd_problem(m): - fail(f"HIP device {m['index']} ({m['name']}) cannot be used: {amd_problem(m)}") - if gpu.get("driver") != "hip" and m["index"] != gpu["index"]: - ok(f"HIP numbers this card {m['index']} (an integrated GPU comes first): the engine is pointed at it") - vram = gpu["vram_gb"] if gpu.get("uma") else (m["vram_gb"] or gpu["vram_gb"]) # an APU: not the runtime's figure - return {**gpu, "index": m["index"], "count": len(hip), "vram_gb": vram, "driver": "hip"} - - -def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: - """The ready-made Windows HIP engine (WIN_HIP_ASSET) in engine/, kept between runs; None when it cannot be had - (not published for this version, no internet) or has no code for the card.""" - eng = ROOT / "engine" - info = eng / "BUILD.json" - if info.exists() and (eng / EXE).exists(): - try: - meta = json.loads(info.read_text(encoding="utf-8")) - except ValueError: - meta = {} - ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) - if meta.get("backend") == "hip" and meta.get("source") == "prebuilt" and ver >= WIN_HIP_MIN_ENGINE and \ - gpu["arch"] in meta.get("archs", []) and not updating: - ok("ready-made AMD engine already installed") - return eng - if not url_base: - return None - eng.mkdir(exist_ok=True) - z = eng / WIN_HIP_ASSET - bases = prebuilt_bases(url_base) - for i, base in enumerate(bases): - if not base.startswith(("http://", "https://")): - break - try: - req = urllib.request.Request(base + WIN_HIP_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"}) - urllib.request.urlopen(req, timeout=60).close() - break - except OSError as e: - if i + 1 < len(bases): - say(f" No ready-made AMD engine for v{source_version()} ({e}): the latest release instead") - continue - warn(f"no ready-made AMD engine at {base} ({e})") - return None - say(" Downloading the ready-made PolyStrata engine for AMD GPUs (with the ROCm libraries it uses) ...") - download(base + WIN_HIP_ASSET, z, "PolyStrata AMD engine") - try: - verify_engine_archive(z, WIN_HIP_ASSET, base) - except UnverifiedEngine as e: - engine_refused(WIN_HIP_ASSET, e, updating) - return None - tmp = eng / "_unpack" - shutil.rmtree(tmp, ignore_errors=True) - with zipfile.ZipFile(z) as f: - f.extractall(tmp) - try: - meta = json.loads((tmp / "BUILD.json").read_text(encoding="utf-8")) - except (OSError, ValueError): - meta = {} - ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) - why = None - if meta.get("backend") != "hip" or not (tmp / EXE).exists(): - why = "it is not a HIP engine" - elif ver < WIN_HIP_MIN_ENGINE: - why = f"it is version {meta.get('version')}; this setup needs {'.'.join(map(str, WIN_HIP_MIN_ENGINE))}" - elif gpu["arch"] not in meta.get("archs", []): - why = (f"it is built for {', '.join(meta.get('archs', []))}; your GPU is {gpu['arch']}. A card it has no code " - "for runs from a self-build of the engine: see docs/AMD_HIP.md (--build)") # #881 - if is_strix_halo(gpu): # never a zip without gfx1151 code: say so, and what to do - why = (f"it is built for {', '.join(meta.get('archs', [])) or 'other GPUs'} and has no gfx1151 code: your " - f"{gpu['name']} (Strix Halo) needs a ready-made engine from PolyStrata 0.1.40 or newer, whose zip is " - "built for gfx1151 too. Until then: the Linux guide docs/STRIX_HALO.md, or compile the engine " - "here with tools\\hip\\build_windows.bat (its default list has gfx1151) and start setup with " - "--prebuilt ") - if why: - warn(f"the ready-made AMD engine at {base} cannot be used: {why}") - shutil.rmtree(tmp, ignore_errors=True) - drop_archive(z) - return None - install_unpacked(tmp, eng) - shutil.rmtree(tmp, ignore_errors=True) - drop_archive(z) - hip_runtime_beside_exe(eng) # #468 #461 - ok(f"ready-made AMD engine {meta.get('version', '')} for {', '.join(meta.get('archs', []))} " - f"(ROCm {meta.get('rocm', '?')})") - return eng - - -def rocm_version(root): - """(major, minor) of a ROCm install, from rocm-core's header; None when it has none.""" - try: - text = (Path(root) / "include" / "rocm-core" / "rocm_version.h").read_text(encoding="utf-8") - return tuple(int(re.search(rf"#define\s+ROCM_VERSION_{k}\s+(\d+)", text).group(1)) for k in ("MAJOR", "MINOR")) - except (OSError, AttributeError, ValueError): - return None - - -def rocm_dev_missing(sysroot: Path) -> list: - """#446: the HIP development files the engine's build needs that a system ROCm lacks (a runtime-only install has - hipcc and libhipblas but not these, and cmake's enable_language(HIP) then fails on the hip-lang package).""" - lang = "cmake/hip-lang/hip-lang-config.cmake" # where CMake's HIP support looks for it - need = {"lib/" + lang: [sysroot / d / lang for d in ("lib", "lib64", "lib/x86_64-unknown-linux-gnu")], - "include/hip/hip_runtime.h": [sysroot / "include" / "hip" / "hip_runtime.h"]} - return [name for name, paths in need.items() if not any(p.is_file() for p in paths)] - - -def rocm_root(archs): - """ROCm for compiling and running the HIP engine for `archs` (one arch or a list: the cards of a layer split): - (root, library folders). A system ROCm 7 with hipcc, hipBLAS and the HIP development files (#446), else AMD's - TheRock wheels (rocm_wanted: a version per card family, from the family's index) installed into .venv.""" - archs = [archs] if isinstance(archs, str) else list(archs) - sysroot = Path(os.environ.get("ROCM_PATH") or "/opt/rocm") - if (sysroot / "bin" / "hipcc").exists() and list((sysroot / "lib").glob("libhipblas.so*")): - ver = rocm_version(sysroot) - missing = rocm_dev_missing(sysroot) - if (ver is None or ver >= ROCM_SYSTEM_MIN) and not missing: - return sysroot, [str(sysroot / "lib")] - if ver is not None and ver < ROCM_SYSTEM_MIN: - warn(f"the ROCm in {sysroot} is {ver[0]}.{ver[1]}; PolyStrata needs {ROCM_SYSTEM_MIN[0]}.{ROCM_SYSTEM_MIN[1]} " - "or newer: using AMD's wheels in .venv instead") - else: # #446: a runtime-only ROCm (no -dev packages): cmake would fail - warn(f"the ROCm in {sysroot} has no HIP development files ({', '.join(missing)}): using AMD's wheels in " - ".venv instead (or install them, e.g. AMD's amdrocm-core-dev package for your ROCm and card)") - indexes = list(dict.fromkeys(rocm_index(a) for a in archs)) - if len(indexes) > 1: # TheRock's wheels hold one GPU family's libraries - fail(f"cards of two GPU families ({', '.join(archs)}) need a system ROCm 7 (in /opt/rocm): AMD's Python " - "wheels come per family", "install ROCm 7 system-wide, or use cards of one family (--gpu N for one card)") - index = indexes[0] - stamp = Path(sys.prefix) / ".strata-rocm.json" - have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {} - wheel = None - if have.get("index") == index and have.get("version") and not ROCM_VERSION_OVERRIDE \ - and (Path(sys.executable).parent / "rocm-sdk").exists() and have["version"] == ROCM_FAMILY_PINS.get(rocm_family(index), ROCM_VERSION_DEFAULT): - wheel = have["version"] # the family's pin is installed: no lookup - if wheel is None: - wheel, note = rocm_wanted(index) - if note: - warn(note) - if have.get("version") != wheel or have.get("index") != index: - say(f" Installing ROCm {wheel} for AMD GPUs into .venv (AMD's TheRock wheels, ~10 GB, no sudo) ...") - pip = [sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--index-url", index] - if have.get("version") == wheel: # the same version for another GPU family: its own libraries - run(pip + ["--force-reinstall", "--no-deps", f"rocm=={wheel}"]) - run(pip + [f"rocm[libraries,devel]=={wheel}"]) - stamp.write_text(json.dumps({"version": wheel, "index": index})) - sdk = Path(sys.executable).parent / "rocm-sdk" - root = Path(out([str(sdk), "path", "--root"]).strip()) - if not (root / "llvm" / "bin" / "clang++").exists(): - fail(f"ROCm was installed but its compiler is missing ({root})", - f"remove {stamp} and run this again; or install ROCm 7 system-wide") - # the card family's libraries only (gfx120X-all -> _rocm_sdk_libraries_gfx120X_all): another family's - # libhipblaslt.so first on the path would have no kernels for this card - family = "_rocm_sdk_libraries_" + index.rstrip("/").rsplit("/", 1)[-1].replace("-", "_") - dirs = [str(root / "lib")] - for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}: - libs = sorted(sp.glob("_rocm_sdk_libraries_*")) - libs = [d for d in libs if d.name.lower() == family.lower()] or libs - dirs += [str(d / "lib") for d in libs if (d / "lib").is_dir()] - ok(f"ROCm: {root}") - return root, list(dict.fromkeys(dirs)) - - -def hipblaslt_version(lib_dirs): - """The installed hipBLASLt's version as the engine reads it (hipblasLtGetVersion: 1.4.1 -> 100401), from the - header of the ROCm whose libraries the engine loads; None when not found.""" - for d in lib_dirs: - try: - text = (Path(d).parent / "include" / "hipblaslt" / "hipblaslt-version.h").read_text(encoding="utf-8") - v = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", text).group(1)) - for k in ("MAJOR", "MINOR", "PATCH")] - except (OSError, AttributeError, ValueError): - continue - return v[0] * 100000 + v[1] * 100 + v[2] - return None - - -def hipblaslt_table(arch, lib_dirs, ver=None): - """tools/hip/-hipblaslt-.txt for this card AND the installed hipBLASLt, else None: its solution - ids are valid only for that pair (the engine refuses any other table and uses plain hipBLAS). ver: the - hipBLASLt version the ready-made Windows engine ships (its BUILD.json), else read from the installed headers.""" - ver = ver or hipblaslt_version(lib_dirs) - table = ROOT / "tools" / "hip" / f"{arch}-hipblaslt-{ver}.txt" - if ver is not None and table.exists(): - head = table.read_text(encoding="utf-8").split("\n", 2)[:2] - if f"STRATA_HIPBLASLT_TUNING_V1 {arch} {ver}" in (h.strip() for h in head): - ok(f"hipBLASLt tuning table: {table.name} (faster prompts)") - return table - have = sorted(p.name for p in (ROOT / "tools" / "hip").glob(f"{arch}-hipblaslt-*.txt")) - warn(f"no hipBLASLt tuning table for {arch} with hipBLASLt {ver or '(version unknown)'}" - + (f" (have: {', '.join(have)})" if have else "") - + ": the prompt's dense matrix products use plain hipBLAS (tools/hip/tune_hipblaslt makes a table: " - "docs/AMD_HIP.md, Tuning table)") - return None - - -def build_engine_hip(gpu, llama, vision="none") -> Path: - """Compile the HIP engine for this AMD GPU into engine/ (again only when its source changed: a `git pull`). - gpu["archs"]: every architecture it needs code for (the cards of a layer split), else gpu["arch"]. vision "cpu" - (#304): the image encoder too, for the CPU (there is no HIP encoder build yet).""" - eng = ROOT / "engine" - eng.mkdir(exist_ok=True) - stamp = eng / "BUILD.json" - meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {} - src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) - archs = sorted(set(gpu.get("archs") or [gpu["arch"]])) - has_archs = set(archs) <= set(meta.get("archs", [])) - floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine - engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs and \ - (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE) - vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc) - if engine_ok and vision_ok: - ok("engine already built for this PC") - return eng - if engine_ok: - return build_vision_cpu(eng, stamp, meta, llama, vsrc) - if not (shutil.which("c++") or shutil.which("g++")) or not shutil.which("git"): - fail("a C++ compiler and git are needed to compile the AMD engine", - "Ubuntu/Debian: sudo apt install build-essential git Fedora: sudo dnf install gcc-c++ git") - root, dirs = rocm_root(archs) - libs = [str(Path(d).parent) for d in dirs[1:]] - bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()), - root / "amdgcn" / "bitcode") - os.environ.update({"HIP_PLATFORM": "amd", "HIP_COMPILER": "clang", "HIP_RUNTIME": "rocclr", "ROCM_PATH": str(root), - "HIP_PATH": str(root)}) - os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) - os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(root / "llvm" / "bin"), os.environ.get("PATH", "")]) - say(" The engine's source changed: compiling it again (only what changed, a few minutes) ..." - if meta.get("backend") == "hip" and (eng / EXE).exists() and has_archs - else f" Compiling the PolyStrata engine for your AMD GPU{'s' if len(archs) > 1 else ''} ({', '.join(archs)}; " - "10-20 minutes, once) ...") - cmake_build(ROOT, ROOT / "build-hip", "strata", - ["-DSTRATA_ENABLE_HIP=ON", "-DSTRATA_ENABLE_CUDA=OFF", "-DSTRATA_BUILD_TESTS=OFF", - "-DSTRATA_PREFILL_MMQ=ON", "-DSTRATA_Q6K_EXPERTS=ON", "-DSTRATA_MMQ_KQUANTS=ON", "-DCMAKE_HIP_ARCHITECTURES=" + ";".join(archs), - f"-DCMAKE_HIP_COMPILER={root / 'llvm' / 'bin' / 'clang++'}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", - "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), - f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}", - f"-DSTRATA_GGML_DIR={llama}", *isa_floor_defs(floor, ROOT / "build-hip", meta)], None, "") - if stale_binary(ROOT / "build-hip" / EXE): # #2054: no stamp for a binary of another version - fail(f"the engine build finished without a new engine ({EXE} is version " - f"{binary_engine_version(ROOT / 'build-hip' / EXE)}, this source is {source_version()}): " - "the installed engine is left as it was", "delete the folder build-hip and run this again") - shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE) - meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none", - "lib_dirs": dirs, "src": src, **({"isa_floor": floor} if floor else {})} - if vision != "none": - return build_vision_cpu(eng, stamp, meta, llama, vsrc) - stamp.write_text(json.dumps(meta, indent=1)) - ok(f"engine compiled: {eng / EXE}") - return eng - - -def hip_vision(asked) -> str: - """The image encoder with the AMD backend (--vision): the CPU one when asked for (#304); a HIP (GPU) encoder build - is a later step, so `yes`/`gpu` leave images off, as before, and say how to get them.""" - if asked in ("yes", "gpu"): - warn("the AMD backend has no GPU image encoder yet: images off" - + ("" if WIN else " (--vision cpu reads them on the CPU)")) - if asked == "cpu" and WIN: - warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no " - "image encoder): images off") - return "none" - return "cpu" if asked == "cpu" else "none" - - -def build_vision_cpu(eng: Path, stamp: Path, meta: dict, llama, vsrc) -> Path: - """#304: the CPU image encoder beside the HIP engine (tools/vision without CUDA), recorded in its BUILD.json.""" - if not ((eng / VEXE).exists() and meta.get("vision_src") == vsrc): - say(" Compiling the image encoder (for the CPU) ...") - cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision", "strata-vision", - [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=OFF", "-DSTRATA_PORTABLE=OFF"], - find_vcvars() if WIN else None, - "build-vision-cpu.bat" if WIN else "") # #881: MSVC's environment on Windows, as the CUDA path has - shutil.copy2(ROOT / "build-vision" / "bin" / VEXE, eng / VEXE) - stamp.write_text(json.dumps({**meta, "vision": "cpu", "vision_src": vsrc}, indent=1)) - ok(f"engine: {eng / EXE}, image encoder (CPU): {eng / VEXE}") - return eng - - -# ------------------------------------------------------------------------------------------------ image generation -IMAGE_ENGINE = ROOT / "engine-image" # sd-cli for Qwen-Image-2.1-Turbo (tools/image/qimage.py), --images - - -def _qimage(): - if str(ROOT / "tools" / "image") not in sys.path: - sys.path.insert(0, str(ROOT / "tools" / "image")) - import qimage - return qimage - - -def get_sd_cpp() -> Path: - """stable-diffusion.cpp and its ggml at the pinned commits (tools/image/qimage.py), as zips: no git.""" - QI = _qimage() - src = ROOT / "third_party" / "stable-diffusion.cpp" - if QI.source_ok(src): - return src - z1 = ROOT / "third_party" / f"stable-diffusion.cpp-{QI.SD_CPP_COMMIT[:7]}.zip" - z2 = ROOT / "third_party" / f"sd-ggml-{QI.SD_GGML_COMMIT[:7]}.zip" - download(QI.SD_CPP_ZIP, z1, "stable-diffusion.cpp source") - download(QI.SD_GGML_ZIP, z2, "stable-diffusion.cpp's ggml source") - try: - src = QI.unpack_source(ROOT / "third_party", z1, z2) - except zipfile.BadZipFile: - for z in (z1, z2): - drop_archive(z) - raise - for z in (z1, z2): - z.unlink(missing_ok=True) - z.with_name(z.name + ".done").unlink(missing_ok=True) - return src - - -def vulkan_sdk() -> Path | None: - """What a Vulkan build of sd-cli needs (the Vulkan headers and glslc): $VULKAN_SDK, the distribution's packages, - else (Linux) the LunarG SDK unpacked into third_party (no sudo, ~370 MB). Returns the SDK folder it put on PATH, - None when the system's files are used.""" - QI = _qimage() - have = os.environ.get("VULKAN_SDK") - if have and Path(have).is_dir(): - return None - if not WIN and shutil.which("glslc") and Path("/usr/include/vulkan/vulkan.h").exists(): - return None - if WIN: - fail("compiling the image generator for this GPU (Vulkan) needs the Vulkan SDK", - "install it from https://vulkan.lunarg.com/sdk/home#windows, open a new window and run setup again " - "(or --image-backend cpu)") - base = ROOT / "third_party" / "vulkan-sdk" - sdk = base / QI.VULKAN_SDK_VERSION / "x86_64" - if not (sdk / "bin" / "glslc").exists(): - import tarfile - tar = ROOT / "third_party" / f"vulkansdk-{QI.VULKAN_SDK_VERSION}.tar.xz" - download(QI.VULKAN_SDK_URL, tar, f"the Vulkan SDK {QI.VULKAN_SDK_VERSION} (LunarG, for compiling only)") - verify_sha256(tar, QI.VULKAN_SDK_SIZE, QI.VULKAN_SDK_SHA256) - shutil.rmtree(base, ignore_errors=True) - base.mkdir(parents=True) - with tarfile.open(tar) as t: - t.extractall(base, **({"filter": "data"} if hasattr(tarfile, "data_filter") else {})) - tar.unlink(missing_ok=True) - tar.with_name(tar.name + ".done").unlink(missing_ok=True) - os.environ["VULKAN_SDK"] = str(sdk) - os.environ["PATH"] = os.pathsep.join([str(sdk / "bin"), os.environ.get("PATH", "")]) - os.environ["LD_LIBRARY_PATH"] = os.pathsep.join([str(sdk / "lib" / "VulkanLoader" / "lib"), - os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) - ok(f"Vulkan SDK: {sdk}") - return sdk - - -def apply_native_runner(src: Path) -> None: - """I2: tools/image/sdcpp_native's runner into the stable-diffusion.cpp source (idempotent).""" - import importlib.util - QI = _qimage() - spec = importlib.util.spec_from_file_location("strata_sdcpp_native_apply", QI.NATIVE_DIR / "apply.py") - mod = importlib.util.module_from_spec(spec) - spec.loader.exec_module(mod) - mod.apply(src) - - -def build_image_engine(backend: str, gpu: dict) -> tuple[Path, list[str]]: - """Compile sd-cli for `backend` into engine-image/ (again only when the pins or the backend changed) -> (its path, - the library folders it runs with).""" - QI = _qimage() - IMAGE_ENGINE.mkdir(exist_ok=True) - exe, stamp = IMAGE_ENGINE / QI.SD_EXE, IMAGE_ENGINE / "BUILD.json" - arch = gpu.get("arch") if backend in ("cuda", "hip") else None - want = QI.build_stamp(backend, arch) - meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {} - lib_dirs = [d for d in meta.get("lib_dirs") or [] if Path(d).is_dir()] - if exe.exists() and {k: meta.get(k) for k in want} == want: - ok(f"image generator already built ({backend})") - return exe, lib_dirs - src = get_sd_cpp() - if backend in QI.NATIVE_BACKENDS: # PolyStrata's DiT runner (inert unless the config asks for it) - apply_native_runner(src) - vcvars, lib_dirs = None, [] - if backend == "cuda": - nvcc, cuda_v = find_nvcc() - if nvcc is None: - fail("compiling the image generator for NVIDIA needs the CUDA Toolkit (nvcc)", - "install it from https://developer.nvidia.com/cuda-downloads and run setup again " - "(or --image-backend vulkan / cpu)") - root = Path(nvcc).resolve().parent.parent - defs = QI.cmake_defs("cuda", arch=arch, cuda_root=root) + [f"-DCMAKE_CUDA_COMPILER={nvcc}"] + \ - host_compiler_defs(True) - vcvars = find_vcvars(cuda_v) if WIN else None - lib_dirs = [str(root / "bin")] if WIN else [str(d) for d in (root / "lib64", root / "lib") if d.is_dir()] - elif backend == "hip": - root, dirs = rocm_root([arch]) - os.environ.update({"HIP_PLATFORM": "amd", "ROCM_PATH": str(root), "HIP_PATH": str(root)}) - os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) - defs = QI.cmake_defs("hip", arch=arch, rocm=root) - lib_dirs = list(dirs) - elif backend == "vulkan": - sdk = vulkan_sdk() - defs = QI.cmake_defs("vulkan") - vcvars = find_vcvars() if WIN else None - if sdk is not None: # the SDK's loader (lib/VulkanLoader): CMake does not look there - loader = sdk / "lib" / "VulkanLoader" / "lib" - defs += [f"-DVulkan_LIBRARY={loader / 'libvulkan.so'}", f"-DVulkan_INCLUDE_DIR={sdk / 'include'}", - f"-DVulkan_GLSLC_EXECUTABLE={sdk / 'bin' / 'glslc'}"] - import ctypes.util - if not ctypes.util.find_library("vulkan"): - lib_dirs = [str(loader)] # no system Vulkan loader to run with: the SDK's - else: - defs = QI.cmake_defs("cpu") - vcvars = find_vcvars() if WIN else None - say(f" Compiling the image generator (stable-diffusion.cpp {QI.SD_CPP_COMMIT[:7]}, {backend}; 5-20 minutes, " - "once) ...") - bdir = ROOT / f"build-image-{backend}" - cmake_build(src, bdir, "sd-cli", defs, vcvars, f"build-image-{backend}.bat" if WIN else "") - built = bdir / "bin" / QI.SD_EXE - if not built.exists(): - fail(f"the image generator's build finished without {built}", f"delete the folder {bdir.name} and run again") - shutil.copy2(built, exe) - stamp.write_text(json.dumps({**want, "lib_dirs": lib_dirs}, indent=1)) - ok(f"image generator compiled: {exe}") - return exe, lib_dirs - - -def image_backend_choice(a, gpu: dict | None, hip: bool) -> tuple[str, str, float]: - """--images: (backend, quant, the GPU memory in GB the quant was picked for). An explicit --image-quant above the - recommendation is kept, with a warning (recommend, never force).""" - QI = _qimage() - vendor = "amd" if hip else ((gpu or {}).get("vendor") or "nvidia") - backend = a.image_backend or QI.pick_backend({**gpu, "vendor": vendor} if gpu else None, WIN) - gb = float((gpu or {}).get("vram_gb") or 0.0) if backend != "cpu" else 0.0 - rec = QI.pick_quant(gb) if backend != "cpu" else "Q4_K_M" - quant = a.image_quant or rec - if QI.QUANTS.index(quant) > QI.QUANTS.index(rec): - warn(f"image model {quant}: setup recommends {rec} for {gb:.0f} GB of GPU memory; kept as you chose " - "(stable-diffusion.cpp then keeps part of it in RAM, which is slower)") - return backend, quant, gb - - -def setup_images(a, gpu: dict, hip: bool, models_dir: Path) -> dict | None: - """--images qwen-image: sd-cli for this GPU and Qwen-Image-2.1-Turbo's three files -> the run config's "images" - section (serve/images.py); None for --images no, or when not wanted after all.""" - if not a.images or a.images == "no": - return None - QI = _qimage() - backend, quant, _ = image_backend_choice(a, gpu, hip) - say(f" Image generation: Qwen-Image-2.1-Turbo {quant} on {backend} (8 steps, CFG 1; POST /v1/images/generations)") - say(" " + QI.LICENSE_NOTE) - need = sum(QI.FILES[k][2] for k in (quant, "vae", "llm")) / 1e9 - if ask(f"Download the image model ({need:.1f} GB) and set up image generation?", ["y", "n"], "y", a.yes) != "y": - return None - models_dir.mkdir(parents=True, exist_ok=True) - if free_gb(models_dir) < need + 5: - warn(f"less than {need + 5:.0f} GB free for the image model: the download may run out of disk space") - exe, lib_dirs = build_image_engine(backend, gpu or {}) - for name in (quant, "vae", "llm"): - repo, path, size, sha = QI.FILES[name] - dst = QI.local_path(models_dir, name) - download(QI.file_url(name, hf_endpoint()), dst, f"image model: {Path(path).name}") - verify_sha256(dst, size, sha) - cfg = QI.image_config(backend, quant, exe, models_dir, uma=QI.is_apu(gpu), lib_dirs=lib_dirs, - policy=a.image_gpu_policy or "auto", native=getattr(a, "image_native", None) == "on") - ok(f"image generation: {quant} on {backend}, GPU policy {cfg['gpu_policy']}") - return cfg - - -# ------------------------------------------------------------------------------------------------ the engine -def driver_major(gpu): - try: - return int(gpu["driver"].split(".")[0]) - except (ValueError, KeyError): - return 0 - - -class UnverifiedEngine(Exception): - """The engine archive could not be verified, with the reason. - - Raised rather than `fail()`-ed on purpose. The engine-UPDATE paths wrap their download in - `except Exception` and fall back to the engine already installed, so a refusal has to be an Exception: - `fail()` ends in `sys.exit(1)`, and SystemExit is a BaseException, so it flies past that guard and - kills the start instead. Measured on this change before the fix - a wrong hash, a wrong size and a - missing digest each escaped get_prebuilt(updating=True) as SystemExit(1). - """ - - -def release_of(base: str) -> tuple[str, str | None] | None: - """("github", tag) for a GitHub release URL, or None when the URL is not one. - - `base` is one of the bases from `prebuilt_bases`: a `releases/download/v0.1.40/` URL (which names its - tag), the `releases/latest/download/` URL, or something else entirely - a local folder, a plain mirror. - That last case matters: it has no published digest, so treating it as "latest" would check the file - against a release the user did not ask for, over the network, which is wrong twice over. - - The repository comes out of the URL when it names one, so a fork's own releases are checked against - the fork rather than against Niko1221/Strata (which never has the fork's tags, so the check would - always fail). - """ - m = re.search(r"https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/releases/(?:download/v([^/]+)|latest)/", - base) - if not m: - return None - return f"https://api.github.com/repos/{m.group(1)}/{m.group(2)}/releases", m.group(3) - - -def is_local(base: str) -> bool: - """True for a path on this machine - `C:/mirror`, `/mnt/mirror`, `//share/engine`, `file://...`. - - A local folder is the user's own file on their own disk, the same trust decision as `--gguf-dir`, and - there is no published digest for it to be checked against. It is treated differently from a remote - mirror on purpose: nothing is between the file and setup, whereas a remote mirror has a network in the - middle and still no release to check it against. - """ - b = base.strip() - if b.lower().startswith("file://"): - return True - return not re.match(r"^[a-z][a-z0-9+.\-]*://", b, re.I) - - -def engine_digest(asset: str, base: str) -> tuple[int, str] | None: - """(size, "sha256:") for `asset` in the release `base` points at, or None if GitHub will not say. - - The size and hash come from the releases API - a different origin from the download, which is the - whole point: a mirrored, substituted or TLS-intercepted download does not come with a matching digest, - while a compromised release does (see `verify_engine_archive` for what that leaves uncovered). - - GitHub populates `digest` for every asset, including ones uploaded before the field existed - (measured on v0.1.34 through v0.1.40.1). None means no answer - no network, a rate limit, or a - release that does not publish one - and the caller warns and installs anyway (never refuses). - """ - where = release_of(base) - if where is None: # a local folder or a plain mirror: nothing published to check against - return None - releases, tag = where - url = f"{releases}/tags/v{tag}" if tag else f"{releases}/latest" - try: - req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", - "Accept": "application/vnd.github+json"}) - with urllib.request.urlopen(req, timeout=60) as r: - rel = json.loads(r.read().decode("utf-8")) - except Exception: - return None # offline, rate-limited, or the release is not there - for a in rel.get("assets") or []: - if a.get("name") == asset and a.get("digest") and str(a.get("digest")).startswith("sha256:"): - return int(a.get("size") or 0), str(a["digest"]).split(":", 1)[1] - return None - - -def drop_download(z: Path) -> None: - """The archive and its finish mark. A refused engine is not left where a later run would reuse it.""" - z.unlink(missing_ok=True) - z.with_name(z.name + ".done").unlink(missing_ok=True) - - -def verify_engine_archive(z: Path, asset: str, base: str) -> None: - """The downloaded engine archive against the published size and SHA-256, before it is unpacked. - - Without this, a ready-made engine is installed on nothing more than the byte count matching the - server's Content-Length - and a substituted file of the same length passes that. It runs before the - archive is opened, so a wrong engine never reaches `_unpack`, let alone the engine directory. - - Raises UnverifiedEngine on a refusal; the caller decides whether that stops setup (a first install, - with nothing to fall back to) or keeps the engine that is already there (an update). - - Where the hash comes from, and where it cannot: - - - a GitHub release URL: the tag is read out of the URL, so the exact release the bytes claim to come - from is the one checked rather than "latest" (setup tries the checkout's own release first, #214), - and the repository comes out of the URL too, so a fork's releases are checked against the fork; - - a local folder (`--prebuilt D:/mirror`): nothing published to check against. This warns and goes - ahead - it is the user's own file, the same trust decision as `--gguf-dir`, and there is nothing an - API could say about it; - - any other remote mirror: nothing published to check against either, but a network is in the middle, - so it warns and installs anyway (no digest is never a reason to refuse). - - What a digest from the API does NOT cover, stated plainly: it proves the bytes are the ones GitHub - published for that asset, so it catches a corrupted transfer, a mirror or proxy that substituted the - file, and a hostile network. It does not make a malicious RELEASE safe - if whoever can publish a - release publishes a hostile engine, the digest matches it. Only a hash pinned in this file closes - that, at the cost of a commit per release; a dict of tag -> sha next to `engine_digest` is where one - would go. - - The size and the hashing below are spelled out rather than delegated to `verify_sha256`, for two - reasons, both measured here. That function ends in `fail()`, and a refusal has to be an Exception so - the update paths can fall back. And it keeps a `.done` mark so 111 GB of Unsloth shards is hashed - once; the engine archive is 190 MB, which hashes in 0.79 s at 242 MB/s on this machine, against 3.0 s - to download the same file. A mark that saves 0.8 s is not worth a class of hole - anything that - changes the file after it was verified, at any length - so there is no mark here. - """ - if os.environ.get("STRATA_SKIP_SHA256") == "1": - warn(f"STRATA_SKIP_SHA256=1: NOT checking {asset} against its SHA-256. If the file is corrupt or " - f"tampered with, it will be installed anyway. Unset it to get the check back.") - return - want = engine_digest(asset, base) # one API call: this is a rate-limited API - if not want: - # no published digest (offline, rate limit, a mirror or folder): install anyway, never refuse - warn(f"could not get a SHA-256 for {asset} from GitHub (offline, rate limited, or not a release " - f"URL), so it was NOT verified. Installing it as it is.") - return - size, sha = want - have = z.stat().st_size if z.exists() else -1 - if have != size: - drop_download(z) - raise UnverifiedEngine(f"{z.name} is {have:,} bytes, not the published {size:,}") - h = hashlib.sha256() - with open(z, "rb") as f: - while True: - b = f.read(16 << 20) - if not b: - break - h.update(b) - if h.hexdigest() != sha: - got = h.hexdigest() - drop_download(z) - raise UnverifiedEngine(f"{z.name} has the wrong SHA-256 ({got}, expected {sha})") - ok(f"{z.name}: SHA-256 checksum verified against GitHub's ({sha[:12]}...)") - - -def engine_refused(asset: str, e: Exception, updating: bool) -> None: - """Report a refusal and either stop setup or keep the engine that is installed. - - A first install has nothing to fall back to, so it stops. An update does: the engine already in - place is untouched by a refusal (nothing has been unpacked), it works, and stopping the model from - starting over a hash is worse than keeping what is there - which is the whole reason that call site - catches what the download can throw. - """ - if not updating: - fail(f"the downloaded PolyStrata engine does not match GitHub's checksum: {e}", - "the bad download has been deleted (corrupt or tampered), so the next run fetches the " - "published file again. Set STRATA_SKIP_SHA256=1 only if you insist on installing it anyway") - return - warn(f"keeping the engine that is installed: {e}") - say(" Nothing was replaced. The bad download was deleted; run setup again to fetch it afresh.") - - -def prebuilt_bases(url_base) -> list[str]: - """Where to look for the ready-made engine, in order (each ending in a slash). The default: the release of this - checkout's version first, then the latest (#214); an explicit --prebuilt / STRATA_PREBUILT_URL: only that.""" - base = url_base if url_base.endswith(("/", "\\")) else url_base + "/" - if base != PREBUILT_URL: - return [base] - return [PREBUILT_TAG_URL.format(version=source_version()), base] - - -PREVIOUS_ENGINE = ".previous" - - -def engine_version_of(folder: Path) -> str: - try: - return str(json.loads((folder / "BUILD.json").read_text(encoding="utf-8")).get("version", "?")) - except (OSError, ValueError): - return "?" - - -def install_unpacked(tmp: Path, eng: Path) -> None: - """#670: the unpacked engine (tmp) replaces the installed one in `eng`, which is kept, one generation, in - eng/.previous (about 210 MiB): a new engine that turns out bad has a way back (`setup.py --rollback-engine`). The - swap is all or nothing: a failure part-way puts the old files back instead of leaving a mix of old and new.""" - prev = eng / PREVIOUS_ENGINE - new = list(tmp.iterdir()) - old = [eng / p.name for p in new if p.name != PREVIOUS_ENGINE and (eng / p.name).exists()] - if (eng / KQ_LIB).exists() and all(p.name != KQ_LIB for p in new): # a zip without strata_kq: an older one of - old.append(eng / KQ_LIB) # another build would only be refused (kept in .previous too) - shutil.rmtree(prev, ignore_errors=True) - moved, placed = [], [] - try: - if old: - prev.mkdir() - for dst in old: - shutil.move(str(dst), str(prev / dst.name)) - moved.append(dst) - for p in new: - p.replace(eng / p.name) - placed.append(eng / p.name) - except OSError: - for dst in placed: # back to the old engine, whole - shutil.rmtree(dst) if dst.is_dir() else dst.unlink(missing_ok=True) - for dst in moved: - shutil.move(str(prev / dst.name), str(dst)) - shutil.rmtree(prev, ignore_errors=True) - raise - # #1403 debt: get_prebuilt moved the old BUILD.json aside (BUILD.json.prev) instead of deleting it; it goes with the - # engine it describes, so engine_version_of(.previous) says the version instead of "?" - kept = eng / "BUILD.json.prev" - if kept.exists(): - try: - if moved and not (prev / "BUILD.json").exists(): - shutil.move(str(kept), str(prev / "BUILD.json")) - else: - kept.unlink() - except OSError: - pass - if moved: - ok(f"the engine it replaced ({engine_version_of(prev)}) is kept in {prev}; " - "setup.py --rollback-engine puts it back") - - -def rollback_engine(toolkit=13) -> int: - """#670: `setup.py --rollback-engine`: the engine kept in engine/.previous becomes the installed one again, and the - one it replaces is kept in its place (run it again to go forward).""" - eng = engine_dir(toolkit) - prev = eng / PREVIOUS_ENGINE - if not prev.is_dir() or not any(prev.iterdir()): - warn(f"no earlier engine is kept in {prev} (one is kept when an update replaces the engine)") - return 1 - swap = eng / ".swap" - shutil.rmtree(swap, ignore_errors=True) - swap.mkdir() - was = engine_version_of(eng) - for p in list(prev.iterdir()): # what the earlier engine has: the current copy goes aside - cur = eng / p.name - if cur.exists(): - shutil.move(str(cur), str(swap / p.name)) - shutil.move(str(p), str(cur)) - for p in list(swap.iterdir()): - shutil.move(str(p), str(prev / p.name)) - shutil.rmtree(swap, ignore_errors=True) - ok(f"engine {engine_version_of(eng)} is installed again (it replaced {was}, which is kept in {prev})") - return 0 - - -def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | None: - """The ready-made engine in engine/ (kept between runs), or None when there is none for this PC. - updating: called to replace an installed engine, which starts instead when this fails (no compile). - toolkit 12: the experimental CUDA 12 engine (CUDA12_ASSET) in engine-cuda12/.""" - eng = engine_dir(toolkit) - asset = CUDA12_ASSET if int(toolkit) == 12 else PREBUILT_ASSET - info = eng / "BUILD.json" - if info.exists() and (eng / EXE).exists() and json.loads(info.read_text(encoding="utf-8")).get("backend") != "hip": - meta = json.loads(info.read_text(encoding="utf-8")) - ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) - if meta.get("source") == "local": # compiled here: build_engine checks its source and cards - return None - have = [int(a) for a in meta.get("archs", [])] - miss = [int(x) for x in gpu.get("archs", [gpu["arch"]]) - if have and int(x) not in have and not (meta.get("ptx") and int(x) > max(have))] - if miss: # a card it has no code for (#128): compiled here instead - warn(f"the installed engine is built for {', '.join(str(a) for a in have)}; your GPU is " - f"{', '.join(str(x) for x in miss)}: compiling instead") - return None - if ver >= MIN_ENGINE: - ok("ready-made engine already installed") - return eng - say(f" Updating the ready-made engine ({meta.get('version')} -> {'.'.join(map(str, MIN_ENGINE))} or newer) ...") - info.replace(eng / "BUILD.json.prev") # kept for the .previous copy - if not url_base: - return None - eng.mkdir(exist_ok=True) - z = eng / asset - bases = prebuilt_bases(url_base) - for i, base in enumerate(bases): - if not base.startswith(("http://", "https://")): - break - try: # not published (yet), or no internet: compile instead - req = urllib.request.Request(base + asset, method="HEAD", headers={"User-Agent": "strata-setup"}) - urllib.request.urlopen(req, timeout=60).close() - break - except OSError as e: - if i + 1 < len(bases): # #214: this checkout's release is not published (yet) - say(f" No ready-made engine for v{source_version()} ({e}): the latest release instead") - continue - warn(f"no ready-made engine at {base} ({e})" + ("" if updating else ": compiling instead")) - return None - say(" Downloading the ready-made PolyStrata engine" + (" (CUDA 12, experimental)" if int(toolkit) == 12 else "") + " ...") - download(base + asset, z, "PolyStrata engine") - try: - verify_engine_archive(z, asset, base) - except UnverifiedEngine as e: - engine_refused(asset, e, updating) - return None - tmp = eng / "_unpack" - shutil.rmtree(tmp, ignore_errors=True) - try: - with zipfile.ZipFile(z) as f: - f.extractall(tmp) - except zipfile.BadZipFile: # not a zip, or a damaged one: a kept .done mark would make - drop_archive(z) # every later run fail on it instead of downloading it again - raise - meta = json.loads((tmp / "BUILD.json").read_text(encoding="utf-8")) - if tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) < MIN_ENGINE: - need = ".".join(map(str, MIN_ENGINE)) - if updating: # these files are newer than the published release (#58) - warn(f"engine {need} is not published yet (the release may still be uploading): run this again " - f"in a few minutes to update it") - else: - warn(f"the ready-made engine at {base} is version {meta.get('version')}; this setup needs " - f"{need}: compiling instead") - shutil.rmtree(tmp, ignore_errors=True) - drop_archive(z) - return None - archs = [int(a) for a in meta.get("archs", [])] - miss = [int(x) for x in gpu.get("archs", [gpu["arch"]]) - if int(x) not in archs and not (meta.get("ptx") and int(x) > max(archs))] - if miss: - warn(f"the ready-made engine is built for {', '.join(str(a) for a in archs)}; your GPU is " - f"{', '.join(str(x) for x in miss)}" + ("" if updating else ": compiling instead")) - shutil.rmtree(tmp, ignore_errors=True) - drop_archive(z) - return None - install_unpacked(tmp, eng) - shutil.rmtree(tmp, ignore_errors=True) - drop_archive(z) - if not (eng / EXE).exists(): - fail("the ready-made engine archive has no " + EXE) - if not WIN: - for x in (EXE, VEXE): - if (eng / x).exists(): - (eng / x).chmod(0o755) - ok(f"ready-made engine {meta.get('version', '')} for {', '.join('sm_' + str(a) for a in archs)} (CUDA " - f"{meta.get('cuda', '?')})") - return eng - - -def update_engine_gpu(toolkit=13): - """#1485: the card an engine update is for. Not simply the one with the most VRAM: a Tesla V100 (32 GB) beside two - RTX 4090s was taken, and CUDA 13 cannot compile for it. The cards the installed models are set up for come - first (their "gpu"); for the CUDA 13 engine a card it cannot compile for is left out when another can. An - explicit --gpu (GPU_PICK) still wins. None when there is no NVIDIA GPU.""" - if GPU_PICK is not None: - return gpu_info() - found = gpus() - if not found: - return None - named = set() - for c in installed_configs(): - try: - g = json.loads(c.read_text(encoding="utf-8-sig")).get("gpu") - except (OSError, ValueError): - continue - named.update(i for i in (g if isinstance(g, list) else [g]) if isinstance(i, int) and not isinstance(i, bool)) - pool = [g for g in found if g["index"] in named] or found - if int(toolkit) != 12: - pool = [g for g in pool if int(g["arch"]) >= CUDA13_MIN_ARCH] or pool - g = max(pool, key=lambda x: (round(x["vram_gb"]), -x["index"])) - return {**g, "count": len(found)} - - -def update_installed_engine(url_base, toolkit=None) -> None: - """An installed ready-made engine older than MIN_ENGINE is replaced before the model starts, so a plain - START-HERE.bat on an existing install picks up a new release. If that cannot happen (no internet, the model - still running, no ready-made engine for this GPU) the installed engine is kept and starts as before. - toolkit None: engine/, then the experimental CUDA 12 engine in engine-cuda12/ when one is installed.""" - if toolkit is None: - update_installed_engine(url_base, 13) - if (engine_dir(12) / "BUILD.json").exists(): - update_installed_engine(url_base, 12) - return - eng = engine_dir(toolkit) - info = eng / "BUILD.json" - if not info.exists() or not (eng / EXE).exists(): - return - meta_text = info.read_text(encoding="utf-8") - meta = json.loads(meta_text) - if meta.get("backend") == "hip" and WIN: # AMD on Windows: the ready-made HIP engine, when older - ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) - if meta.get("source") == "prebuilt" and ver < WIN_HIP_MIN_ENGINE: - try: - g = next((x for x in amd_gpus() if amd_problem(x) is None), None) - if g is None: - raise RuntimeError("no supported AMD GPU found") - say(f" Updating the ready-made AMD engine ({meta.get('version')} -> " - f"{'.'.join(map(str, WIN_HIP_MIN_ENGINE))} or newer) ...") - if get_prebuilt_hip(url_base, g, updating=True) is None: - raise RuntimeError("not published yet") - except (Exception, SystemExit) as e: - warn(f"could not update the AMD engine{'' if isinstance(e, SystemExit) else f' ({e})'}: " - "starting the installed one") - return - if meta.get("backend") == "hip": # AMD: compiled here, again when its source changed - if meta.get("src") != source_hash(ENGINE_SOURCES) or stale_binary(eng / EXE): - try: - usable = [x for x in amd_gpus() if amd_problem(x) is None] - g = next((x for x in usable if x["arch"] in meta.get("archs", [])), usable[0] if usable else None) - if g is None: - raise RuntimeError("no supported AMD GPU found") - # every architecture it was built for (a layer split across two families keeps both) - build_engine_hip({**g, "archs": [x for x in meta.get("archs", []) if x in AMD_ARCHS] or [g["arch"]]}, - get_llama_cpp(vision=True), meta.get("vision") or "none") - except (Exception, SystemExit) as e: - warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: " - "starting the installed one") - return - ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) - local = meta.get("source") == "local" - vision = meta.get("vision") or "none" - if local: # compiled here: is it older than the source (a git pull)? - if meta.get("src") == source_hash(ENGINE_SOURCES) and not stale_binary(eng / EXE) and \ - (vision == "none" or meta.get("vision_src") == source_hash(VISION_SOURCES)): - return - elif ver >= MIN_ENGINE: - return - try: # a running engine cannot be replaced (Windows keeps it locked) - for x in (EXE, VEXE): - if (eng / x).exists(): - with open(eng / x, "r+b"): - pass - except OSError: - warn(f"engine {meta.get('version') or ''} is in use: close the model window and run this again to update it") - return - gpu = update_engine_gpu(toolkit) - if local: - try: # a failed compile must not stop the model from starting - if gpu is None: - raise RuntimeError("no NVIDIA GPU found") - gpu = {**gpu, "archs": sorted({int(gpu["arch"]), *(int(x) for x in meta.get("archs", []))})} - if int(toolkit) == 12: # the cards it was compiled for (the main GPU may be newer) - gpu["archs"] = sorted({int(x) for x in meta.get("archs", [])}) or gpu["archs"] - build_engine(gpu, vision, False, get_llama_cpp(), toolkit=toolkit) - except (Exception, SystemExit) as e: - warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the installed one") - return - new = None - if gpu is not None: - try: - if int(toolkit) == 12: # the cards the CUDA 12 engine serves, not the newest one - gpu = {**gpu, "archs": [x for x in (int(a) for a in meta.get("archs", [])) if x < CUDA13_MIN_ARCH] - or [int(gpu["arch"])]} - new = get_prebuilt(url_base, gpu, "gpu", updating=True, toolkit=toolkit) - except Exception as e: # a failed download must not stop the model from starting - warn(f"updating the engine failed ({e})") - if new is None: - if not info.exists(): - info.write_text(meta_text) # get_prebuilt drops it before downloading: put it back - warn(f"could not update the engine: starting the installed {meta.get('version')}") - return - pip_cuda_libs(toolkit) - - -def pip_cuda_libs(toolkit=13) -> None: - """NVIDIA's cuBLAS and CUDA runtime for a ready-made engine, from pip: CUDA 13's, or the CUDA 12 engine's.""" - if int(toolkit) == 12: - pip_install(CUDA12_WHEELS, "NVIDIA CUDA 12 libraries for the experimental engine (cuBLAS, CUDA runtime; ~0.7 GB)") - else: - pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)") - - -CUDA_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 - # (K-quant MMQ) that the same source compiled with 13.0.88 answers correctly (llama.cpp hit it too) -CUDA_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) - - -def nvcc_build(nvcc): - """The build number of an nvcc ("Build cuda_13.2.r13.2/compiler...", "V13.2.86" -> 86); None when it cannot be read.""" - m = re.search(r"\bV\d+\.\d+\.(\d+)", out([nvcc, "--version"]) if nvcc else "") - return int(m.group(1)) if m else None - - -def sm120_nvcc(nvcc, cuda_v, archs): - """#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 - when one is installed and the user did not name a compiler (STRATA_NVCC), else the one found, with a warning that says - what to do. CUDA 13.2.2 (build 86 or newer) is fine. Recommends, never forces: a user who picked 13.2 keeps it.""" - if not nvcc or cuda_v != CUDA_SM120_SUSPECT or max(archs) < 120: - return nvcc, cuda_v - build = nvcc_build(nvcc) - if build is not None and build >= CUDA_SM120_FIXED_BUILD: - return nvcc, cuda_v - if not os.environ.get("STRATA_NVCC"): - alt, alt_v = find_nvcc(below=CUDA_SM120_SUSPECT) - if alt and alt_v and alt_v >= (13, 0): - 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 " - "answers there (#892, #968); STRATA_NVCC= picks another") - return alt, alt_v - 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 " - "reports (#892, #968): the same source compiled with CUDA 13.0, 13.1 or 13.2.2 is right. If the engine answers " - "with nonsense, update to CUDA 13.2.2 or install CUDA 13.0 next to it (https://developer.nvidia.com/cuda-toolkit-archive) " - "and set STRATA_NVCC to its nvcc; the ready-made engine is built with 13.0") - return nvcc, cuda_v - - -def cuda_apt_repo(osr): - """The NVIDIA apt repo for this distribution ("ubuntu2404", "debian13") from /etc/os-release, or None when it is - not one setup adds the CUDA keyring for. Both families publish cuda-keyring and CUDA 13.x.""" - ver = osr.get("VERSION_ID", "").strip('"').replace(".", "") - repo = {"ubuntu": "ubuntu", "debian": "debian"}.get(osr.get("ID", ""), "") + ver - return repo if repo in ("ubuntu2204", "ubuntu2404", "debian12", "debian13") else None - - -def install_build_tools(gpu, yes): - """The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars).""" - archs = [int(x) for x in gpu.get("archs", [gpu["arch"]])] - # #295: Pascal / Volta need a CUDA 12.x toolkit - CUDA 13 cannot build sm_60/sm_70; gpu["toolkit"] = 12: the - # experimental CUDA 12 engine for any cards (--cuda 12, docs/OLDER_GPUS.md) - old = int(gpu.get("toolkit") or (12 if min(archs) < CUDA13_MIN_ARCH else 13)) == 12 - need12 = (12, 8) if max(archs) >= 120 else (12, 0) # sm_120 needs CUDA 12.8 or newer - if old and max(archs) >= 120 and "need_cuda" not in gpu: # #220 is the Qwen engine's prompt path - warn("an RTX 50 card (sm_120) in a CUDA 12 engine: engines built with CUDA 12.8 crashed on long prompts there " - "(#220, #224); the RTX 50 card alone (--gpu N) runs the ready-made CUDA 13 engine") - nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc() - if old and (nvcc is None or cuda_v < need12): - fail("the experimental CUDA 12 engine (Pascal / Volta, or --cuda 12) is compiled here with the NVIDIA CUDA " - f"Toolkit {need12[0]}.{need12[1]} or a newer 12.x (CUDA 13 cannot compile for these cards)" + - (f"; found CUDA {cuda_v[0]}.{cuda_v[1]}" if nvcc else ""), - "install CUDA 12.9 (it can sit next to a newer one) from https://developer.nvidia.com/cuda-toolkit-archive " - "and run it again (STRATA_NVCC= picks one toolkit)") - # RTX 50 (sm_120): CUDA 13.0 - an engine built with 12.8 crashed in the prompt path on Linux (#220). - # gpu["need_cuda"]: another engine's own floor (strata-poly, which is another prompt path: build_engine_poly) - need_cuda = need12 if old else gpu.get("need_cuda") or ((13, 0) if max(archs) >= 120 else (12, 0)) - vcvars = find_vcvars(cuda_v) if WIN else None - have_cc = vcvars is not None if WIN else shutil.which("g++") is not None - missing = [] - if not have_cc: - missing.append("Visual Studio 2022 Build Tools (C++)" if WIN else "the C++ compiler (build-essential)") - if nvcc is None or cuda_v < need_cuda: - missing.append("the NVIDIA CUDA Toolkit 13.0") - if not missing: - nvcc, cuda_v = sm120_nvcc(nvcc, cuda_v, archs) - ok(f"build tools present (CUDA {cuda_v[0]}.{cuda_v[1]})") - return nvcc, vcvars - say(" The engine has to be compiled for your PC, which needs: " + " and ".join(missing) + ".") - say(" They can be installed now (about 8-10 GB, 15-40 minutes" + (", Windows will ask for permission" if WIN else - ", sudo will ask for your password") + ").") - if ask(" Install them now?", ["y", "n"], "y", yes) != "y": - fail("the build tools are needed", "install them yourself (see README.md) and run it again") - if WIN: - if shutil.which("winget") is None: - fail("winget (Windows package manager) is not available", - "install 'App Installer' from the Microsoft Store, or install the tools by hand (README.md)") - wg = ["winget", "install", "-e", "--source", "winget", "--accept-package-agreements", - "--accept-source-agreements", "--disable-interactivity"] - if not have_cc: - run([*wg, "--id", "Microsoft.VisualStudio.2022.BuildTools", "--override", - "--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"], - check=False) - if nvcc is None or cuda_v < need_cuda: - run([*wg, "--id", "Nvidia.CUDA", "--version", "13.0"], check=False) - vcvars = find_vcvars(cuda_v) - else: - apt = shutil.which("apt-get") - if apt is None: - fail("missing: " + " and ".join(missing) + " (the automatic install is only done on Ubuntu/Debian)", - "install them with your distribution's packages (Arch: pacman -S base-devel cuda; nvcc is found on " - "PATH, in /usr/local/cuda* and in /opt/cuda*), then run it again") - if not have_cc: - run(["sudo", "apt-get", "install", "-y", "build-essential"]) - if nvcc is None or cuda_v < need_cuda: - osr = dict(line.split("=", 1) for line in open("/etc/os-release").read().splitlines() if "=" in line) - repo = cuda_apt_repo(osr) - if repo is None: - fail("the CUDA Toolkit can be installed automatically on Ubuntu 22.04 / 24.04 and Debian 12 / 13 only", - "install it from https://developer.nvidia.com/cuda-downloads and run it again") - deb = Path("/tmp/cuda-keyring.deb") - download(f"https://developer.download.nvidia.com/compute/cuda/repos/{repo}/x86_64/cuda-keyring_1.1-1_all.deb", - deb, "CUDA repository key") - run(["sudo", "dpkg", "-i", str(deb)]) - run(["sudo", "apt-get", "update"]) - if repo.startswith("ubuntu"): # as before: 13.0, and a failed install stops setup here - run(["sudo", "apt-get", "install", "-y", "cuda-toolkit-13-0"]) - else: - # Debian 13's CUDA repo carries no 13.0 package: take the oldest 13.x minor it has - for minor in range(10): - if run(["sudo", "apt-get", "install", "-y", f"cuda-toolkit-13-{minor}"], check=False).returncode == 0: - break - else: - fail(f"no cuda-toolkit-13-x package could be installed from NVIDIA's {repo} repository", - "install the CUDA Toolkit 13 from https://developer.nvidia.com/cuda-downloads and run it again") - nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc() - if (WIN and find_vcvars(cuda_v) is None) or (not WIN and shutil.which("g++") is None): - fail("the C++ build tools did not install", "install them by hand (README.md) and run it again") - if nvcc is None or cuda_v < need_cuda: - fail("the CUDA Toolkit did not install", "install it from https://developer.nvidia.com/cuda-downloads, then run it again") - nvcc, cuda_v = sm120_nvcc(nvcc, cuda_v, archs) - ok(f"build tools installed (CUDA {cuda_v[0]}.{cuda_v[1]})") - return nvcc, find_vcvars(cuda_v) if WIN else None - - -def cmake_build(src, bdir, target, defs, vcvars, bat_name): - cmake, ninja = find_tool("cmake"), find_tool("ninja") - if cmake is None or ninja is None: - fail("cmake / ninja not found after installing them", "run: .venv python -m pip install cmake ninja") - conf = [cmake, "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", "-S", str(src), "-B", str(bdir), - "-DCMAKE_BUILD_TYPE=Release", *defs] - build = [cmake, "--build", str(bdir), "--target", target, "-j", str(max(2, (os.cpu_count() or 4) // 2))] - # 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 - # the same command then gets past it (issue #45); a second attempt only compiles what is still missing. - if WIN: - if vcvars is None: # #881: the build needs MSVC's environment - fail("the Visual Studio C++ build tools were not found", - "install them (Visual Studio 2019 or 2022, workload 'Desktop development with C++') and run setup again") - bat = ROOT / bat_name - q = lambda c: " ".join(f'"{x}"' if " " in str(x) else str(x) for x in c) # noqa: E731 - bat.write_text(f'@echo off\r\ncall "{vcvars}"{vcvars_toolset(vcvars)} >nul\r\n' - f'{q(conf)} || exit /b 1\r\n{q(build)} && exit /b 0\r\n' - f'echo (the build stopped - trying it once more)\r\n{q(build)} || exit /b 1\r\n', - encoding="utf-8") - run(["cmd", "/c", str(bat)]) - else: - run(conf) - if run(build, check=False).returncode != 0: - say(" (the build stopped - trying it once more)") - run(build) - - -ENGINE_SOURCES = ("CMakeLists.txt", "cmake", "src", "include", "third_party/ggml") -VISION_SOURCES = ("tools/vision",) - - -def source_hash(parts) -> str: - """A fingerprint of the files a compiled engine is built from, kept in engine/BUILD.json: when a `git pull` - changes them, the engine is compiled again (issue #31).""" - h = hashlib.sha256(LLAMA_CPP_COMMIT.encode()) - for part in parts: - base = ROOT / part - for f in [base] if base.is_file() else sorted(x for x in base.rglob("*") if x.is_file()): - h.update(f.relative_to(ROOT).as_posix().encode() + b"\0" + f.read_bytes().replace(b"\r\n", b"\n")) - return h.hexdigest()[:16] - - -def isa_floor_defs(floor: str, bdir: Path, meta: dict) -> list: - """The experimental older-CPU build's CMake definition (STRATA_ISA_FLOOR, CMakeLists.txt), none for the normal - build. A build folder configured for another floor is configured afresh: ggml's CPU options are cached there.""" - if (meta.get("isa_floor") or "") != floor and (bdir / "CMakeCache.txt").exists(): - (bdir / "CMakeCache.txt").unlink() - return [f"-DSTRATA_ISA_FLOOR={floor}"] if floor else [] - - -def host_compiler_defs(cuda: bool) -> list: - """CC / CXX / CUDAHOSTCXX pick the host compilers of a build - as -D definitions, so an existing build folder - takes them too (the environment reaches CMake only on a folder's first configure, which is why CXX=g++-14 alone - could die at the last step, #1645). CUDAHOSTCXX is nvcc's host compiler (-ccbin); it defaults to CXX, as - CMake's does. `cuda`: the project compiles CUDA (the host-compiler definition means nothing to a C++-only - one).""" - cc = os.environ.get("CC", "").strip() - cxx = os.environ.get("CXX", "").strip() - hostcxx = os.environ.get("CUDAHOSTCXX", "").strip() or cxx - return ([f"-DCMAKE_C_COMPILER={cc}"] if cc else []) + \ - ([f"-DCMAKE_CXX_COMPILER={cxx}"] if cxx else []) + \ - ([f"-DCMAKE_CUDA_HOST_COMPILER={hostcxx}"] if cuda and hostcxx else []) - - -def toolkit_root_defs(nvcc) -> list: - """CUDAToolkit_ROOT for the toolkit whose nvcc builds the engine. Without it CMake can take cudart and cuBLAS from - another toolkit: with STRATA_NVCC=/opt/cuda-13.0/bin/nvcc on Ubuntu 24.04 that also has the distribution's CUDA - 12.0 (nvidia-cuda-toolkit), the engine was compiled with the 13.0 headers but linked libcudart.so.12 from - /usr/lib/x86_64-linux-gnu. The distribution's own nvcc (/usr/bin) keeps CMake's search as before.""" - root = Path(nvcc).resolve().parent.parent - return [] if root == Path("/usr") else [f"-DCUDAToolkit_ROOT={root}"] - - -def engine_defs(archs, toolkit=13) -> list: - """Extra CMake definitions for the engine: the experimental Pascal/Volta build (#295) for cards below sm_75, and - for every CUDA 12 engine (the same build as the ready-made CUDA 12 one: it admits the older cards).""" - return ["-DSTRATA_EXPERIMENTAL_SM60=ON"] if min(int(x) for x in archs) < 75 or int(toolkit) == 12 else [] - - -def prebuilt_vision(meta: dict, gpu: dict, vision: str) -> str: - """The image encoder to use with a ready-made engine (`meta`: its BUILD.json). The encoder can cover fewer cards - 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 - of compiling one, which fails on most Windows PCs (no Visual Studio / CUDA toolkit); --build compiles it.""" - if vision != "gpu": - return vision - va = [int(x) for x in meta.get("vision_archs", meta.get("archs", []))] - if va and int(gpu["arch"]) not in va and not (meta.get("ptx") and int(gpu["arch"]) > max(va)): - warn(f"the ready-made image encoder has no code for your GPU (sm_{gpu['arch']}): it runs on the CPU instead " - "(images take longer; setup --build compiles one for your GPU)") - return "cpu" - return vision - - -def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path: - """Compile the engine (and, for images, the encoder) for this GPU; the results go to engine/. A compiled - engine whose source files changed since (a `git pull`) is compiled again: only the changed files, a few minutes. - toolkit 12 (default: 12 for a card older than CUDA 13 supports): the experimental CUDA 12 engine, in - engine-cuda12/ with its own build folders.""" - if toolkit is None: - toolkit = 12 if min(int(x) for x in gpu.get("archs", [gpu["arch"]])) < CUDA13_MIN_ARCH else 13 - t12 = int(toolkit) == 12 - eng = engine_dir(toolkit) - eng.mkdir(exist_ok=True) - stamp = eng / "BUILD.json" - meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {} - want_vision = vision != "none" - local = meta.get("source") == "local" - src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) - archs = sorted({int(x) for x in gpu.get("archs", [gpu["arch"]])}) # every card the model runs on - built = {int(x) for x in meta.get("archs", [])} - # a card the engine has no code for (a GPU added with --gpus, #128) needs a compile even when the source is the - # same; the compile keeps the generations it was built for - new_arch = local and not set(archs) <= built - floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine - engine_ok = local and (eng / EXE).exists() and meta.get("src") == src and not new_arch and \ - (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE) - vision_ok = not want_vision or ((eng / VEXE).exists() and (not local or meta.get("vision_src") == vsrc)) - if engine_ok and vision_ok: - ok("engine already built for this PC") - return eng - if local: - archs = sorted(built | set(archs)) - nvcc, vcvars = install_build_tools({**gpu, "archs": archs, "toolkit": toolkit}, yes) - cuda_archs = ";".join(str(x) for x in archs) - bdir, vdir = (ROOT / "build-cuda12", ROOT / "build-vision-cuda12") if t12 else (ROOT / "build", ROOT / "build-vision") - if not engine_ok: - say(" Compiling the engine for " + ", ".join(f"sm_{x}" for x in archs) + " (a card it had no code for; " - "10-20 minutes, once) ..." if new_arch else - " The engine's source changed: compiling it again (only what changed, a few minutes) ..." - if local and (eng / EXE).exists() else " Compiling the PolyStrata engine for your GPU (10-20 minutes, once) ...") - cmake_build(ROOT, bdir, "strata", - ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", "-DSTRATA_Q6K_EXPERTS=ON", "-DSTRATA_MMQ_KQUANTS=ON", - f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", - f"-DCMAKE_CUDA_COMPILER={nvcc}", *toolkit_root_defs(nvcc), f"-DSTRATA_GGML_DIR={llama}", - *host_compiler_defs(True), *engine_defs(archs, toolkit), - *isa_floor_defs(floor, bdir, meta)], - vcvars, "build-strata-cuda12.bat" if t12 else "build-strata.bat") - if stale_binary(bdir / EXE): # #2054: the stamp below is written only for a binary of this source - fail(f"the engine build finished without a new engine ({EXE} is version {binary_engine_version(bdir / EXE)}, " - f"this source is {source_version()}): the installed engine and its stamp are left as they were", - "the build folder " + str(bdir) + " may be configured for something else: delete it and run this again") - shutil.copy2(bdir / EXE, eng / EXE) - if (bdir / KQ_LIB).exists(): # built with it (Phase 1): it goes next to the engine - shutil.copy2(bdir / KQ_LIB, eng / KQ_LIB) - elif (eng / KQ_LIB).exists(): # an older one of another build would only be refused - (eng / KQ_LIB).unlink() - if not vision_ok: - say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ...")) - defs = [f"-DLLAMA_DIR={get_llama_cpp(vision=True)}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}", - "-DSTRATA_PORTABLE=OFF", *host_compiler_defs(vision == "gpu")] # native, like the engine - if vision == "gpu": - defs += [f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", f"-DCMAKE_CUDA_COMPILER={nvcc}", - *toolkit_root_defs(nvcc)] - cmake_build(ROOT / "tools" / "vision", vdir, "strata-vision", defs, vcvars, - "build-vision-cuda12.bat" if t12 else "build-vision.bat") - shutil.copy2(vdir / "bin" / VEXE, eng / VEXE) - bindir = Path(nvcc).parent # the toolkit's own libraries (bin, bin/x64, lib64) - dirs = [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()] - stamp.write_text(json.dumps({"source": "local", "version": source_version(), "archs": archs, - "vision": vision, **({"toolkit": 12} if t12 else {}), - "cuda_dirs": dirs, "src": src, "vision_src": vsrc if want_vision else None, - **({"isa_floor": floor} if floor else {})}, indent=1)) - ok(f"engine compiled: {eng / EXE}") - return eng - - -# ------------------------------------------------------------------------------------------------ the data folder -# The model files - the GGUFs, the prepared packs and the MTP layer, 70-120 GB - live in a data folder NEXT TO the -# PolyStrata folder (`PolyStrata-data`), not inside it: updating PolyStrata by unzipping a new copy used to give a new, empty -# folder and a full download again. Where it is, and which PolyStrata folders this user ran, is kept in a small -# per-user file, so every PolyStrata folder on the PC finds the same files. -DATA_ITEMS = ("models", "packs", "mtp") - - -LOW_RAM_HEADROOM_GB = 10 # RAM beside the experts: the OS, the engine's other buffers, the server -RESIDENT_ENGINE = (0, 1, 30) # the first engine with --resident-experts (the low-RAM mode's resident variant) -RESIDENT_SPLIT_ENGINE = (0, 1, 40) # #642: the first engine that runs it on a layer split - - -def resident_split() -> bool: - """#642: the engine setup requires runs the low-RAM mode's resident variant on a layer split - each card's cache - holds the most-used experts of its own layers, and the RAM copy leaves out what any card holds. Before it, a - resident config on several GPUs read those experts through the OS file cache (#364 #384).""" - return MIN_ENGINE >= RESIDENT_SPLIT_ENGINE - - -def low_ram_needed(model, ram) -> bool: - """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 - experts.bin instead of copied into RAM (the low-RAM mode).""" - return ram < MODELS[model]["arena_gb"] + LOW_RAM_HEADROOM_GB - - -def low_ram_gpu_gb(model, vram_gb, ctx=32768, kv="int8") -> float: - """About how many GB of the model's experts the GPU's cache holds: its VRAM minus ~5 GB for the dense weights, - 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 - has no room for KV streaming).""" - kv_tok = 13 * KV_CELL_BYTES.get(kv, 1056) # bytes per context token: 12 QSA layers + the draft layer - longer = max(0, ctx - 32768) * kv_tok / 1e9 - return max(0.0, min(MODELS[model]["arena_gb"], vram_gb - 5 - longer)) - - -def low_ram_gpu_share(model, vram_gb, ctx=32768, kv="int8") -> float: - """About how much of the model's experts the GPU holds.""" - return low_ram_gpu_gb(model, vram_gb, ctx, kv) / MODELS[model]["arena_gb"] - - -def low_ram_resident(model, ram, vram_gb, ctx=32768, kv="int8") -> bool: - """In the low-RAM mode: the experts the GPU does not hold fit the RAM with the usual room beside them, so they are - copied into RAM once (the resident variant, `--resident-experts`) instead of being read through the OS file cache - (plain `--mmap-experts`, which a PC this short of RAM keeps re-reading from the SSD).""" - rest = MODELS[model]["arena_gb"] - low_ram_gpu_gb(model, vram_gb, ctx, kv) - return ram >= rest + LOW_RAM_HEADROOM_GB - - -def low_ram_fits(model, ram, vram_gb) -> bool: - """In the low-RAM mode: the experts the GPU does not hold fit the RAM left beside the rest (as file cache).""" - arena = MODELS[model]["arena_gb"] - return ram - 6 + max(0.0, vram_gb - 5) >= arena - - -def low_ram_wanted(model, ram, choice="auto") -> bool: - """Does setup put this model in the low-RAM mode on this PC: its experts do not fit the RAM with the usual room - beside them (`low_ram_needed`), or the user asked for it. Unsloth's 4-bit file is not the low-RAM mode at all: - it always reads part of its experts from the files, through its RAM budget. Step 5 applies exactly this answer, - and the launcher's preset diff asks it too - so a preset that says "auto" is compared with what auto decides, - not with the word.""" - if MODELS[model].get("budget"): - return False - return choice in ("on", "resident", "mmap") or (choice == "auto" and low_ram_needed(model, ram)) - - -def kv_streaming_ram_gb(ctx, kv) -> float: - """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 - K8V4, 7.5 KB with 4-bit - 12 QSA layers + the draft layer.""" - return ctx * (13 * KV_CELL_BYTES.get(kv, 1056)) / 1e9 - - -def kv_streaming_wanted(model, ctx, kv, ram, choice="auto") -> bool: - """Will setup stream this model's KV cache on this PC: from 64K up, when the RAM holds the cache beside the - model's experts (+1 GB); `--kv-streaming on|off` overrides the RAM test (the owner's rule), and WSL never - streams. Step 7 writes `--kv-resident` on exactly this answer, and the launcher's preset diff - asks it too: a config's `--kv-resident` and a preset's "auto" are the same setting when this says yes.""" - if is_wsl() or choice == "off": - return False - return ctx >= 65536 and (ram >= MODELS[model]["ram_gb"] + kv_streaming_ram_gb(ctx, kv) + 1 or choice == "on") - - -def low_ram_one_gpu_why(model, ram, choice, sel=None) -> list[str]: - """#250: why the low-RAM mode recommends one GPU, with the RAM math that turned it on; #364 #384: and how to use - all of them (sel: the cards, for the --gpus example).""" - arena, need = MODELS[model]["arena_gb"], MODELS[model]["arena_gb"] + LOW_RAM_HEADROOM_GB - if choice == "auto": - why = [f"Why: {model}'s experts are {arena:.0f} GB and must fit in RAM with ~{LOW_RAM_HEADROOM_GB} GB beside " - f"them for the OS and the rest: {arena:.0f} + {LOW_RAM_HEADROOM_GB} = {need:.0f} GB, and this PC has " - f"{ram:.0f} GB.", - "So setup uses the low-RAM mode: the experts come from the model's file (copied into RAM as far as " - "it fits), the GPU holds the most-used ones."] - else: - why = [f"Why: you chose the low-RAM mode (--low-ram {choice}); without it {model} needs {arena:.0f} + " - f"{LOW_RAM_HEADROOM_GB} = {need:.0f} GB of RAM, this PC has {ram:.0f} GB."] - return why + ["Its resident variant (the experts the GPU does not hold copied into RAM once: steady RAM use) runs " - "on one GPU: the engine has no layer split for it yet.", - f"To use all the GPUs: --gpus {','.join(str(i) for i in sel) if sel else '0,1'} - the experts the " - "GPUs do not hold are then read through the OS file cache: faster in two reports (1.3-1.6x, #364 " - f"#384), but RAM can fill up to 0 free during long prompts. Or {need:.0f} GB of RAM or more, or a " - "smaller size."] - - -def low_ram_together(a, model, ram, gpu, chosen) -> bool: - """#364 #384: the low-RAM mode with several GPUs chosen. One GPU is recommended: the resident variant keeps the - experts the GPU does not hold in RAM (steady RAM use) and has no layer split. All the GPUs together read those - experts through the OS file cache instead (--mmap-experts) - 1.3-1.6x faster in those reports, but RAM can fill - up to 0 free during long prompts. An explicit --gpus (or an earlier install's cards) is kept; otherwise asked, - one GPU by default (--yes: one GPU, as before). True: all of them.""" - sel = [g["index"] for g in chosen] - names = " + ".join(gpu_name(g) for g in chosen) - if a.gpus: - warn(f"the low-RAM mode on {names}, as you chose (--gpus): the experts the GPUs do not hold are read through " - "the OS file cache (the resident variant has no layer split yet), and RAM can fill up to 0 free during " - "long prompts") - say(f" One GPU keeps them in RAM (steady RAM use, recommended): --gpu {gpu['index']}") - if a.low_ram == "resident": - warn("--low-ram resident has no layer split yet: the experts are read through the OS file cache instead") - return True - if a.low_ram != "resident" and not a.yes: - say() - for line in low_ram_one_gpu_why(model, ram, a.low_ram, sel): - say(" " + line) - say(f" 1) {gpu_name(gpu)} only: the experts it does not hold kept in RAM where they fit (recommended: " - "steady RAM use)") - say(f" 2) {names} together: the experts the GPUs do not hold read through the OS file cache - faster") - say(" in two reports (1.3-1.6x, #364 #384), but RAM can fill up to 0 free during long prompts") - if ask("Low-RAM mode: which GPUs?", ["1", "2"], "1", a.yes) == "2": - ok(f"the low-RAM mode on {names}: the experts read through the OS file cache, as you chose") - return True - warn("the low-RAM mode: using " + gpu_name(gpu) + " only") - return False - warn("the low-RAM mode: using " + gpu_name(gpu) + " only (recommended)") - for line in low_ram_one_gpu_why(model, ram, a.low_ram, sel): - say(" " + line) - return False - - -def unsloth_together(a, model, ram, gpu, chosen) -> bool: - """#498: UD-Q4_K_XL with several GPUs chosen. Its RAM budget (--resident-budget-gib) has no layer split, so a - split runs without it: all its experts loaded into RAM from the GGUFs at start, as with the 2-3-bit models - only - where the RAM holds the GGUF files and 24 GB more (unsloth_split_need_gb; 165 GiB, 2x RTX 3090: 31 -> 64-78 - tok/s). An explicit --gpus is honoured there; otherwise asked, one GPU by default (--yes: one GPU, as before); an - explicit --resident-budget-gib keeps one GPU. #642: the engines from RESIDENT_SPLIT_ENGINE keep the budget on a - split (the experts no card holds, the hottest by the whole profile), so there the cards go together with it, at - any RAM: --gpus, or "2" when asked; one GPU stays the recommendation (--yes alone: one GPU, as before). True: all - of them.""" - names = " + ".join(gpu_name(g) for g in chosen) - if resident_split(): - note = "with its RAM budget (each card caches its own layers' experts, the RAM the hottest of the rest; #642)" - if a.gpus: - ok(f"{model} on {names}, as you chose (--gpus), {note}") - return True - if not a.yes: - say() - say(f" {model} runs with a RAM budget of its experts, on one GPU or on {names} together:") - say(f" 1) {gpu_name(gpu)} only (recommended: the tested setup)") - say(f" 2) {names} together: each card caches the experts of its own layers (#642)") - if ask(f"{model}: which GPUs?", ["1", "2"], "1", a.yes) == "2": - ok(f"{model} on {names}, {note}") - return True - warn(f"{model} runs on one GPU: using {gpu_name(gpu)} only (--gpus " + ",".join(str(g["index"]) for g in chosen) - + f" shares it across {names}, with its RAM budget)") - return False - need = unsloth_split_need_gb(model) - if ram < need: - note = (f"{model} on several GPUs has no RAM budget and needs ~{need:.0f} GB of RAM (its GGUF files and " - f"{UNSLOTH_RAM_LEFT_GB} GB more), this PC has {ram:.0f}; the estimate is a worst case (#737: a 128 GB PC " - "ran it)") - if a.gpus and a.resident_budget_gib is None: # #737: asked for by name: a question, not a refusal - confirm_risk(note + ", but it may page or stall here", True, a.yes, - f"{model} on several GPUs needs ~{need:.0f} GB of RAM; this PC has {ram:.0f} GB", - f"start it on one GPU: --gpus {gpu['index']}", " Use them together anyway?") - ok(f"{model} on {names}, as you chose (--gpus), with {ram:.0f} GB of RAM") - return True - warn(f"{note} - using {gpu_name(gpu)} only (--gpus " + ",".join(str(g["index"]) for g in chosen) + - " uses them together anyway)") - return False - if a.resident_budget_gib is not None: - warn(f"--resident-budget-gib has no layer split: {model} runs on one GPU with it - using {gpu_name(gpu)} only " - f"(leave the budget out to use {names} together)") - return False - note = (f"no RAM budget - all of its experts (~{MODELS[model]['arena_gb']:.0f} GB) are loaded into RAM from the " - f"model files at start, and the files pass through the OS file cache (needs ~{need:.0f} GB of RAM, this " - f"PC has {ram:.0f})") - if a.gpus: - ok(f"{model} on {names}, as you chose (--gpus): {note}") - return True - if not a.yes: - say() - say(f" {model} can run on one GPU with a RAM budget of its experts, or on {names} together without one:") - say(f" 1) {gpu_name(gpu)} only: the most-used experts kept in RAM, the rest read from the SSD (recommended: " - "the tested setup)") - say(f" 2) {names} together: {note};") - say(" about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s)") - if ask(f"{model}: which GPUs?", ["1", "2"], "1", a.yes) == "2": - ok(f"{model} on {names}: {note}") - return True - warn(f"{model} runs on one GPU: using {gpu_name(gpu)} only (--gpus " + ",".join(str(g["index"]) for g in chosen) + - f" shares it across {names} without the RAM budget: this PC's RAM holds it)") - return False - - -def confirm_risk(msg, explicit, yes, stop, hint=None, question=" Go on anyway?", default="n") -> None: - """The owner's rule: setup recommends, it never forces. A choice setup expects to fail or run badly is said - plainly (msg), then asked (default n; `default` keeps an older question's own default), or with --yes taken as - consent when it was asked for explicitly (a flag such as --model or --gpus): --yes alone keeps the stop - (stop, hint). Returns when it goes on; the caller says what it does.""" - warn(msg) - if yes and explicit: - return - if ask(question, ["y", "n"], default, yes) != "y": - fail(stop, hint) - - -def confirm_paging(model, ram, choice, yes, explicit_model=False): - """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 - a stop - the user may accept paging. Asked "no" by default, so an unattended --yes install stops here, unless - the low-RAM mode was turned off explicitly (--low-ram off, #250) or the size was (--model): that is the choice - already made.""" - need_gb, arena = MODELS[model]["ram_gb"], MODELS[model]["arena_gb"] - off = choice == "off" - confirm_risk(f"{model} needs about {need_gb} GB of RAM and this PC has {ram:.0f} GB: its experts alone are " - f"{arena:.0f} GB and must stay in RAM, so Windows/Linux will page part of them from disk. Expect it " - "to be much slower, and it may not start at all.\n A smaller size (Q2_0 or IQ2_XS) fits; more " - "RAM fixes it.", off or explicit_model, yes, - f"{model} needs about {need_gb} GB of RAM; this PC has {ram:.0f} GB", - "choose Q2_0 or IQ2_XS, or add RAM" + ("" if off else f"; or --model {model} --yes (or --low-ram off " - "--yes) to install it anyway"), - " Install it anyway?", "y" if off else "n") - warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose" + (" (--low-ram off)" if off else - " (--model)" if explicit_model else "")) - - -def ctx_ram_need(model, ctx, low_ram=False): - """#406: the RAM (GB) setup estimates for a long context with IQ3_XXS / IQ3_S: their experts + the context's - 8-bit KV cache + 24 GB of room for everything else (the 0.1.29 arithmetic, counted). None where the context does - not count against RAM by this rule: the other sizes, and the low-RAM mode (its KV cache stays in VRAM).""" - if model not in ("IQ3_XXS", "IQ3_S") or low_ram: - return None - return MODELS[model]["arena_gb"] + ctx * 13 * 1056 / 1e9 + 24 - - -def ram_ctx(model, ram, low_ram=False) -> int: - """#406: the longest context the RAM rule recommends: 128K, or longer where the estimate fits this PC's RAM. It - is part of the recommended default (the smaller of it and the GPU's rule); a longer choice is kept, with a note. - The 200K menu step is never the recommendation (#608).""" - # 204800 (#608) is a menu step between 128K and 256K, never the recommendation: where 256K does not fit, 128K stays - return max(c for c in CONTEXTS if c <= 131072 or (c != 204800 and (ctx_ram_need(model, c, low_ram) or 0) <= ram)) - - -def settings_path() -> Path: - if WIN: - return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "PolyStrata" / "settings.json" - return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "polystrata" / "settings.json" - - -def load_settings() -> dict: - try: - return json.loads(settings_path().read_text(encoding="utf-8")) - except (OSError, ValueError): - return {} - - -def save_settings(s: dict) -> None: - try: - settings_path().parent.mkdir(parents=True, exist_ok=True) - settings_path().write_text(json.dumps(s, indent=1), encoding="utf-8") - except OSError as e: - warn(f"could not save {settings_path()} ({e})") - - -def has_data(folder: Path) -> bool: - for d in DATA_ITEMS: - try: - if (folder / d).is_dir() and any((folder / d).iterdir()): - return True - except OSError: - pass - return False - - -def other_installs(settings: dict) -> list: - """PolyStrata folders besides this one that may hold model files: the ones this user ran before, and PolyStrata* folders - next to this one (a zip unpacked again lands in e.g. `PolyStrata-main (1)\\PolyStrata-main`).""" - cands = [Path(p) for p in settings.get("installs", [])] - for base in dict.fromkeys((ROOT.parent, ROOT.parent.parent)): - try: - for d in base.iterdir(): - if d.is_dir() and d.name.lower().startswith("polystrata"): - cands.append(d) - cands += [c for c in d.iterdir() if c.is_dir() and c.name.lower().startswith("polystrata")] - except OSError: - pass - found = [] - for d in cands: - try: - d = d.resolve() - if d != ROOT and d not in found and (d / "setup.py").is_file(): - found.append(d) - except OSError: - pass - return found - - -def same_drive(a: Path, b: Path) -> bool: - try: - return os.stat(a).st_dev == os.stat(b).st_dev - except OSError: - return False - - -def move_into(src: Path, dst: Path) -> None: - """A rename into the data folder (same drive: instant); a folder merges into one already there, keeping what the - destination has. Whatever cannot be moved (a file in use) stays where it is.""" - if not dst.exists(): - try: - dst.parent.mkdir(parents=True, exist_ok=True) - os.replace(src, dst) - return - except OSError: - if not src.is_dir(): - return - dst.mkdir(parents=True, exist_ok=True) - if src.is_dir() and dst.is_dir(): - for c in list(src.iterdir()): - move_into(c, dst / c.name) - try: - src.rmdir() - except OSError: - pass - - -def repoint_config(cfg_file: Path, old: Path, new: Path) -> None: - """A config whose model files moved from `old` to `new` points at them there (each path only if its file is - now there and no longer at the old place).""" - try: - cfg = json.loads(cfg_file.read_text(encoding="utf-8-sig")) - except (OSError, ValueError): - return - - def fix(v): - if isinstance(v, list): - return [fix(x) for x in v] - if isinstance(v, dict): - return {k: fix(x) for k, x in v.items()} - if isinstance(v, str): - for d in DATA_ITEMS: - o = str(old / d) - nv, no = os.path.normcase(v), os.path.normcase(o) # Windows: C:\ and c:\ are the same place - if nv == no or nv.startswith(no + os.sep): - n = str(new / d) + v[len(o):] - if Path(n).exists() and not Path(v).exists(): - return n - return v - - new_cfg = fix(cfg) - if new_cfg != cfg: - write_config(cfg_file, new_cfg) - - -def data_folder(requested: str | None) -> tuple: - """(the data folder, folders on other drives that still hold model files). Moves the model files of this folder - and of earlier PolyStrata folders on the same drive into the data folder, and points their configs there.""" - settings = load_settings() - dest = Path(requested).expanduser().resolve() if requested else \ - Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "PolyStrata-data" - try: - dest.mkdir(parents=True, exist_ok=True) - except OSError as e: # e.g. no write access next to the PolyStrata folder - warn(f"cannot use {dest} for the model files ({e}): keeping them in {ROOT}") - dest = ROOT - elsewhere = [] - # #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a PolyStrata-data - # folder nested in any of them (an install that kept its models one level down) - sources = [ROOT, *other_installs(settings)] - if settings.get("data_dir") and Path(settings["data_dir"]) != dest: - sources.append(Path(settings["data_dir"])) - sources += [f / "PolyStrata-data" for f in list(sources) if (f / "PolyStrata-data") != dest] - seen = set() - for folder in sources: - key = os.path.normcase(str(folder)) - if key in seen: - continue - seen.add(key) - if folder == dest or not has_data(folder): - continue - if not same_drive(folder, dest): - elsewhere.append(folder) # another drive: used where it is (no 70 GB copy) - continue - # the downloads merge file by file (the same file wherever it came from); a prepared pack or MTP layer moves - # whole or not at all, so two copies are never mixed - if (folder / "models").is_dir(): - move_into(folder / "models", dest / "models") - for item in [*((folder / "packs").glob("*") if (folder / "packs").is_dir() else []), folder / "mtp"]: - rel = item.relative_to(folder) - if item.exists() and not (dest / rel).exists(): - move_into(item, dest / rel) - for d in ("packs",): - try: - (folder / d).rmdir() # empty now - except OSError: - pass - for c in model_config_files(folder): - repoint_config(c, folder, dest) - if has_data(folder): - elsewhere.append(folder) # in use, or a copy the data folder already has - warn(f"some model files are still in {folder} (in use, or already in {dest})") - else: - ok(f"model files from {folder} moved to {dest} (a new copy of PolyStrata finds them there)") - installs = [str(ROOT)] + [p for p in settings.get("installs", []) if p != str(ROOT) and Path(p).is_dir()] - save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]}) - return dest, elsewhere - - -def write_config(path: Path, cfg: dict): - """A run config, written whole or not at all (#459): to a temporary file first, then moved over the old one, so - a setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind.""" - tmp = path.with_name(path.name + ".tmp") - tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") - os.replace(tmp, path) - - -# #629: the run config's keys setup writes itself (and rewrites on every setup run); any other key is the user's - a -# "sampling" or "mcp_servers" block, "allowed_hosts", "cors_origins", "open_browser" - and is kept when setup runs again -SETUP_KEYS = frozenset({"exe", "args", "cwd", "tokenizer", "model_name", "log", "lib_dirs", "port", "backend", "env", - "gpu", "gpus_asked", "layer_split", "host", "api_key", "draft_vocab", "vision", - "display_name", "cuda"}) -SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_ROCBLAS_TUNING", "STRATA_RESIDENT_PIN", "STRATA_NO_ARENA_THP", "STRATA_MMQ_KQ", "STRATA_HC_Q8", - "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) -# 0.1.44 added these three, written for Unsloth's files only (unsloth_default_env). In any other model's config they are the -# 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 -# (0.1.44 dropped them with the rest of SETUP_ENV). -SETUP_ENV_UNSLOTH = frozenset({"STRATA_MMQ_KQ", "STRATA_HC_Q8", "STRATA_ROUTE_TAIL_SKIP"}) -SETUP_VISION = frozenset({"exe", "mmproj", "model", "gpu", "max_tokens", "threads"}) - - -def carry_over(old: dict, cfg: dict) -> list[str]: - """#629: setup run again for an installed model keeps what the user added to its run config: every key setup does - not write (`SETUP_KEYS`), the "env" entries setup does not write, and in "vision" the keys setup does not write - plus an mmproj of their own (a Q8_0 one, #625) that still exists. `cfg` (the new config) is updated in place; - the names of what was kept are returned. Engine options added by hand to "args" are not merged (setup chooses - those): `args_dropped` names them.""" - kept = [] - for k, v in old.items(): - if k not in SETUP_KEYS and k not in cfg: - cfg[k] = v - kept.append(k) - mine = SETUP_ENV if "-unsloth-" in str(cfg.get("model_name") or "") else SETUP_ENV - SETUP_ENV_UNSLOTH - 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 {})} \ - if isinstance(old.get("env"), dict) else {} - if env: - cfg["env"] = {**(cfg.get("env") or {}), **env} - kept += [f"env {k}" for k in env] - ov, nv = old.get("vision"), cfg.get("vision") - if isinstance(ov, dict) and isinstance(nv, dict): - for k, v in ov.items(): - if k not in SETUP_VISION and k not in nv: - nv[k] = v - kept.append(f"vision {k}") - mm = ov.get("mmproj") # a file of the user's own: not the one setup downloads - if isinstance(mm, str) and Path(mm).name != Path(str(nv.get("mmproj"))).name and Path(mm).is_file(): - nv["mmproj"] = mm - kept.append("vision mmproj") - kept += carry_profile_args(old, cfg) - return kept - - -def flag_value(args: list, flag: str): - """The value after `flag` in an argument list, or None.""" - for i, a in enumerate(args[:-1]): - if a == flag: - return str(args[i + 1]) - return None - - -def carry_profile_args(old: dict, cfg: dict) -> list[str]: - """#775: a learned expert profile the user wired in by hand (--expert-profile , --expert-profile-save - ) survives a setup run: setup writes the shipped profile, which a measured one of their own beats (2.5-3.1x at - 256K on a 16 GB card in the report). Their --expert-profile replaces the shipped one only when it is another file - that still exists; --expert-profile-save is kept when the new config has none. The names kept are returned.""" - oargs, nargs = old.get("args"), cfg.get("args") - if not isinstance(oargs, list) or not isinstance(nargs, list): - return [] - kept = [] - mine, shipped = flag_value(oargs, "--expert-profile"), flag_value(nargs, "--expert-profile") - if mine and shipped and Path(mine).name != Path(shipped).name and Path(mine).is_file(): - nargs[nargs.index("--expert-profile") + 1] = mine - kept.append("args --expert-profile") - save = flag_value(oargs, "--expert-profile-save") - if save and flag_value(nargs, "--expert-profile-save") is None: - nargs += ["--expert-profile-save", save] - kept.append("args --expert-profile-save") - return kept - - -def args_dropped(old: dict, cfg: dict) -> list[str]: - """#629: the engine options of the earlier run config that the new one has no more (by flag name): options added - by hand, which a setup run does not carry over - the start of the line that names them.""" - def flags(c): - a = c.get("args") if isinstance(c.get("args"), list) else [] - return [str(x) for x in a if str(x).startswith("--")] - new = set(flags(cfg)) - return list(dict.fromkeys(f for f in flags(old) if f not in new)) - - -def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> None: - """#629: setup's run config, written over an earlier one for the same model without losing what the user added - to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as - strata-.json.bak when it changes. `source`: an earlier install's config to carry the keys over from when - this folder has none yet (a copy set up like the last one). A line says what was kept, one what was not.""" - old_path = cfg_path if cfg_path.is_file() else source - old = None - if old_path is not None and old_path.is_file(): - try: - old = json.loads(old_path.read_text(encoding="utf-8-sig")) - except (OSError, ValueError): - pass - if not isinstance(old, dict): - old = None - kept = carry_over(old, cfg) if old is not None else [] - if "images" in cfg and cfg["images"] is None: # --images no (or not downloaded): no image section - cfg.pop("images") - bak = None - if cfg_path.is_file() and old != cfg: - bak = cfg_path.with_name(cfg_path.name + ".bak") - try: - shutil.copyfile(cfg_path, bak) - except OSError as e: - warn(f"could not keep a copy of the earlier {cfg_path.name} ({e.strerror or e})") - bak = None - write_config(cfg_path, cfg) - if kept: - ok(f"kept from your earlier {old_path.name}: " + ", ".join(kept)) - if bak is not None: - dropped = args_dropped(old, cfg) if old is not None else [] - say(f" the earlier run config is kept as {bak.name}" + ( - f"; engine options it had that this one has not (setup chooses those): {' '.join(dropped)}" - if dropped else "")) - - -def readable_config(path: Path) -> bool: - """#459: a config that parses as a JSON object; any other gets a one-line warning naming it.""" - text = None - try: - text = path.read_text(encoding="utf-8-sig") - if isinstance(json.loads(text), dict): - return True - why = "not a JSON object" - except OSError as e: - why = e.strerror or str(e) - except ValueError: # JSONDecodeError, or bytes that are not UTF-8 - why = "the file is empty" if text is not None and not text.strip() else "not valid JSON" - warn(f"skipped the earlier config {path} ({why}): setting this copy up without it") - return False - - -def model_config_files(folder: Path) -> list: - """#346: the strata-*.json files of a folder that can be model configs. The server keeps a config's Chat settings - next to it as strata-.shared-settings.json: it matches the pattern but is no config (no exe, no args).""" - return [p for p in folder.glob("strata-*.json") if not p.name.endswith(".shared-settings.json")] - - -def previous_config(elsewhere_first: list, settings: dict): - """The most recently used model config of another PolyStrata folder on this PC, for a folder that has none yet. One - that does not parse (an empty or cut-off file, #459) is skipped with a warning: the newest readable one is used, - and with none this copy is set up as a fresh install.""" - cands = [] - for folder in [*elsewhere_first, *other_installs(settings)]: - cands += model_config_files(folder) - cands = [c for c in dict.fromkeys(cands) if c.is_file()] - return next((c for c in sorted(cands, key=lambda p: p.stat().st_mtime, reverse=True) if readable_config(c)), None) - - -def own_path_config(cfg: dict) -> bool: - """A config for a family with its own engine path (Qwen3.6): its --mtp is a draft count, not a draft layer.""" - return cfg.get("arch") in {d["arch"] for d in OWN_PATH_FAMILIES.values()} - - -def choices_from_config(cfg_path: Path) -> dict: - """The setup answers a config was written with (family, size, context, KV, images, projection, network).""" - cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) - tag = cfg_path.stem[len("strata-"):] - own = next((f for f, d in OWN_PATH_FAMILIES.items() if tag.startswith(d["tag"])), None) - if own is not None: # Qwen3.6: its own sizes; no KV / images / projection settings - d = OWN_PATH_FAMILIES[own] - size = next((m for m in d["models"] if m.lower() == tag[len(d["tag"]):].lower()), None) - a = cfg.get("args", []) - ctx = a[a.index("--max-context") + 1] if "--max-context" in a and a.index("--max-context") + 1 < len(a) else None - vis = cfg.get("vision") - return {"family": own, "model": size, "context": int(ctx) if ctx and ctx.isdigit() else None, "kv": None, - "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"), - "port": cfg.get("port"), "gpu": cfg.get("gpu"), "layer_split": None, - "cuda": 12 if config_toolkit(cfg) == 12 else None, "vram_reserve_mib": None} - family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen") - model = (tag[len(FAMILIES[family]["tag"]):] if tag.startswith(FAMILIES[family]["tag"]) else tag).upper() - sizes = FAMILIES[family].get("models", MODELS) # a family's own sizes, where it has them - if model not in sizes: # (sizes have no dash except UD-Q4_K_XL: the old rule) - model = tag.split("-")[-1].upper() - a = cfg.get("args", []) - val = lambda k: a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None # noqa: E731 - vis = cfg.get("vision") - esp = val("--control-vector-scaled") - esp_path = esp.rsplit(":", 1)[0] if esp else None - return {"family": family, "model": model if model in sizes else None, - "context": int(val("--max-context")) if val("--max-context") else None, - "kv": val("--kv") if val("--kv") in ("int8", "q4_0") else None, - "vision": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none", - "esp": ("on" if Path(esp_path).name == ESP_VECTOR.name else esp_path) if esp_path else "off", - "host": cfg.get("host"), "api_key": cfg.get("api_key"), "port": cfg.get("port"), "gpu": cfg.get("gpu"), - "layer_split": cfg.get("layer_split"), "cuda": 12 if config_toolkit(cfg) == 12 else None, - # #493: --vram-reserve-mib given at setup (images write the default 700 themselves) - "vram_reserve_mib": int(val("--vram-reserve-mib")) if (val("--vram-reserve-mib") or "").isdigit() and ( - vis is None or int(val("--vram-reserve-mib")) != VISION["gpu"]["reserve_mib"]) else None} - - -def calibration_targets(have: list, model: str | None, family: str | None) -> list: - """#2036: the installed configs `--calibrate --model X` (and/or --family) means; every config with neither.""" - if not (model or family): - return [c for c in have if choices_from_config(c)["family"] not in OWN_PATH_FAMILIES] - out = [] - for c in have: - ch = choices_from_config(c) - if ch["family"] in OWN_PATH_FAMILIES: # the tuning measures Flash-Next's engine settings - continue - if (not model or ch["model"] == model) and (not family or ch["family"] == family): - out.append(c) - return out - - -def find_in(roots: list, rel: str): - """The first of roots/rel that exists.""" - for r in roots: - if (r / rel).exists(): - return r / rel - return None - - -# ------------------------------------------------------------------------------------------------ start -def model_config(path: Path) -> bool: - """#549: a model's run config (a JSON object with "exe" and "args"). Any other strata-*.json in the folder (a - file of the user's own, a cut-off one) is skipped with a warning naming it instead of stopping setup.""" - try: - cfg = json.loads(path.read_text(encoding="utf-8-sig")) - if isinstance(cfg, dict) and cfg.get("exe") and isinstance(cfg.get("args"), list): - return True - why = 'no "exe" or "args"' - except OSError as e: - why = e.strerror or str(e) - except ValueError: - why = "not valid JSON" - warn(f"skipped {path.name} ({why}): it is not a PolyStrata model config") - return False - - -def installed_configs(): - return [p for p in sorted(model_config_files(ROOT), key=lambda p: p.stat().st_mtime, reverse=True) - if model_config(p)] - - -def source_version() -> str: - """The engine version the source tree builds (CMakeLists.txt's project version).""" - m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8")) - return m.group(1) if m else "0" - - -def binary_engine_version(exe) -> str | None: - """The version compiled into an engine binary (the `engine=X.Y.Z` line it prints at start; 0.1.13 and newer carry - it), read from the file without running it. None: unreadable, or a binary without it.""" - try: - m = re.search(rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n", Path(exe).read_bytes()) - except OSError: - return None - return m.group(1).decode() if m else None - - -def stale_binary(exe) -> bool: - """#2054: the engine binary is of another version than this source tree builds. A BUILD.json that carries the - source's hash and version cannot be trusted alone: a build that stopped (a host compiler the toolkit rejects) can - leave the old binary beside a stamp of the new source, and nothing would ever compile it again.""" - v = binary_engine_version(exe) - return v is not None and v != source_version() - - -def engine_version(exe: Path) -> tuple: - """The version in the engine folder's BUILD.json, or else the one compiled into the binary. A locally compiled - engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept - (issue #49).""" - try: - meta = json.loads((Path(exe).parent / "BUILD.json").read_text(encoding="utf-8")) - except (OSError, ValueError): - meta = {} - v = str(meta.get("version") or "") - if not v: # the version compiled into the binary: 0.1.13 and newer - try: # carry it, so a binary without it is older - m = re.search(rb"engine=(\d+\.\d+\.\d+(?:\.\d+)?)\n", Path(exe).read_bytes()) - v = m.group(1).decode() if m else "0.1.12" - except OSError: - v = "0" - return tuple(int(x) for x in v.split(".")[:4] if x.isdigit()) - - -def is_wsl() -> bool: - return sys.platform.startswith("linux") and "microsoft" in platform.uname().release.lower() - - -def rotational_disk(path) -> str | None: - """#605 (Linux): the disk's name when `path` is on a rotational disk (sysfs queue/rotational), else None.""" - if WIN: - return None - try: - st = os.stat(path) - p = Path(f"/sys/dev/block/{os.major(st.st_dev)}:{os.minor(st.st_dev)}").resolve() - for q in (p, p.parent): # a partition has its disk's queue - f = q / "queue" / "rotational" - if f.exists(): - return q.name if f.read_text().strip() == "1" else None - except (OSError, ValueError, AttributeError): - pass - return None - - -def hip_config_cards(sel) -> list[dict]: - """#566: the AMD cards a HIP config runs on - its "gpu" (one index or a list) in HIP's numbering, as amd_gpus - lists them; no "gpu": the supported card with the most VRAM, as setup picks it. Each card's name carries its - architecture (an RX 7900 XTX and an RX 7900 XT are both gfx1100; a card without a product name in sysfs is known - by its arch only). A card that is not found is {} (the key then says "?").""" - amd = amd_gpus() - if sel is None: - usable = [g for g in amd if amd_problem(g) is None] - sel = min(usable, key=amd_rank)["index"] if usable else None - byid = {g["index"]: g for g in amd} - cards = [] - for i in (sel if isinstance(sel, list) else [sel]): - g = byid.get(i) - if g is None: - cards.append({}) - continue - arch = g.get("arch") or "" - name = g.get("name") or "?" - cards.append({**g, "name": name if not arch or arch in name else f"{name} ({arch})"}) - return cards - - -def hardware_key(cfg: dict) -> str: - """What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting - (the context's KV cache and the image encoder take VRAM from the expert cache). #566: a HIP config's cards are - AMD's (hip_config_cards) - nvidia-smi's list named them "?" (or another card with that number) before.""" - sel = cfg.get("gpu") - if cfg.get("backend") == "hip": - gl = hip_config_cards(sel) - else: - gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}] - g = {"name": " + ".join(x.get("name", "?") for x in gl), "vram_gb": sum(x.get("vram_gb", 0) for x in gl)} - a = cfg.get("args", []) - ctx = a[a.index("--max-context") + 1] if "--max-context" in a else "?" - return "|".join([g.get("name", "?"), f"{g.get('vram_gb', 0):.0f}GB", cpu_info()[0], f"{ram_gb():.0f}GB", - cfg.get("model_name", "?"), ctx, "images" if "--vision" in a else "text"]) - - -def calibrate_config(cfg_path: Path) -> bool: - """Measure the engine's hardware-dependent settings on this PC (tools/calibrate.py), write them into the run - config and remember them per PC and model in the settings file, so an update or a reinstall keeps them.""" - sys.path.insert(0, str(ROOT / "tools")) - import calibrate as CAL - cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) - say() - say(" Tuning PolyStrata for this PC: the output speed is measured with a few engine settings (the PCIe share, the") - say(" draft depth, the CPU threads, the expert cache; on two or more cards also the prompt chunks). It takes") - say(" roughly 15-30 minutes (3 rounds of each value); the PC is busy meanwhile.") - try: - since = os.path.getsize(cfg["log"]) if cfg.get("log") and os.path.isfile(cfg["log"]) else 0 - except OSError: - since = 0 - try: - res = CAL.run(cfg, say=say) - except Exception as e: # never stops an install: the defaults stay - warn(f"the tuning did not finish ({e}): the default settings stay") - why = CAL.engine_error(cfg.get("log"), since) # #447: the engine's own reason, not only "see the log" - if why: - say(f" the engine said: {why}") - return False - cfg["args"] = CAL.apply(cfg["args"], res["settings"]) - if "env" in res: # HIP: the engine variables it measured (STRATA_SH_STREAM) - cfg["env"] = CAL.apply_env(cfg.get("env"), res["env"]) - write_config(cfg_path, cfg) - st = load_settings() - st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "env": res.get("env") or {}, - "tok_s": res["report"].get("tok_s"), - "date": time.strftime("%Y-%m-%d")} - save_settings(st) - chosen = {**res["settings"], **(res.get("env") or {})} - if chosen: - ok("tuned for this PC: " + ", ".join(f"{k} {v}" if k.startswith("--") else f"{k}={v}" for k, v in chosen.items()) - + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else "")) - else: - ok("tuned for this PC: the default settings are already the fastest here" - + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else "")) - return True - - -def saved_calibration(cfg: dict) -> dict | None: - """The settings an earlier calibration found for this PC and model, if any.""" - return (load_settings().get("calibration") or {}).get(hardware_key(cfg)) - - -def setup_calibration(cfg: dict, hip: bool) -> dict | None: - """The calibration a (re-)install applies to its new config: the one saved for this PC and model. #566: on Linux - HIP too - hardware_key now names the AMD cards, so a `./setup.sh --calibrate` run is matched to its card and - model. Windows HIP keeps the defaults for now (not tried there). Setup still offers the tuning itself on NVIDIA - only: each control is verified on HIP first.""" - if hip and WIN: - return None - return saved_calibration(cfg) - - -def upgrade_config(cfg_path: Path, cfg: dict) -> dict: - """Configs written before v0.1.13 read prompts in fixed 2048-token chunks; the engine now picks the chunk - itself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts). Under WSL, - KV streaming is dropped: its RAM copy must be pinned, and the driver pins only about 1 GB there.""" - a = cfg.get("args", []) - changed = False - ver = engine_version(cfg["exe"]) if "--prefill" in a else (0, 0, 0) - if "--prefill" in a and a[a.index("--prefill") + 1] == "2048" and ver >= (0, 1, 13): - a[a.index("--prefill") + 1] = "auto" - changed = True - ok("prompt reading: the engine now picks its chunk size (--prefill auto)") - elif "--prefill" in a and a[a.index("--prefill") + 1] == "auto" and (0, 0, 0) < ver < (0, 1, 13): - a[a.index("--prefill") + 1] = "2048" # an older engine kept after a failed update (issue #49) - changed = True - warn(f"the installed engine is {'.'.join(map(str, ver))}: prompts are read in 2048-token chunks until it is updated") - if is_wsl() and "--kv-resident" in a: - i = a.index("--kv-resident") - del a[i:i + 2] - changed = True - ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM") - if changed: - write_config(cfg_path, cfg) - return cfg - - -def update_install(have: list, a) -> int: - """#475: `setup.py --update` (UPDATE.bat / update.sh, after their git pull): what a plain START-HERE.bat does to - an install before it starts the model, without starting it - the Python packages, the ready-made engine when this - setup needs a newer one (MIN_ENGINE; a compiled engine when its source changed), each installed model's config - upgrades and its draft subset. No question is asked and the model files are not touched; a model still running - keeps its engine (update_installed_engine says to close it and run this again).""" - have = [p for p in have if model_config(p)] # #549: a strata-*.json that is no model config is skipped - if not have: - say(" No model is installed in this PolyStrata folder yet: run START-HERE.bat (Linux: ./setup.sh) to set it up -") - say(" it finds an earlier install's model files next to it and reuses them.") - return 0 - pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, - "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") - if not a.build: - update_installed_engine(a.prebuilt) - mtp_done: set = set() - for cfg_path in have: - cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) - if poly_config(cfg): - update_poly_engine(cfg, cfg_path=cfg_path) - poly_tail_skip(cfg, cfg_path) - poly_kv_whole(cfg, cfg_path) - if not own_path_config(cfg): - refresh_shared_draft_vocab(cfg, mtp_done) - if cfg.get("backend") == "hip" and WIN: - hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461 - ok(f"{cfg.get('model_name', cfg_path.stem)}: up to date") - ver = engine_version(Path(json.loads(have[0].read_text(encoding="utf-8-sig"))["exe"])) - say() - ok("PolyStrata is updated" + (f" (engine {'.'.join(map(str, ver))})" if any(ver) else "") + - ". Start the model with " + ("START-HERE.bat" if WIN else "./setup.sh") + " when you want it.") - return 0 - - -def settings_summary(cfg: dict, port=None) -> str: - """#564: the settings a start uses, in one line: the config's engine options (the model's file paths left out) - and the server's own fields, so a change made by hand to strata-.json can be checked without the log.""" - a, out, i = [str(x) for x in cfg.get("args") or []], [], 0 - while i < len(a): - flag = a[i] - val = a[i + 1] if i + 1 < len(a) and not a[i + 1].startswith("--") else None - i += 1 if val is None else 2 - if not flag.startswith("--"): - continue # a positional: the model file - if val is not None and ("/" in val or "\\" in val or val.lower().endswith((".gguf", ".bin"))): - continue # a path: --native, --mtp, --profile ... - out.append(flag if val is None else f"{flag} {val}") - srv = [f"{cfg.get('host', '127.0.0.1')}:{port or cfg.get('port', 8080)}"] - if cfg.get("api_key"): - srv.append("api key set") - if cfg.get("open_browser") is False: # #609 - srv.append("no browser") - for k in ("gpu", "layer_split", "draft_vocab", "fit_max_tokens", "reasoning_budget_tokens", "anthropic_thinking"): - if cfg.get(k) is not None: - v = cfg[k] - srv.append(f"{k} {','.join(map(str, v)) if isinstance(v, list) else str(v).lower() if isinstance(v, bool) else v}") - return " ".join(out) + ("; " if out else "") + "server " + ", ".join(srv) - - -def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False, - layer_split=None, keep=None) -> int: - """keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab, - --vram-reserve-mib).""" - cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) - missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] - if missing: - fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair") - glm = poly_config(cfg) # a model of strata-poly: its own engine (engine-poly/) - if glm: - if isinstance(gpu, list): # update_poly_engine() wants code for these cards - cfg["gpu"] = gpu - update_poly_engine(cfg, yes, cfg_path) - poly_tail_skip(cfg, cfg_path) - poly_kv_whole(cfg, cfg_path) - keep = {k: v for k, v in (keep or {}).items() if v is not None} - reserve = keep.pop("vram_reserve_mib", None) # #493: an engine argument, kept in the config's args - if reserve is not None: - args = cfg["args"] - if "--vram-reserve-mib" in args[:-1]: - args[args.index("--vram-reserve-mib") + 1] = str(reserve) - else: - args += ["--vram-reserve-mib", str(reserve)] - write_config(cfg_path, cfg) - ok(f"saved for this model: {reserve} MiB of VRAM kept free for other programs (--vram-reserve-mib)") - if keep and any(cfg.get(k) != v for k, v in keep.items()): # #179: a --host/--api-key on a start was ignored - cfg.update(keep) - write_config(cfg_path, cfg) - ok("saved for this model: " + ", ".join( - "api key" if k == "api_key" else ("the browser opens" if v else "no browser") if k == "open_browser" - else f"{k.replace('_', ' ')} {v}" for k, v in keep.items())) - cfg_path.touch() # the most recently used model - if "--mtp" in cfg["args"][:-1] and not own_path_config(cfg): - refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) - cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), - "--port", str(port or cfg.get("port", 8080))] - if cfg.get("backend") == "hip": # AMD, numbered as HIP numbers them (setup's KFD order) - if WIN: - hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461: also fixes a 0.1.34 install - amd = amd_gpus() - if isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on - cards = amd_parse_gpus(",".join(str(i) for i in gpu), amd) - built = (engine_archs_hip() or []) - miss = [x for x in cards if built and x["arch"] not in built] - if miss: - fail("the installed engine has no code for " + ", ".join(f"{x['name']} ({x['arch']})" for x in miss), - "set it up for these cards: ./setup.sh --setup --backend hip --gpus " + ",".join(map(str, gpu))) - cfg["gpu"], cfg["gpus_asked"] = gpu, True - cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" - split_budget(cfg, yes, True) # #498: before it is saved (asks when the RAM is short, #737) - write_config(cfg_path, cfg) - gpu = None - elif gpu is not None: - cmd += ["--gpu", str(gpu)] - found = [] - use = gpu if gpu is not None else cfg.get("gpu") - if isinstance(use, list): - byid = {x["index"]: x for x in amd} - ok("GPUs: " + " + ".join(gpu_name(byid[i]) if i in byid else f"GPU {i} (not found)" for i in use) - + f" together, AMD (layers split {cfg.get('layer_split') or 'auto'})") - else: - g = next((x for x in amd if x["index"] == (use if use is not None else x["index"]) - and amd_problem(x) is None), None) - if g is not None: - ok(f"GPU: {g['name']} ({g['vram_gb']:.0f} GB, AMD)") - else: - found = gpus() - global OLD_GPUS # Pascal / Volta: named on this start, or this model's CUDA 12 engine - OLD_GPUS = OLD_GPUS or old_gpus_opt_in(found, gpu if isinstance(gpu, list) else [gpu] if gpu is not None else - cfg.get("gpu") if isinstance(cfg.get("gpu"), list) else [cfg.get("gpu")], - 12 if config_toolkit(cfg) == 12 else None) - if cfg.get("backend") == "hip": - pass - elif isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on - check_gpus(gpu, found, yes=yes, named=True) - cfg["gpu"], cfg["gpus_asked"] = gpu, True - cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" - split_budget(cfg, yes, True) # #498: before it is saved (asks when the RAM is short, #737) - recommend_remote_expert_opt(cfg) - write_config(cfg_path, cfg) - gpu = None - elif gpu is not None: # --gpu N: this start only, on that card - check_gpus([gpu], found) - cmd += ["--gpu", str(gpu)] - elif not glm: - cfg = offer_together(cfg_path, cfg, yes) - use = gpu if gpu is not None else cfg.get("gpu") - # #364 #384: a resident low-RAM config on several GPUs; #498: a UD-Q4_K_XL config with its RAM budget (by hand) - if isinstance(use, list) and (split_mmap(cfg) | split_budget(cfg)): - write_config(cfg_path, cfg) - if cfg.get("backend") == "hip": - pass - elif isinstance(use, list): - check_gpus(use, found, "(chosen for this model) ", yes=True, named=True) - byid = {g["index"]: g for g in found} - if not glm: - cfg = ensure_engine_for([byid[i] for i in use], cfg_path, cfg, yes) - ok("GPUs: " + " + ".join(gpu_name(byid[i]) for i in use) + f" together (layers split {cfg.get('layer_split') or 'auto'})") - elif found: - g = next((x for x in found if x["index"] == use), None) if use is not None else max( - found, key=lambda x: (round(x["vram_gb"]), -x["index"])) - if g is not None: - if not glm: - cfg = ensure_engine_for([g], cfg_path, cfg, yes) - ok("GPU: " + gpu_name(g)) - browser = open_browser and cfg.get("open_browser") is not False # #609: "open_browser": false, --no-browser - if browser: - cmd.append("--open") - gb = 0.0 - for flag in ("--native", "--model"): - if flag in cfg["args"]: - try: - gb = Path(cfg["args"][cfg["args"].index(flag) + 1]).stat().st_size / 1e9 - except (OSError, IndexError): - pass - say() - say(" " + "-" * 100) - size = f'about {gb:.0f} GB' if gb >= 1 else '34-55 GB' - a_ = cfg["args"] - if glm: - say(f" Starting {cfg.get('model_name', 'the model')}: it reads the model file ({size}) in place: the weights " - "go to the GPU,") - say(" and the OS file cache keeps the experts the GPU does not hold.") - elif "--mmap-experts" in a_ and "--resident-budget-gib" not in a_ and "--resident-experts" not in a_: - # #505: the mapped low-RAM mode loads nothing into RAM up front (the server's narrator says the same) - say(f" Starting {cfg.get('model_name', 'the model')}: it maps {size} of experts from the model files (the OS " - "file cache reads them).") - else: - say(f" Starting {cfg.get('model_name', 'the model')}: it loads {size} into RAM and locks part of it for the " - "GPU.") - say(" While it does, YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES (longer the first time after a") - say(" restart). That is normal: please wait and don't close this window - " + ( - "the browser opens when it is ready." if browser else "the server says when it is ready.")) - say(" Later, closing this window stops the model.") - say(" " + "-" * 100) - for n, line in enumerate(textwrap.wrap(f"Settings ({cfg_path.name}): {settings_summary(cfg, port)}", 100, - break_on_hyphens=False)): # #564: what this start uses - say((" " if n == 0 else " ") + line) - if not WIN and os.environ.get("STRATA_EXECV"): - # Replace this process instead of spawning a child. The Docker image sets STRATA_EXECV=1, - # so there the server is PID 1 and docker stop's SIGTERM reaches the process that can - # answer the engine with QUIT. Normal Linux starts keep spawning the server as a child. - os.execv(cmd[0], cmd) - return subprocess.call(cmd) - - -# the draft subsets setup copied before (sha256): replaced by the current one, a subset made by hand is kept -OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens - - -DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin", "cyrillic": "draft_vocab_cyrillic.bin", - "fr": "draft_vocab_fr.bin"} - - -def saved_draft_vocab(cfg_path: Path) -> str | None: - """The draft subset a model's config chose earlier (--draft-vocab), or None: a setup run again without the flag - rewrites the config, and would otherwise put the default subset back.""" - try: - v = json.loads(cfg_path.read_text(encoding="utf-8-sig")).get("draft_vocab") - except (OSError, ValueError, AttributeError): - return None - return v if v in DRAFT_VOCABS else None - - -def vision_tokens(asked: int | None, vision: str, earlier: Path | None) -> int: - """#625: the most image tokens a picture becomes (the config's vision.max_tokens): --vision-tokens N, else what an - earlier config of this model chose for the same encoder device (a setup run again keeps it), else the device's - default (VISION). More is allowed with a note on the time it takes: setup recommends, it does not cap.""" - default = VISION[vision]["max_tokens"] - if asked is None and earlier is not None: - try: - v = json.loads(earlier.read_text(encoding="utf-8-sig")).get("vision") - except (OSError, ValueError, AttributeError): - v = None - mt = v.get("max_tokens") if isinstance(v, dict) and bool(v.get("gpu")) == (vision == "gpu") else None - if isinstance(mt, int) and mt > 0 and mt != default: - asked = mt - if asked is None: - return default - note = "" - if vision == "cpu" and asked > default: - note = (" - on the CPU a picture takes longer to encode the more tokens it gets (several seconds more at " - "1,024 than at 300)") - elif asked > VISION["gpu"]["max_tokens"]: - note = " - more than the encoder's default needs more VRAM and context per picture" - ok(f"images: up to {asked} image tokens per picture (--vision-tokens; default {default}){note}") - return asked - - -DRAFT_VOCAB_MIB = {"cjk": 348, "cyrillic": 193, "fr": 151, "en": 133} # the draft head's VRAM per subset (IQ3_S: the largest) -SMALL_DRAFT_VRAM_GB = 14 # #474: below this the default subset's head can be what does not fit - - -def draft_vocab_note(vram_gb: float, chosen: str | None) -> list[str]: - """#474: on a card under 14 GB, the default draft subset (cjk, ~348 MiB of VRAM) can be what does not fit at the - start ("the draft head does not fit"), and the engine's expert cache gets what a smaller one leaves. Setup - RECOMMENDS a smaller one here and changes nothing (the owner's rule, #403 #406): a subset chosen with - --draft-vocab, or kept from an earlier install, gets no note. [] for every other case.""" - if chosen or not 0 < vram_gb < SMALL_DRAFT_VRAM_GB: - return [] - start = "START-HERE.bat" if WIN else "./setup.sh" - return [f"Tip for a {vram_gb:.0f} GB card: the draft layer's default token subset (with Chinese, Japanese and " - f"Korean) needs up to ~{DRAFT_VOCAB_MIB['cjk']} MiB of VRAM.", - f" For English and code answers, {start} --draft-vocab en needs up to ~{DRAFT_VOCAB_MIB['en']} MiB " - f"(cyrillic: ~{DRAFT_VOCAB_MIB['cyrillic']}) and leaves the rest to the expert cache - and it is the", - " fix when the start stops with \"the draft head does not fit\". The model keeps the choice."] - - -SMALL_CARD_GB = 7.5 # #496: a card under 8 GB gets a tip (an 8 GB card lists 7.99) - - -def small_card_note(ctx: int, draft_vocab: str | None) -> list[str]: - """#496: what frees VRAM on a card under 8 GB when the start stops with "no VRAM is left for the expert cache" - (the engine already lowers its own reserve on such a card) - a recommendation, setup changes none of it. (The - draft layer stays: the server needs it.)""" - start = "START-HERE.bat --setup" if WIN else "./setup.sh" - tips = [] - if ctx > 8192: - tips.append("an 8K context (a smaller KV cache)") - if draft_vocab != "en": - tips.append(f"--draft-vocab en (a draft head of ~{DRAFT_VOCAB_MIB['en']} MiB instead of " - f"~{DRAFT_VOCAB_MIB[draft_vocab or 'cjk']})") - lines = ["If the start stops with \"no VRAM is left for the expert cache\" (the engine's log says how much is " - "short):"] - if tips: - lines.append(f" run {start} again with " + " and ".join(tips) + ", or close other programs that use the GPU.") - else: - lines.append(" close other programs that use the GPU.") - return lines - - -# 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 -# left for the expert cache. Measured on an 8 GB Arc A750 (the Intel worker, 2026-10-13): setup's 8192 / int8 / reserve 400 -# start stopped with "no VRAM is left for the expert cache, short 473 MiB"; --max-context 4608 --kv q4_0 --vram-reserve-mib 0 -# started with 3 cache slots (4.4 tok/s). UD_FIT_FIXED_MIB is that measurement turned into a constant (everything but the -# session's KV, the reserve and the draft layer); an ESTIMATE for CUDA and HIP cards of the same size, whose engine says what -# is short if it is off. The engine itself lowers its default reserve to 300 MiB on such a card. -UD_FIT_FIXED_MIB = 7356 -UD_FIT_MTP_MIB = 802 -UD_FIT_MIN_SLACK_MIB = 64 # at least a few cache slots beside the estimate's error -UD_FIT_CARD_GB = 9.5 # the check is for cards up to here -UD_FIT_RUNTIME_MIB = 250 # CUDA / HIP: the runtime's own context (the SYCL measurement above has none of it) -UD_FIT_ENGINE_RESERVE_MIB = 300 # the reserve the engine settles on when none is given and the card is tight -UD_FIT_KV_BYTES = {"fp16": 2112, "int8": 1056, "q4_0": 576, "k8v4": 816} # per token per attention layer (13) -UD_FIT_CTX_STEPS = (8192, 6144, 4608) - - -def unsloth_runtime_mib(gpu: dict) -> int: - return 0 if (gpu or {}).get("driver") in ("xe", "i915") else UD_FIT_RUNTIME_MIB - - -def unsloth_vram_slack_mib(vram_gb: float, ctx: int, kv: str, reserve_mib: int, mtp: bool = True, - runtime_mib: int = 0) -> float: - """MiB left for the expert cache by setup's estimate (negative: the engine would refuse to start).""" - session = ctx * 13 * UD_FIT_KV_BYTES.get(kv, 1056) / 2 ** 20 - return vram_gb * 1024 - UD_FIT_FIXED_MIB - (UD_FIT_MTP_MIB if mtp else 0) - session - max(reserve_mib, 0) - runtime_mib - - -def unsloth_small_card_plan(vram_gb: float, ctx: int, kv: str, reserve_mib: int | None, ctx_fixed=False, kv_fixed=False, - runtime_mib: int = 0): - """(ctx, kv, mtp, slack_mib) of the least harmful start that the estimate says fits, or None when none does. - Order of harm: the KV in 4 bits, then a smaller context (down to 4608), then no draft layer on the GPU (decode - up to 2x slower, but 0.8 GB for the cache); a value the user chose (--context, --kv) is not changed.""" - reserve = UD_FIT_ENGINE_RESERVE_MIB if reserve_mib is None else reserve_mib - ctxs = [ctx] if ctx_fixed else [ctx] + [c for c in UD_FIT_CTX_STEPS if c < ctx] - kvs = [kv] if kv_fixed or kv == "q4_0" else [kv, "q4_0"] - for mtp in (True, False): - for c in ctxs: - for k in kvs: - slack = unsloth_vram_slack_mib(vram_gb, c, k, reserve, mtp, runtime_mib) - if slack >= UD_FIT_MIN_SLACK_MIB: - return c, k, mtp, slack - return None - - -def unsloth_small_card_lines(model: str, vram_gb: float, plan, start_ok: bool) -> list[str]: - """The words for a ~8 GB card: that UD-* is very slow here and what to pick instead (always), and when the start - would have stopped, that and what setup changed instead. Recommend, never force.""" - 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 " - "cache gets a few slots, and nearly every expert comes from RAM or the SSD (3-5 tok/s measured on an 8 GB " - "Arc A750). IQ3_XXS or IQ3_S of the Qwen3.8-Flash-Next family fit such a card far better; run setup again " - "and pick one of them."] - if not start_ok and plan is None: - lines.append("By setup's estimate even a 4608 context with a 4-bit KV cache and no draft layer leaves no room " - "for the expert cache on this card: the start will probably stop with \"no VRAM is left for the " - "expert cache\".") - return lines - - -PARALLEL_MAX = 8 # #465: the engine's batch window holds at most 8 requests -PARALLEL_SHARE = 0.2 # #465: the slots' sessions may take this share of the VRAM the expert cache would hold -PARALLEL_HELD = 0.5 # #465: ... and only where the cache still holds this share of the experts beside them -PARALLEL_COST_NOTE = ("parallel N reduces waiting for several users but costs about 10-25% speed per request on this " - "card") - - -def parallel_slot_gb(ctx: int, kv: str, streaming: bool) -> float: - """#465: the VRAM one batch slot's session takes: its KV cache (12 QSA layers; with KV streaming only the 32K - positions the attention reads stay in VRAM) and the DeltaNet state (~0.17 GB). Measured: 0.56 GiB at 32K int8.""" - kv_tok = 12 * (576 if kv == "q4_0" else 1056) - return (min(ctx, 32768) if streaming else ctx) * kv_tok / 1e9 + 0.17 - - -def parallel_recommend(vram_gbs, arena_gb: float, ctx: int, kv: str, streaming: bool) -> int: - """#465: how many requests at once ("parallel") to recommend: 0 = none (one at a time). Only where the experts - mostly fit in VRAM - the expert cache (each card's VRAM less ~5 GB, every card of a layer split) still holds - PARALLEL_HELD of the model's experts beside the slots' sessions, which take at most PARALLEL_SHARE of it, up to 4. - Where the experts mostly run on the CPU a batch reads about as many experts as the requests one by one and every - 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 - slots, 4 requests together 63 tok/s against 71 one after the other (docs/BATCHING.md).""" - if isinstance(vram_gbs, (int, float)): - vram_gbs = [vram_gbs] - cache_gb = sum(max(0.0, v - 5) for v in vram_gbs) - slot = parallel_slot_gb(ctx, kv, streaming) - best = 0 - for n in (2, 3, 4): - if n * slot <= PARALLEL_SHARE * cache_gb and (cache_gb - n * slot) >= PARALLEL_HELD * arena_gb: - best = n - return best - - -def parallel_note(asked: int | None, vram_gbs, arena_gb: float, ctx: int, kv: str, streaming: bool) -> list[str]: - """#465: what setup says about "parallel": the recommendation (or, where it would cost speed, why it is left at - one), or how the asked count compares with it (kept as asked: recommend, never force).""" - rec = parallel_recommend(vram_gbs, arena_gb, ctx, kv, streaming) - slot = parallel_slot_gb(ctx, kv, streaming) - if asked is None or asked <= 1: - if not rec: - return [f"Several requests at once: left at one at a time - {PARALLEL_COST_NOTE} (docs/BATCHING.md)."] - return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together instead of one " - f"after the other (each takes ~{slot:.1f} GB of VRAM from the expert cache; docs/BATCHING.md)."] - lines = [f"parallel requests: {asked} at once (each takes ~{slot:.1f} GB of VRAM from the expert cache, " - f"{asked * slot:.1f} GB in all)"] - if asked > PARALLEL_MAX: - lines.append(f"the engine runs at most {PARALLEL_MAX} at once; it will use {PARALLEL_MAX}") - if not rec: - lines.append(f"recommended for this card: one at a time - {PARALLEL_COST_NOTE}; kept as you chose") - elif asked > rec: - lines.append(f"recommended for this card: {rec} - more slots leave fewer experts in VRAM, which can make every " - "request slower; kept as you chose") - return lines - - -PREFILL_BIG_RAM_GB = 96 # bench #433 #440 #834 #669: --prefill auto:32768 +21-35% at 96 GB, ~3x slower at 32 GB -PREFILL_RISK_RAM_GB = 64 # below this an explicit auto:32768 is warned about -HEADROOM_RAM_GB = 48 # bench #834: STRATA_RESIDENT_HEADROOM_GIB=6 on a PC with this much RAM or less -AGENT_CACHE_FREE_GB = 24 # bench #882 #440: RAM left beside the model for the conversation cache -AGENT_CACHE_MIB = 8192 -SMALL_VISION_VRAM_GB = 12.5 # bench #469: the GPU image encoder shrinks the prompt chunks on cards up to 12 GB - - -def arg_after(args, flag): - """The value after `flag` in an argument list, or None.""" - return args[args.index(flag) + 1] if flag in args[:-1] else None - - -def bench_tips(args, env, ram: float, model_ram_gb: float, vram_gb: float, vision: str, win: bool) -> list[str]: - """Recommendations from the community bench data (plan 0.1.40 item 14). Text only: nothing here changes a - default, the config or the engine's arguments (recommend, never force). `ram` is this PC's RAM, `model_ram_gb` - what the chosen model keeps in it.""" - tips = [] - cache = arg_after(args, "--expert-cache") - if win and cache is not None and cache != "auto": - tips.append(f"warning: --expert-cache {cache} is a fixed size. On Windows, a size that leaves almost no VRAM free " - "has run up to 7x slower (#780 #781); a smaller number, or auto, leaves the driver room") - prefill = arg_after(args, "--prefill") - if prefill == "auto:32768" and ram < PREFILL_RISK_RAM_GB: - tips.append(f"warning: --prefill auto:32768 on {ram:.0f} GB of RAM: it ran ~3x slower than --prefill auto with " - "32 GB (#834 #669); it paid off (+21-35%) with 96 GB") - elif prefill == "auto" and ram >= PREFILL_BIG_RAM_GB: - tips.append(f"tip: with {ram:.0f} GB of RAM, --prefill auto:32768 in the config's args read prompts 21-35% " - "faster in community benchmarks (#433 #440 #834); not set, nothing changes") - resident = any(a in args for a in ("--resident-experts", "--resident-budget-gib")) - if resident and ram <= HEADROOM_RAM_GB and "STRATA_RESIDENT_HEADROOM_GIB" not in (env or {}): - tips.append(f"tip: on a PC with {ram:.0f} GB of RAM, \"env\": {{\"STRATA_RESIDENT_HEADROOM_GIB\": \"6\"}} in the " - "config kept decode speed in a community benchmark and left the system 2 GiB more (#834); the " - "default is 4") - if "--conversation-cache-mib" not in args and ram - model_ram_gb >= AGENT_CACHE_FREE_GB: - tips.append(f"tip: for several agents or clients at once, --conversation-cache-mib {AGENT_CACHE_MIB} in the " - "config's args keeps each one's conversation; without it they were measured re-reading ~90% of " - "their prompts (#882 #440; docs/DETAILS.md, Multiple conversations)") - if vision == "gpu" and 0 < vram_gb <= SMALL_VISION_VRAM_GB: - tips.append("tip: the image encoder on the GPU makes a prompt's chunks smaller on a card this size (243 vs 750 " - "tok/s measured, #469); run setup again with --vision cpu to read prompts ~3x faster, at about " - "2-3 s per picture") - return tips - - -DISPLAY_RESERVE_MIB = 1500 # #779: the tip for an NVIDIA card that also drives a display -DESKTOP_RESERVE_MIB = 3072 # #560 #516: what kept a KDE/Wayland desktop alive beside a full expert cache - - -def linux_desktop(env=None) -> bool: - """A graphical session on Linux (Wayland or X).""" - env = os.environ if env is None else env - return sys.platform.startswith("linux") and bool(env.get("WAYLAND_DISPLAY") or env.get("DISPLAY")) - - -def desktop_reserve_note() -> list[str]: - """#560 #516: an AMD card that also drives a Linux desktop - with the default 700 MiB reserve the expert cache - fills it, and when the desktop needs more VRAM amdgpu moves the cache to system RAM, where the OOM killer then ends - the compositor. A recommendation, setup changes nothing.""" - return [f"If this AMD card also drives your desktop and the desktop or apps crash once the model is loaded, keep " - f"more VRAM free: ./setup.sh --vram-reserve-mib {DESKTOP_RESERVE_MIB}", - " (remembered for this model; the expert cache gets ~2.3 GB less, a few % of speed)"] - - -def mtp_corrupt(mtp: Path, env=None) -> bool: - """#327: True when the MTP tensors an install fetched are not the pinned checkpoint's (tools/mtp_fetch.py verify, - which hashes only files that changed since they last checked out). A mirror that ignored range requests left the - shards' starts there instead, and the draft layer built from them accepted nothing - with no error anywhere.""" - if not (mtp / "tensors").is_dir(): - return False - r = subprocess.run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "verify", "--out", str(mtp)], env=env, - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) - return r.returncode == 3 - - -def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: - """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137), `en` - (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster) or - `cyrillic` (data/draft_vocab_cyrillic.bin: English/code and the whole Cyrillic script, for Ukrainian, Russian, - Bulgarian, Serbian... answers) or `fr` (data/draft_vocab_fr.bin: English/code and the tokens of French text, #597). - Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept.""" - new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin" - if not new.exists() or not rt.is_dir(): - return - if dst.exists(): - old = hashlib.sha256(dst.read_bytes()).hexdigest() - shipped = OLD_DRAFT_VOCABS | {hashlib.sha256((ROOT / "data" / f).read_bytes()).hexdigest() - for f in DRAFT_VOCABS.values() if (ROOT / "data" / f).exists()} - if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest(): - return - ok("draft layer: the token subset " + {"cjk": "with Chinese, Japanese and Korean", - "cyrillic": "with the Cyrillic script", - "fr": "for French"}.get(choice, - "for English and code (less VRAM)")) - shutil.copyfile(new, dst) - - -def refresh_shared_draft_vocab(cfg: dict, done: set) -> None: - """update_install's draft subset of one config, for configs taken most recently used first (installed_configs' - order): an MTP folder already in `done` is left alone. Several configs can name one MTP folder (a second config of - the same model: another GPU mode, another context), each with its own "draft_vocab". Refreshed once per config, - the folder ended with the subset of the config used LONGEST ago: a config without the key (cjk) put the default - subset over the cyrillic one of the config in use, and its Russian answers were drafted without Cyrillic tokens. - The folder takes the subset of the most recently used config that names it; a start still installs its own - config's.""" - args = cfg.get("args") or [] - if "--mtp" not in args[:-1]: - return - rt = Path(args[args.index("--mtp") + 1]) - key = os.path.normcase(os.path.abspath(rt)) - if key in done: - return - done.add(key) - refresh_draft_vocab(rt, cfg.get("draft_vocab", "cjk")) - - -def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: - """The installed engine must have code for every card the model starts on: a card added later (--gpus with an - older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a - card gets the engine compiled for all of them, before the start. A Pascal / Volta card added to a model on the - CUDA 13 engine moves the model to the experimental CUDA 12 engine (CUDA 13 has no code for it).""" - tk = config_toolkit(cfg) - if tk == 13 and any(int(g["arch"]) < CUDA13_MIN_ARCH for g in cards): - return use_cuda12(cards, cfg_path, cfg, yes) - missing = [g for g in cards if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))] - if not missing: - return cfg - eng = engine_dir(tk) - info = eng / "BUILD.json" - meta = json.loads(info.read_text(encoding="utf-8")) - say() - say(" The installed engine has no code for " + ", ".join(f"{g['name']} (sm_{g['arch']})" for g in missing) + - ": it is compiled for " + ("these cards" if len(cards) > 1 else "it") + " now.") - main = gpu_info(cards[0]["index"]) - archs = sorted({int(x) for x in meta.get("archs", [])} | {int(g["arch"]) for g in cards}) - vision = meta.get("vision") or ("gpu" if (eng / VEXE).exists() else "none") - build_engine({**main, "archs": archs}, vision, yes, get_llama_cpp(), toolkit=tk) - dirs = json.loads(info.read_text(encoding="utf-8")).get("cuda_dirs") or [] - cfg["lib_dirs"] = dirs + [d for d in cfg.get("lib_dirs") or [] if d not in dirs] - write_config(cfg_path, cfg) - return cfg - - -def get_cuda12_engine(url_base, gpu, vision, yes, build=False) -> Path: - """The experimental CUDA 12 engine for these cards (gpu["archs"]): the ready-made one (Windows) with NVIDIA's - CUDA 12 libraries, or compiled here with a CUDA 12.x toolkit (Linux, --build, or no ready-made one).""" - eng = None if build else get_prebuilt(url_base, gpu, vision, toolkit=12) - if eng is not None and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local": - pip_cuda_libs(12) - if vision != "none" and not (eng / VEXE).exists(): - eng = None - return eng if eng is not None else build_engine(gpu, vision, yes, get_llama_cpp(), toolkit=12) - - -def engine_lib_dirs(eng: Path, toolkit=13) -> list: - """The library folders a CUDA engine loads from: its own (a compiled one: the toolkit's), else pip's wheels.""" - meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) - return meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(toolkit) - - -def use_cuda12(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: - """A model on the CUDA 13 engine now has a Pascal / Volta card (a --gpus at start): the model's config moves to - the experimental CUDA 12 engine (one engine per model; its other models keep theirs).""" - old = min(int(g["arch"]) for g in cards) - say() - warn(f"sm_{old} is older than CUDA 13 supports (it dropped Pascal and Volta): this model moves to the experimental " - "CUDA 12 engine (docs/OLDER_GPUS.md; START-HERE.bat --setup --cuda 13 and newer cards only moves it back)") - main = gpu_info(cards[0]["index"]) or cards[0] - vision = "gpu" if cfg.get("vision") else "none" - eng = get_cuda12_engine(os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL), - {**main, "archs": sorted({int(g["arch"]) for g in cards})}, vision, yes) - cfg["exe"] = str(eng / EXE) - cfg["cuda"] = 12 - cfg["lib_dirs"] = engine_lib_dirs(eng, 12) - if cfg.get("vision") and (eng / VEXE).exists(): - cfg["vision"]["exe"] = str(eng / VEXE) - write_config(cfg_path, cfg) - ok(f"engine: {eng / EXE} (CUDA 12, experimental)") - return cfg - - -def write_run_script(model, cfg_path, port, open_browser=True): - """run-.bat / .sh: the server with this config; `open_browser` False (#609: --no-browser) leaves --open out.""" - serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), - "--port", str(port)] + (["--open"] if open_browser else []) - if WIN: - script = ROOT / f"run-{model.lower()}.bat" - script.write_text("@echo off\r\ntitle PolyStrata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" + - " ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8") - else: - script = ROOT / f"run-{model.lower()}.sh" - script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n", - encoding="utf-8") - script.chmod(0o755) - return script - - -# ------------------------------------------------------------------------------------------------ the rope config -def derived_factor(ctx: int, trained: int = 262144) -> float: - """The automatic extension factor: the FINAL context over the trained one, at least 1. - - Factor 1 removes the automatic expansion - the trained angles stand as they are - but it is not a - switch for rope as a whole: an explicitly chosen method's settings keep their defined behavior. - """ - return max(1.0, float(ctx) / float(trained)) - - -def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): - """The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. - - An explicit --rope-scaling/--rope-scale always wins - a user-supplied factor is kept verbatim even - when a reduction changed the context. Past the trained range an omitted method defaults to yarn - - llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the - magnitude correction keeps the attention temperature - and an omitted factor is derived from the - final context (final / trained, at least 1), as is an explicitly chosen method's missing factor - inside the trained range: factor 1, the trained angles, no expansion. An explicit none is refused - past the trained range (the setup will not configure a run it knows is out of spec) rather than - silently overridden. - """ - if ctx <= trained: - if scale is not None and scaling in (None, "none"): - raise ValueError("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the " - "trained 262144, so there is nothing to scale)") - if scaling in (None, "none"): - return None, None # the stock model, by choice or by default - return scaling, scale if scale is not None else derived_factor(ctx, trained) - if scaling == "none": - raise ValueError(f"a {ctx // 1024}K context is past the model's trained 262144, and --rope-scaling none " - "keeps the stock angles there - the model has never seen those positions, so the setup " - "refuses the combination instead of quietly overriding it. Pick --rope-scaling yarn or " - "linear, or rerun with --context 262144 or lower") - return scaling or "yarn", scale if scale is not None else derived_factor(ctx, trained) - - -# ------------------------------------------------------------------------------------------------ GLM 5.3 Flash -def poly_config(cfg: dict) -> bool: - """A run config of strata-poly, under this name or the one it had.""" - return Path(str(cfg.get("exe", ""))).name in (POLY_EXE, OLD_POLY_EXE) - - -# The estimates below take a size's entry: what MODELS, or a family's own "models", says of it (family_models()). -def poly_beside_gb(d) -> float: - """The GiB of VRAM a size takes before any expert, at a 32K context.""" - return d.get("vram_beside_gb", GLM_VRAM_BESIDE_GB) - - -def poly_held_gb(d, vram_gb) -> float: - """About the GB of a size's experts a card with this much VRAM (GiB) holds at a 32K context.""" - return min(d["arena_gb"], max(0.0, vram_gb - poly_beside_gb(d)) * 1.073741824) - - -def poly_parallel_note(asked: int | None, d, vram_gb) -> list[str]: - """What setup says of "parallel" for a strata-poly size: answers written together pay where the card holds every - expert of the size. Where most of them run on the CPU, different requests route to different experts and the - CPU does each one's: on the 8 GB laptop three Qwen3.6 UD-Q3_K_M chats at once wrote 105 tokens/s together and - 79 one after the other, so there "parallel" gains less than it does on a large card.""" - whole = poly_held_gb(d, vram_gb) >= d["arena_gb"] - turns = ("on this card most experts run on the CPU and do each request's own, so requests at once gain less: on " - "an 8 GB laptop three chats at once wrote about a third faster than one after the other (docs/BATCHING.md)") - if asked is None or asked <= 1: - if whole: - return ["Several requests at once (opt-in): --parallel 2 to 4 writes their answers together, each in a " - "slot whose attention rows take VRAM from the expert cache as its conversation grows " - "(docs/BATCHING.md)."] - return [f"Several requests at once (opt-in, --parallel N): {turns}."] - lines = [f"parallel requests: {asked} at once (each slot's attention rows take VRAM from the expert cache as its " - "conversation grows)"] - if asked > PARALLEL_MAX: - lines.append(f"the engine runs at most {PARALLEL_MAX} at once; it will use {PARALLEL_MAX}") - if not whole: - lines.append(turns) - return lines - - -def poly_batch(fam, d, vram_gb, ctx) -> bool: - """Whether setup's config reads a prompt 2,048 tokens at a time instead of the engine's 1,024: on a card that holds - every expert of a size beside the larger batch and the context's rows past 32K, with a GiB to spare, llama.cpp's - matrix kernels get twice the rows of each expert and a long prompt is read 14% (Qwen3.6) to 30% (LFM2.5) faster; - on a smaller card the experts outside VRAM are copied to it half as often. A family without "batch_gb" keeps - 1,024, one with "batch_from_gb" takes 2,048 on any card from that size on.""" - if fam.get("batch_from_gb") and vram_gb >= fam["batch_from_gb"]: - return True - if not fam.get("batch_gb"): - return False - rows = max(0, ctx - 32768) * fam.get("row_bytes", GLM_ROW_BYTES) / 2**30 - return d["arena_gb"] <= poly_held_gb(d, vram_gb - fam["batch_gb"] - rows - 1) - - -def poly_default(sizes, ram, vram_gb) -> str: - """The size setup takes when none is named: the first whose RAM estimate this PC meets, else the one that wants - the least.""" - return next((m for m, d in sizes.items() if ram >= poly_ram_need(d, vram_gb) - 4), - min(sizes, key=lambda m: poly_ram_need(sizes[m], vram_gb))) - - -def poly_ram_need(d, vram_gb) -> float: - """About the GB of RAM a size wants on that card: the experts the card does not hold, in the OS file cache, - and room for the rest. An estimate from one machine (32 GB of VRAM, 120 GB of RAM).""" - return d["arena_gb"] - poly_held_gb(d, vram_gb) + POLY_RAM_BESIDE_GB - - -def poly_fits(d, ram, vram_gb, hip) -> bool: - """Whether a size of strata-poly's models runs on this PC with its experts in RAM, by setup's estimate.""" - return not (hip and WIN) and vram_gb >= poly_beside_gb(d) + 2 and ram >= poly_ram_need(d, vram_gb) - 4 - - -def poly_verdict(d, ram, vram_gb, hip, windows=False) -> str: - """--check's line for a size of strata-poly's models. `windows`: its family has run there (FAMILIES).""" - if hip and WIN: - return "does not run on AMD cards on Windows yet (its HIP engine is compiled on Linux)" - if vram_gb < poly_beside_gb(d) + 2: - return f"does not fit: it takes about {poly_beside_gb(d)} GB of VRAM before any expert" - need = poly_ram_need(d, vram_gb) - return "EXPERIMENTAL, " + ("not tried on Windows, " if WIN and not windows else "") + ( - f"fits by setup's estimate (~{need:.0f} GB of RAM on this card)" if poly_fits(d, ram, vram_gb, hip) else - f"wants ~{need:.0f} GB of RAM on this card: with {ram:.0f} its experts are read from the SSD") - - -def poly_saved_conv(paths) -> int | None: - """--conversation-cache-mib of an earlier run config of this model (the first of `paths` there is), 0 when that - config has none; None without an earlier config: setup then asks.""" - for p in paths: - if p is None or not p.is_file(): - continue - try: - args = json.loads(p.read_text(encoding="utf-8-sig")).get("args") - except (OSError, ValueError, AttributeError): - continue - if isinstance(args, list): - v = str(args[args.index("--conversation-cache-mib") + 1]) if "--conversation-cache-mib" in args[:-1] else "" - return int(v) if v.isdigit() else 0 - return None - - -def poly_asset() -> str: - """The ready-made strata-poly's asset for this checkout: the engine and the image encoder are both in it.""" - return POLY_ASSET.format(src=source_hash(ENGINE_SOURCES + VISION_SOURCES)) - - -def get_poly_prebuilt(gpu) -> bool: - """The ready-made strata-poly and image encoder of this checkout's source in engine-poly/, with NVIDIA's CUDA 13 - libraries from pip. False when the release has none for this source or this GPU, off Windows, with a driver - older than CUDA 13's or a CPU without AVX2. An engine already there for this source and GPU is kept, ready-made - or compiled, unless it was compiled with CUDA 12.""" - eng = ROOT / ENGINE_POLY_DIR - stamp = eng / "BUILD.json" - meta = json.loads(stamp.read_text()) if stamp.exists() else {} - src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) - cards = {int(x) for x in gpu.get("archs", [gpu["arch"]])} - # a ready-made one came with its encoder, which is out of date when tools/vision changed - if meta.get("src") == src and (eng / POLY_EXE).exists() and cards <= {int(x) for x in meta.get("archs", [])} \ - and (meta.get("source") != "release" or meta.get("vision_src") == vsrc) and meta.get("toolkit", 13) == 13: - return True - if not WIN or not POLY_PREBUILT_URL or driver_major(gpu) < MIN_DRIVER or cpu_floor(cpu_info()[1]): - return False - base = POLY_PREBUILT_URL if POLY_PREBUILT_URL.endswith(("/", "\\")) else POLY_PREBUILT_URL + "/" - asset = poly_asset() - try: # a checkout after the release has a source it was not built from - if is_local(base): - if not Path(base[7:] if base.lower().startswith("file://") else base, asset).exists(): - raise FileNotFoundError(f"no {asset} in {base}") - else: - req = urllib.request.Request(base + asset, method="HEAD", headers={"User-Agent": "strata-setup"}) - urllib.request.urlopen(req, timeout=60).close() - except OSError as e: - say(f" No ready-made strata-poly for this checkout ({e})") - return False - eng.mkdir(exist_ok=True) - z = eng / asset - say(" Downloading the ready-made strata-poly engine ...") - download(base + asset, z, "strata-poly engine") - try: - verify_engine_archive(z, asset, base) - except UnverifiedEngine as e: - warn(f"the ready-made strata-poly is not installed ({e})") - return False - tmp = eng / "_unpack" - shutil.rmtree(tmp, ignore_errors=True) - try: - with zipfile.ZipFile(z) as f: - f.extractall(tmp) - finally: - drop_archive(z) - new = json.loads((tmp / "BUILD.json").read_text(encoding="utf-8")) - archs = {int(x) for x in new.get("archs", [])} - if (new.get("src"), new.get("vision_src")) != (src, vsrc) or not cards <= archs: - warn(f"the ready-made strata-poly is built for {', '.join(f'sm_{x}' for x in sorted(archs))}, not for " - f"{', '.join(f'sm_{x}' for x in sorted(cards - archs)) or 'this source'}") - shutil.rmtree(tmp, ignore_errors=True) - return False - pip_cuda_libs(13) # before the engine there is replaced, should pip fail - for p in tmp.iterdir(): - p.replace(eng / p.name) - shutil.rmtree(tmp, ignore_errors=True) - ok(f"ready-made strata-poly for {', '.join(f'sm_{x}' for x in sorted(archs))} (CUDA {new.get('cuda', '?')})") - return True - - -def build_engine_poly(gpu, yes, llama, vision="none", toolkit=13) -> Path: - """Compile strata-poly for this GPU and, for images, the encoder beside it ("gpu": with CUDA, "cpu": without); - the results go to engine-poly/. Each is compiled again when its source changed (a `git pull`); the engine also - when the card is one it has no code for, and the encoder when it is wanted on the GPU and was built without. - toolkit 12 (--cuda 12): with a CUDA 12.x toolkit, for a driver older than CUDA 13's or a Pascal / Volta card; - both are compiled again when the ones there were built with the other toolkit.""" - eng = ROOT / ENGINE_POLY_DIR - eng.mkdir(exist_ok=True) - stamp = eng / "BUILD.json" - meta = json.loads(stamp.read_text()) if stamp.exists() else {} - src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) - cards = {int(x) for x in gpu.get("archs", [gpu["arch"]])} - built = {int(x) for x in meta.get("archs", [])} - same = int(meta.get("toolkit", 13)) == toolkit - # one compiled here keeps the cards it was built for; one in place of a ready-made engine is for these cards - release = meta.get("source") == "release" - archs = sorted(cards if release or not same else built | cards) - have = (eng / POLY_EXE).exists() - engine_ok = have and same and meta.get("src") == src and (cards <= built if release else set(archs) == built) - # an encoder built with CUDA also runs on the CPU, so the one there is kept unless the GPU is asked of a CPU one - was = meta.get("vision") or "none" - vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc and - (was == "gpu" and same or was == "cpu" and vision == "cpu")) - if engine_ok and vision_ok: - ok(f"strata-poly already {'downloaded' if release else 'built'} for this PC") - return eng - # CUDA 12.8 is the toolkit it was written and measured with, on an RTX 5090: the Qwen engine's reason to want 13.0 - # there (#220, its prompt path) is not this engine's - nvcc, vcvars = install_build_tools({**gpu, "archs": archs, "toolkit": toolkit, - "need_cuda": (12, 8) if max(archs) >= 120 else (12, 0)}, yes) - cuda_archs = ";".join(str(x) for x in archs) - if not engine_ok: - say(" strata-poly's source changed: compiling it again (only what changed, a few minutes) ..." - if have and same and set(archs) == built else - " Compiling the strata-poly engine for your GPU (some minutes, once) ...") - # a folder per toolkit: CMake does not take another compiler into a folder configured with one - bdir = ROOT / ("build-poly" if toolkit == 13 else "build-poly-cuda12") - defs = ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", - f"-DCMAKE_CUDA_COMPILER={nvcc}", f"-DSTRATA_GGML_DIR={llama}"] - if min(archs) < CUDA13_MIN_ARCH: - defs.append("-DSTRATA_EXPERIMENTAL_SM60=ON") - cmake_build(ROOT, bdir, "strata-poly", defs, vcvars, "build-strata-poly.bat") - shutil.copy2(bdir / POLY_EXE, eng / POLY_EXE) - if not vision_ok: - say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ...")) - defs = [f"-DLLAMA_DIR={get_llama_cpp(vision=True)}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}"] - if vision == "gpu": - defs += [f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", f"-DCMAKE_CUDA_COMPILER={nvcc}"] - # its own build folder: the Qwen engine's encoder may be built for another toolkit in build-vision/ - vdir = ROOT / ("build-vision-poly" if toolkit == 13 else "build-vision-poly-cuda12") - cmake_build(ROOT / "tools" / "vision", vdir, "strata-vision", defs, vcvars, "build-vision-poly.bat") - shutil.copy2(vdir / "bin" / VEXE, eng / VEXE) - was, meta = vision, {**meta, "vision_src": vsrc} - bindir = Path(nvcc).parent # the toolkit's own libraries (bin, bin/x64, lib64) - dirs = [str(x) for x in (bindir, bindir / "x64", bindir.parent / "lib64") if x.is_dir()] - if toolkit == 13: # pip's, for a ready-made encoder kept beside it - dirs += [d for d in cuda_lib_dirs(13) if d not in dirs] - stamp.write_text(json.dumps({"source": "local", "version": source_version(), "archs": archs, "cuda_dirs": dirs, - "toolkit": toolkit, "src": src, "vision": was, "vision_src": meta.get("vision_src")}, - indent=1)) - ok(f"strata-poly compiled: {eng / POLY_EXE}" + (f", image encoder: {eng / VEXE}" if vision != "none" else "")) - return eng - - -def build_engine_poly_hip(gpu, llama) -> Path: - """Compile strata-poly for this AMD GPU into engine-poly/ (again only when its source changed: a `git pull`). - ROCm comes from rocm_root: a system ROCm 7 or AMD's TheRock wheels in .venv, as for the main engine's HIP - build. There is no ready-made AMD engine and no HIP image encoder: images stay off.""" - eng = ROOT / ENGINE_POLY_DIR - eng.mkdir(exist_ok=True) - stamp = eng / "BUILD.json" - meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {} - src = source_hash(ENGINE_SOURCES) - archs = sorted(set(gpu.get("archs") or [gpu["arch"]])) - engine_ok = meta.get("backend") == "hip" and (eng / POLY_EXE).exists() and meta.get("src") == src and \ - set(archs) <= set(meta.get("archs", [])) - if engine_ok: - ok("strata-poly already built for this PC") - return eng - if not (shutil.which("c++") or shutil.which("g++")) or not shutil.which("git"): - fail("a C++ compiler and git are needed to compile the AMD strata-poly", - "Ubuntu/Debian: sudo apt install build-essential git Fedora: sudo dnf install gcc-c++ git") - root, dirs = rocm_root(archs) - libs = [str(Path(d).parent) for d in dirs[1:]] - bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()), - root / "amdgcn" / "bitcode") - os.environ.update({"HIP_PLATFORM": "amd", "HIP_COMPILER": "clang", "HIP_RUNTIME": "rocclr", "ROCM_PATH": str(root), - "HIP_PATH": str(root)}) - os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) - os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(root / "llvm" / "bin"), os.environ.get("PATH", "")]) - say(" strata-poly's source changed: compiling it again (only what changed, a few minutes) ..." - if meta.get("backend") == "hip" and (eng / POLY_EXE).exists() - else f" Compiling the strata-poly engine for your AMD GPU ({', '.join(archs)}; some minutes, once) ...") - cmake_build(ROOT, ROOT / "build-poly-hip", "strata-poly", - ["-DSTRATA_ENABLE_HIP=ON", "-DSTRATA_ENABLE_CUDA=OFF", "-DSTRATA_BUILD_TESTS=OFF", - "-DCMAKE_HIP_ARCHITECTURES=" + ";".join(archs), - f"-DCMAKE_HIP_COMPILER={root / 'llvm' / 'bin' / 'clang++'}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", - "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), - f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}", - f"-DSTRATA_GGML_DIR={llama}"], None, "") - shutil.copy2(ROOT / "build-poly-hip" / POLY_EXE, eng / POLY_EXE) - stamp.write_text(json.dumps({"source": "local-hip", "backend": "hip", "version": source_version(), - "archs": archs, "vision": "none", "lib_dirs": dirs, "src": src}, indent=1)) - ok(f"strata-poly compiled: {eng / POLY_EXE}") - return eng - - -def update_poly_engine(cfg: dict, yes=False, cfg_path: Path | None = None) -> None: - """Before a model of strata-poly starts: the engine setup installed is replaced when its source changed (a `git - pull`) or the card is another generation, a ready-made one by the release's for the new source, one compiled here - by a compile. A ready-made one stays while no release has the new source: a compile would first install the - build tools. A failure must not stop the start: the installed one runs. An install from before the engine was - renamed has the old engine in its config: the engine is compiled under its new name and, with cfg_path, the - config is moved to it.""" - eng = Path(cfg["exe"]).parent - renamed = eng == ROOT / OLD_ENGINE_POLY_DIR and Path(cfg["exe"]).name == OLD_POLY_EXE - if renamed: - eng = ROOT / ENGINE_POLY_DIR - stamp = eng / "BUILD.json" - if eng != ROOT / ENGINE_POLY_DIR or not (stamp.exists() or renamed): # an engine of the user's own - return - try: - meta = json.loads(stamp.read_text()) if stamp.exists() else {} - if meta.get("backend") == "hip": # the AMD engine compiled here: the same way again when the source moved - if not (meta.get("src") == source_hash(ENGINE_SOURCES) and (eng / POLY_EXE).exists()): - build_engine_poly_hip({"arch": (meta.get("archs") or [""])[0], "archs": meta.get("archs")}, - get_llama_cpp()) - cfg["lib_dirs"] = engine_lib_dirs(eng) - if renamed: - cfg["exe"] = str(eng / POLY_EXE) - if cfg_path is not None: - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") - return - picks = cfg["gpu"] if isinstance(cfg.get("gpu"), list) else [cfg["gpu"] if isinstance(cfg.get("gpu"), int) else None] - gpu = gpu_info(picks[0]) - if gpu is None: - raise RuntimeError("no NVIDIA GPU found") - gpu["archs"] = sorted({int(gpu_info(i)["arch"]) for i in picks}) # a layer split's cards - # the encoder too, when this model has one: on the device it was built for - vis = cfg.get("vision") - vision = ("gpu" if meta.get("vision") == "gpu" or vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none" - changed = renamed - fits = set(gpu["archs"]) <= {int(x) for x in meta.get("archs", [])} - if not (meta.get("src") == source_hash(ENGINE_SOURCES) and (eng / POLY_EXE).exists() and fits - and (vision == "none" or meta.get("vision_src") == source_hash(VISION_SOURCES))): - # one compiled here (--build, a CPU without AVX2) stays so - if meta.get("source") == "release" and not get_poly_prebuilt(gpu) and fits: - warn("the latest release has no ready-made strata-poly of this source: the one installed starts " - "(START-HERE.bat --setup --build compiles this source)") - return - build_engine_poly(gpu, yes, get_llama_cpp(), vision, int(meta.get("toolkit", 13))) - # a ready-made engine loads CUDA from pip, one compiled here from the toolkit it was compiled with - cfg["lib_dirs"], changed = engine_lib_dirs(eng), True - if changed: - cfg["exe"] = str(eng / POLY_EXE) - if cfg_path is not None: - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") - if renamed: - ok(f"this install's engine is {POLY_EXE} now (it was {OLD_POLY_EXE}); {OLD_ENGINE_POLY_DIR}/ can be deleted") - except (Exception, SystemExit) as e: - warn(f"could not update strata-poly{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the installed one") - - -def poly_tail_skip(cfg: dict, cfg_path: Path | None = None) -> None: - """A config written before its family got "tail_skip" gets the option, once the installed engine knows it (0.1.42). - A config that has --tail-skip, with any value, keeps it.""" - a = cfg["args"] - fam = next((f for f in FAMILIES.values() if f.get("tail_skip") - and str(cfg.get("model_name", "")).startswith(f["name"] + "-")), None) - if fam is None or "--tail-skip" in a or engine_version(Path(cfg["exe"])) < (0, 1, 42): - return - a += ["--tail-skip", str(fam["tail_skip"])] - ok(f"{fam['title']}: --tail-skip {fam['tail_skip']}, a few experts outside VRAM are left out (faster on a small " - "card, the answers move a little; STRATA_ROUTE_TAIL_SKIP=0 turns it off)") - if cfg_path is not None: - write_config(cfg_path, cfg) - - -def poly_kv_whole(cfg: dict, cfg_path: Path | None = None) -> None: - """A config of strata-poly on an AMD card gets --kv-whole: ROCm keeps the VRAM that cuMemUnmap() and - cuMemRelease() gave back (issue #13), so the attention caches take theirs at load instead of as the - conversation grows, where the expert cache's VRAM would be lost to them. A config that has it keeps it.""" - a = cfg["args"] - try: - meta = json.loads((Path(cfg["exe"]).parent / "BUILD.json").read_text(encoding="utf-8")) - except (OSError, ValueError): - return - if meta.get("backend") != "hip" or "--kv-whole" in a: - return - a.append("--kv-whole") - ok("AMD card: --kv-whole, the attention caches take their VRAM at load (ROCm keeps what the expert cache gives " - "back, so a long prompt was refused VRAM later)") - if cfg_path is not None: - write_config(cfg_path, cfg) - - -def poly_setup(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, port, adopted) -> int: - """Steps 2 to 7 for a model of strata-poly (docs/GLM.md, docs/BACKENDS.md): its questions, the Python - packages, the engine (ready-made or compiled here), the model file, its tokenizer and expert profile, the run - config and the start script.""" - fam = FAMILIES[family] - title = fam["title"] - if hip and WIN: - fail(f"{title} has no AMD engine for Windows: its HIP engine is compiled on Linux", - "choose another model for this card, or run setup on Linux") - if hip and family in ("glm", "deepseek", "lfm25", "gemma4", "tiel"): # the engine runs on AMD, these models not yet - warn(f"{title} on the AMD card has not been tried: the engine runs there, this model was not") - if cuda_tk == 12: - warn(f"{title}'s engine with CUDA 12 is compiled here (the ready-made one is CUDA 13)" + - (": on Pascal / Volta it is untested" if int(gpu["arch"]) < CUDA13_MIN_ARCH else "")) - if WIN and not fam.get("windows"): - confirm_risk(f"{title} has been run on Linux only: its engine compiles on Windows, the model was not tried " - "there", bool(a.family), a.yes, f"{title} has not been tried on Windows", - f"use Linux, or --family {family} --yes to try it here") - sees = fam.get("vision") is True - if sees and hip: # the image encoder is a CUDA program: no HIP build of it yet (as for the main engine) - say(" Images: the image encoder is a CUDA program: on the AMD card images are off (text answers).") - sees = False - unused = [flag for flag, given in ( - ("--vision", not sees and a.vision not in (None, "no", "none")), - ("--vision-tokens", not sees and a.vision_tokens is not None), - ("--kv", a.kv), ("--kv-streaming", a.kv_streaming != "auto"), ("--rope-scaling", a.rope_scaling), - ("--rope-scale", a.rope_scale is not None), ("--low-ram", a.low_ram != "auto"), - ("--resident-budget-gib", a.resident_budget_gib is not None), - ("--draft-vocab", a.draft_vocab), ("--layer-split", a.layer_split and not multi), ("--calibrate", a.calibrate), - ("--experimental-speed-projection", - (a.experimental_speed_projection or "off").strip().lower() not in ("off", "no", "n", "0"))) if given] - if unused: - warn(f"not used with {title} (its engine has no such setting): " + ", ".join(unused)) - - sizes = family_models(family) - names = list(sizes) - if a.model and a.model not in names: - fail(f"{title} has no {a.model} model file", "choose one of: " + ", ".join(names)) - vram = gpu["vram_gb"] - if multi: # each card has its layers' dense weights; its own scratch and staging buffer cost ~2 GB a card more - vram = sum(gpu_info(i)["vram_gb"] for i in multi) - 2.0 * (len(multi) - 1) - model = a.model or poly_default(sizes, ram, vram) - if not a.model and len(names) > 1: - say() - say(" Which size? The RAM is setup's estimate for this card: the experts it does not hold stay in RAM.") - for i, m in enumerate(names, 1): - say(f" {i}) {m:14s} {sizes[m]['about']}; download {sizes[m]['download_gb']:.0f} GB, " - f"~{poly_ram_need(sizes[m], vram):.0f} GB of RAM") - model = names[int(ask("Size?", [str(i) for i in range(1, len(names) + 1)], str(names.index(model) + 1), - a.yes)) - 1] - d = sizes[model] - # images: the encoder on the GPU takes VRAM the experts would have, so a small card gets it on the CPU - vision = "none" - if sees: - auto = "gpu" if vram >= POLY_VISION_GPU_GB else "cpu" - if a.vision: - vision = {"yes": auto, "no": "none"}.get(a.vision, a.vision) - else: - say() - say(f" Images: the model can also read pictures (screenshots, photos, scanned pages). This adds a " - f"{fam['vision_gb']} GB") - say(" download and a compile of the image encoder, which " + - (f"keeps ~{fam['vision_vram_gb']} GB of VRAM (--vision cpu: none, a few seconds a picture)." - if auto == "gpu" else - f"runs on the CPU on this card (a few seconds a picture; --vision gpu: ~{fam['vision_vram_gb']} " - "GB of VRAM).")) - vision = auto if ask("Do you want images?", ["y", "n"], "n", a.yes) == "y" else "none" - ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) - room = max(0.0, vram - (fam["vision_vram_gb"] if vision == "gpu" else 0)) # the VRAM left for the model - beside = poly_beside_gb(d) - held, need_ram = poly_held_gb(d, room), poly_ram_need(d, room) - say() - say(f" {model}: {d['about']}; download {d['download_gb']:.0f} GB. The file is read in place: about {held:.0f} of") - say(f" its {d['arena_gb']:.0f} GB of experts fit {'these cards' if multi else 'this card'}, the rest stay in RAM " - "(the OS file cache).") - if room < beside + 2: - enc = vision == "gpu" # the encoder's share may be what does not fit - confirm_risk(f"{title} takes about {beside} GB of VRAM before any expert (measured on a 32 GB " - f"card at a 32K context)" + (f" and its image encoder {fam['vision_vram_gb']} GB" if enc else "") + - f"; {gpu_name(gpu)} has less than it takes to start", bool(a.model), a.yes, - f"{title} needs more VRAM than {vram:.0f} GB", - ("--vision cpu keeps the image encoder off the card; " if enc else "") + - f"--family {family} --model {model} --yes installs it anyway") - warn(f"going on with {vram:.0f} GB of VRAM, as you chose") - elif vram < 30: - ran = fam.get("ran_on_gb", 32) # a card of 8 GB reports 8,188 MiB - warn((f"{title} has run on no card under {ran} GB. " if round(vram) < ran else "") + - f"On {vram:.0f} GB about {100 * held / d['arena_gb']:.0f}% of {title}'s experts fit in VRAM " - f"({100 * poly_held_gb(d, 31.84) / d['arena_gb']:.0f}% on a 32 GB card): more of every answer is " - "computed on the CPU, so it is slower") - if ram < need_ram - 4: - confirm_risk(f"RAM: {ram:.0f} GB. {title} wants about {need_ram:.0f} GB on this card by setup's estimate: the " - f"{d['arena_gb'] - held:.0f} GB of experts the GPU does not hold are read through the OS file " - "cache. With less RAM they come from the SSD while it answers: expect it to be much slower (not " - "measured)", bool(a.model), a.yes, - f"{title} wants about {need_ram:.0f} GB of RAM; this PC has {ram:.0f}", - f"--family {family} --model {model} --yes installs it anyway") - warn(f"going on with {ram:.0f} GB of RAM, as you chose") - ok(f"size: {model}") - tag = fam["tag"] + model # names of the config, the start script and the data folders - - if a.context: - ctx = a.context - if not 16 <= ctx <= 1048576: - fail(f"--context {ctx}: {title} takes 16 to 1048576 tokens") - else: - say() - say(" Context length = how much text the model can see at once (your chat, files, tool output).") - say(" Longer takes VRAM from the expert cache:") - row = fam.get("row_bytes", GLM_ROW_BYTES) - # writing after a prompt that fills the context, tokens/s, on the 8 GB laptop (docs/BACKENDS.md, docs/LFM.md) - laptop = fam.get("laptop_tps") or ({32768: "52-58", 65536: "42-46", 131072: "28-30"} - if fam.get("ran_on_gb") == 8 else {}) - for i, c in enumerate(POLY_CONTEXTS, 1): - on8 = f"; 8 GB card: {laptop[c]} tokens/s after a full prompt" if c in laptop else "" - note = f" (recommended{on8})" if c == 32768 else \ - f" ({(c - 32768) * row / 1e9:.1f} GB more VRAM{on8 or '; no long prompt run'})" if c > 32768 else "" - say(f" {i}) {c // 1024}K tokens{note}") - ctx = POLY_CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(POLY_CONTEXTS) + 1)], - str(POLY_CONTEXTS.index(32768) + 1), a.yes)) - 1] - ok(f"context: {ctx} tokens") - - # the conversation cache: asked once, then kept as the model's run config has it - cfg_path = ROOT / f"strata-{tag.lower()}.json" - conv = poly_saved_conv([cfg_path, adopted if adopted is not None and adopted.name == cfg_path.name else None]) - if conv is None: - say() - say(" Conversation cache: a coding agent sends several conversations in turn (the main one, its subagents,") - say(" short side requests). With the cache, one that makes room for another is kept in RAM and comes back") - say(f" without being read again. It takes what it holds, up to {POLY_CONV_CACHE_MIB // 1024} GB of RAM.") - room = ram >= need_ram + POLY_CONV_CACHE_MIB / 1024 - conv = POLY_CONV_CACHE_MIB if ask("Keep several conversations in RAM?", ["y", "n"], "y" if room else "n", - a.yes) == "y" else 0 - ok("conversation cache: " + (f"up to {conv} MiB of RAM" if conv else "off (the last conversation is kept)")) - - # one file, or the numbered files of a split GGUF: the engine is given the first and finds the others by name - models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag - shards = [models_dir / model_file(fam, model, i) for i in range(1, model_shards(fam, model) + 1)] - absent = [s.name for s in shards if not s.exists()] - if a.gguf_dir and absent: - fail(f"{models_dir} has no {absent[0]}", - "put the file there under that name, or leave out --gguf-dir and setup downloads it") - if not a.gguf_dir and not all(s.exists() and done(s) for s in shards): - for r in elsewhere: # already downloaded in a PolyStrata folder on another drive - cand = [r / "models" / tag / s.name for s in shards] - if all(c.exists() and done(c) for c in cand): - models_dir, shards = cand[0].parent, cand - ok(f"model file found in {models_dir}") - break - for s in shards: # #173: a whole file copied in by hand - if s.exists() and not done(s) and whole_shard(s): - mark(s, "whole (checked against its own tensor directory)") - gguf = shards[0] - have_model = all(s.exists() and (done(s) or bool(a.gguf_dir)) for s in shards) - # the size's draft model: beside the model's file, or, when --gguf-dir has none, where setup keeps its own - guesser = models_dir / Path(d["draft_model"]).name if d.get("draft_model") else None - if guesser is not None and a.gguf_dir and not guesser.exists(): - guesser = Path(a.models_dir) / tag / guesser.name - have_guesser = guesser is None or guesser.exists() and (done(guesser) or bool(a.gguf_dir) or whole_shard(guesser)) - # the image encoder, in the same places - mmproj = models_dir / fam["mmproj"] if vision != "none" else None - if mmproj is not None and a.gguf_dir and not mmproj.exists(): - mmproj = Path(a.models_dir) / tag / mmproj.name - have_mmproj = mmproj is None or mmproj.exists() and (done(mmproj) or bool(a.gguf_dir) or whole_shard(mmproj)) - 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 - need = (0 if have_model and have_guesser else max(d["download_gb"] - on_disk, 0)) + \ - (0 if have_mmproj else fam["vision_gb"]) + 2 - if free_gb(models_dir) < need: - fail(f"not enough free disk space in {models_dir}: need ~{need:.0f} GB" + - (f" ({on_disk:.0f} GB of the model is already there)" if on_disk >= 1 and not have_model else ""), - "use --models-dir on a bigger drive") - - step(3, "Python packages") - pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, - "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") - - step(4, "the strata-poly engine") - llama = get_llama_cpp() - ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml)") - if not a.build and not hip and cuda_tk != 12: - get_poly_prebuilt(gpu) - eng = build_engine_poly_hip(gpu, llama) if hip else build_engine_poly(gpu, a.yes, llama, vision, cuda_tk) - lib_dirs = engine_lib_dirs(eng) - ok(f"engine: {eng / POLY_EXE}") - - step(5, f"downloading {title} {model}") - if not have_model: - say(f" The model file goes in {models_dir}") - say(f" A file you already have: put it there with its original name ({', '.join(s.name for s in shards)}), " - "or use --gguf-dir .") - if hf_endpoint() != HF_DEFAULT: - say(f" Downloading from {hf_endpoint()} (HF_ENDPOINT)") - for s in shards: - if s.exists() and done(s): - ok(f"{s.name} already downloaded") - continue - download(d.get("hf", fam["hf"]) + s.name, s) - check_shards(shards) - for s in shards: - verify_sha256(s, *fam["sha256"][s.name]) - if guesser is not None: - if not have_guesser: - say(" Its draft model lets it guess a few words ahead and check them at once (faster answers).") - download(d.get("hf", fam["hf"]) + d["draft_model"], guesser) - verify_sha256(guesser, *fam["sha256"][guesser.name]) - if mmproj is not None: - if not have_mmproj: - download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder") - verify_sha256(mmproj, *fam["sha256"][mmproj.name]) - ok(f"vision encoder: {mmproj}") - ok("model file present") - - step(6, "preparing the model for PolyStrata") - pack = find_in([data, *elsewhere], f"packs/{tag.lower()}") or data / "packs" / tag.lower() - if not (pack / "tokenizer" / "vocab.json").exists(): - run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(gguf), "--out", str(pack)], - env=dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py"))) # writes /tokenizer/ - # The engine counts which experts are used and writes the counts back when it stops, so its profile is a file of - # this install's own: it starts as the counts the repository ships, or with none where it ships none. - profile = pack / "expert-profile.txt" - shipped = d.get("profile", fam.get("profile")) - if shipped and not profile.exists(): - pack.mkdir(parents=True, exist_ok=True) - shutil.copyfile(ROOT / "data" / shipped, profile) - # GLM's draft block is the model's, one for every size. A size whose file leaves it out gets it here: the block - # alone is downloaded, not the file it comes from. - draft = None - if d.get("draft") != "own" and fam.get("draft"): - draft = find_in([data, *elsewhere], fam["draft"]) or data / fam["draft"] - if not draft.exists(): - say(" The draft block lets the model guess a few words ahead and check them at once (faster answers).") - say(f" {model}'s file has none, so the block alone is downloaded (~{fam['draft_gb']} GB).") - run([sys.executable, str(ROOT / "tools" / "glm_draft_fetch.py"), "fetch", "--out", str(draft)]) - ok(f"draft block: {draft}") - if guesser is not None: - draft = guesser - ok(f"draft model: {draft}") - ok(f"model prepared: {pack}") - - step(7, "writing the start script") - args = ["--model", str(gguf), "--max-context", str(ctx), "--expert-profile", str(profile)] - if draft: - args += ["--draft-model", str(draft)] - if conv: - args += ["--conversation-cache-mib", str(conv)] - if a.vram_reserve_mib is not None: - args += ["--vram-reserve-mib", str(a.vram_reserve_mib)] - ok(f"VRAM kept free for other programs: {a.vram_reserve_mib} MiB (--vram-reserve-mib; the expert cache takes " - "that much less)") - if fam.get("tail_skip"): - args += ["--tail-skip", str(fam["tail_skip"])] - if not multi and poly_batch(fam, d, vram, ctx): - args += ["--prompt-batch", "2048"] - ok("prompts are read 2,048 tokens at a time (--prompt-batch in the config)") - # The engine's own count is every logical CPU. On a hybrid CPU that is the slowest: an efficiency core runs - # an expert at half the speed, and a layer waits for its slowest part (hybrid_pool_workers()). - cores = cpu_cores() - threads = hybrid_pool_workers(cores) - if threads is not None: - args += ["--threads", str(threads)] - ok(f"hybrid CPU ({cores[0]} performance + {cores[1]} efficiency cores): {threads} CPU threads for the experts " - "outside VRAM (--threads in the config)") - cfg = {"exe": str(eng / POLY_EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), - "model_name": f"{fam['name']}-{model.lower()}", "display_name": f"{title} {model}", - "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} - if multi: # the server passes --layer-split and orders the cards - cfg["gpu"], cfg["gpus_asked"] = multi, True - cfg["layer_split"] = a.layer_split or "auto" - ok(f"layer split across GPUs {multi} ({cfg['layer_split']})") - elif gpu["count"] > 1 or a.gpu is not None: - cfg["gpu"] = gpu["index"] # the engine is told this card (issue #51) - cfg["gpus_asked"] = True - if cuda_tk == 12: - cfg["cuda"] = 12 # a copy set up from this install takes it too - if a.host: - cfg["host"] = a.host - if a.api_key: - cfg["api_key"] = a.api_key - if a.browser is not None: - cfg["open_browser"] = a.browser - earlier = adopted if adopted is not None and adopted.name == cfg_path.name else None - if vision != "none": - # the most rows a picture becomes: one of this engine's prompt batches (1,024) holds a picture of Gemma 4's - vt = vision_tokens(a.vision_tokens, vision, cfg_path if cfg_path.is_file() else earlier) - if vt > fam.get("vision_most", vt): - warn(f"--vision-tokens {vt}: {title} reads a picture in one prompt batch, {fam['vision_most']} tokens " - "unless the engine is started with a larger --prompt-batch; a picture with more is refused") - cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(gguf), "gpu": vision == "gpu", - "max_tokens": vt} - if vision == "cpu": - cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) - # requests at once: written only when given, else an earlier "parallel" is carried over (write_setup_config) - if a.parallel is not None: - cfg["parallel"] = a.parallel if a.parallel >= 2 else 1 - for line in poly_parallel_note(a.parallel, d, vram): - (ok if a.parallel is not None else say)(line if a.parallel is not None else " " + line) - poly_kv_whole(cfg) - write_setup_config(cfg_path, cfg, earlier) - script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) - ok(f"start script: {script.name}") - - say() - say("All set.") - say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") - say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") - if vision != "none": - say(" Images: send them in the chat page, in chat.py (/image ) or over the API") - if a.host and a.host not in ("127.0.0.1", "localhost"): - say(f" Other devices: the server window prints this PC's address (http://:{port}/)" - + ("" if a.api_key else " - no API key set: anyone on your network can use it")) - say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") - if a.no_start: - return 0 - return start(cfg_path, port) - - -# ------------------------------------------------------------------------------------------------ main -def mac_setup(argv) -> int: - """A Mac (Apple Silicon): the Metal engine, built from source on the Mac by metal/setup_mac.py (its own steps: - the Mac check, the pack by unified memory, the engine build, the Metal defaults). Nothing of the CUDA / HIP paths - is used or changed.""" - return subprocess.call([sys.executable, str(ROOT / "metal" / "setup_mac.py"), *argv]) - - -def sycl_setup(argv) -> int: - """--backend sycl: the Intel Arc engine (the SYCL port in sycl/, PR #423), experimental. There is no ready-made - Intel engine: it is compiled from source on the PC (docs/INTEL_ARC.md), then sycl/setup_intel.py runs this setup - with the Intel steps swapped in. Nothing of the CUDA / HIP paths is used or changed.""" - say() - say(" Intel Arc (--backend sycl): supported since 0.1.40.2 on Linux, tested on an Arc Pro B70 (xe) and an Arc A750 " - "(i915); other Arc cards and driver versions are untested, and reports help (docs/INTEL.md).") - if WIN: - fail("the Intel Arc engine has no Windows setup yet (no ready-made Intel engine either)", - "run it on Linux (Ubuntu 24.04 with Intel's GPU driver and oneAPI): docs/INTEL_ARC.md") - say(" There is no ready-made Intel engine: it is built from source with Intel oneAPI (icpx + oneMKL),") - say(" docs/INTEL_ARC.md. Setup continues with sycl/setup_intel.py.") - rest, skip = [], False - for x in argv: # setup_intel.py drives this setup through its AMD path - if skip: - skip = False - elif x == "--backend": - skip = True - elif not x.startswith("--backend="): - rest.append(x) - script = ROOT / "sycl" / "setup_intel.py" - if not script.exists(): - fail(f"{script} is missing", "use a full PolyStrata checkout (git clone) - docs/INTEL_ARC.md") - return subprocess.call([sys.executable, str(script), *rest]) - - -def engine_step(a, gpu, hip, amd, cuda_tk, vision): - """Step 4: llama.cpp's sources and the engine (ready-made, or compiled here). Returns (llama, engine folder, its - BUILD.json, its library folders, the GPU (AMD on Windows: as the engine sees it), the image-encoder choice).""" - llama = get_llama_cpp() - ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)") - if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler) - eng = None if a.build else get_prebuilt_hip(a.prebuilt, gpu) - if eng is None: - fail("no ready-made AMD engine for this PolyStrata version" + (" (--build)" if a.build else ""), - "compiling it on Windows: tools\\hip\\build_windows.bat makes strata-windows-x64-hip.zip, then run " - "START-HERE.bat --backend hip --prebuilt (docs/AMD_HIP.md)") - gpu = hip_card(eng, gpu, amd) - a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu - else: - eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision, **({"toolkit": 12} if cuda_tk == 12 - else {})) - if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local": - pip_cuda_libs(cuda_tk) - if vision != "none" and not (eng / VEXE).exists(): - warn("the ready-made engine has no image encoder: compiling it") - eng = None - else: - vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text(encoding="utf-8")), gpu, vision) - if eng is None: - eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk) - meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) - if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH - lib_dirs = [str(d) for d in hip_lib_dirs(eng)] - else: - lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk) - return llama, eng, meta, lib_dirs, gpu, vision - - -def engine_families(eng: Path) -> set: - """The model families an engine runs (`strata --families`; an engine from before it: Flash-Next's only).""" - try: - text = subprocess.run([str(eng / EXE), "--families"], capture_output=True, text=True, timeout=60, - env=engine_env(eng)).stdout # #2372: with the engine's rocm/bin on PATH - except (OSError, subprocess.SubprocessError): - return {"qwen4exp"} - names = set(text.split()) - return names if "qwen4exp" in names else {"qwen4exp"} - - -def own_path_context(fam: dict, vram_gb: float) -> int: - """The recommended context for an own-path family: its KV cache (VRAM) beside the dense weights and the most-used - experts - 32K up to 16 GB, 64K up to 24 GB, 128K above.""" - return 32768 if vram_gb <= 16.5 else 65536 if vram_gb <= 24.5 else 131072 - - -def own_path_size(fam: dict, ram: float) -> str: - """The recommended size: the largest file whose RAM need this PC has (the smallest when none fits).""" - fits = [m for m, d in fam["models"].items() if ram >= d["ram_gb"]] - return max(fits, key=lambda m: fam["sha256"][fam["file"].format(q=m)][0]) if fits else next(iter(fam["models"])) - - -def own_path_vision(a, fam: dict, gpu: dict, hip: bool) -> str: - """The image encoder for an own-path family (Qwen3.6-35B-A3B): "gpu", "cpu" or "none". The Flash-Next families' rules: - --vision yes|no|gpu|cpu, else a question whose default answer is yes where the GPU encoder costs little - an NVIDIA - card of 16 GB or more (its ~1.4 GB is under a tenth of it) - and, on AMD under Linux, yes with the CPU encoder (it takes - no VRAM; there is no GPU encoder for AMD yet). A smaller NVIDIA card is recommended the CPU encoder (the GPU one takes - room from the experts); what is asked for with --vision gpu is kept, with a note (recommend, never force).""" - asked = a.vision - vram = float(gpu.get("vram_gb", 0.0)) - big = vram >= UNSLOTH_IMAGES_MIN_VRAM_GB - if asked in ("no", "none"): - return "none" - if asked is None: - say() - say(f" Images: {fam['title']} can also read pictures (screenshots, photos, scanned pages). This adds a " - f"{fam['sha256'][fam['mmproj']][0] / 1e9:.1f} GB download" + ( - "; the encoder runs on the CPU (no VRAM), a few seconds per picture." if hip else - " and the image encoder runs on the GPU (~1.4 GB of VRAM kept free, 0.1-0.5 s per picture)." if big else - "; the encoder runs on the CPU (a few seconds per picture), because the GPU encoder would take ~1.4 GB " - "of VRAM from the experts on this card.")) - default = "n" if (hip and WIN) else "y" if (big or hip) else "n" - if ask("Do you want images?", ["y", "n"], default, a.yes) != "y": - return "none" - asked = "cpu" if (hip or not big) else "gpu" - if hip: - if asked == "gpu": - say(" The AMD backend has no GPU image encoder yet: the encoder runs on the CPU.") - if WIN: - warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no " - "image encoder): images off") - return "none" - return "cpu" - if asked == "yes": - asked = "gpu" if big else "cpu" - if asked == "gpu" and not big and vram > 0: - 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: " - "--vision cpu reads pictures on the CPU instead (a few seconds each); kept as you chose") - return asked - - -def own_path_parallel_slot_gb(fam: dict, ctx: int) -> float: - """The VRAM one batch slot's session takes: its KV cache (fp32 K and V of the attention layers and the MTP block) and - the recurrent state of the GDN layers.""" - return ctx * fam["kv_bytes_per_token"] / 1e9 + fam["state_gb"] - - -PARALLEL_SMALL_SHARE = 0.35 # a card that does not hold every expert: the slots' sessions may take this share of the room the - # experts would have (VRAM less ~4.5 GB for the dense weights and buffers). Measured (Q4_K_XL): - # RTX 3060 12 GB, 8K context, 4 slots (23% of that room): a request alone -4%; A4000 / P100 - # 16 GB, 32K, 2 slots (27%): -11% / -9%, 4 slots (54%): -27% and no gain together. - - -def own_path_parallel_fits_all(fam: dict, model: str, vram_gb: float, ctx: int, n: int) -> bool: - """True where every routed expert still sits in VRAM beside n slots' sessions (one more session than the slots: the - solo path's own).""" - size = fam["sha256"][fam["file"].format(q=model)][0] / 1e9 - base = size * 0.93 + 4.5 # the routed experts + the dense weights and buffers (the file's 7% beyond them) - return base + (n + 1) * own_path_parallel_slot_gb(fam, ctx) <= vram_gb - - -def own_path_parallel_recommend(fam: dict, model: str, vram_gb: float, ctx: int) -> int: - """How many requests at once to recommend: 0 = none (the card cannot hold even two slots). Where every routed expert - still fits in VRAM with the slots' sessions, up to 4 (a batch reads each expert once for all its rows). On a card - that does not hold every expert even for one session (the hybrid mode already) it is recommended too, as an offer with - its price said: measured on - an RTX 3060 12 GB, 4 requests together run ~1.5x as fast as one, a request alone ~5% slower, because the slots take - VRAM from the expert cache; up to the count whose sessions leave PARALLEL_SMALL_ROOM_GB of the card.""" - slot = own_path_parallel_slot_gb(fam, ctx) - best = max([n for n in (2, 3, 4) if own_path_parallel_fits_all(fam, model, vram_gb, ctx, n)], default=0) - if best: - return best - if own_path_parallel_fits_all(fam, model, vram_gb, ctx, 0): - return 0 # a card that holds every expert for one session only: more sessions would push experts to the CPU - # (measured on a 32 GB R9700 at 128K: 4 slots left 15 of 256 experts per layer, decode 81 tok/s - # against ~180): not offered there, a number asked for is kept - room = max(vram_gb - 4.5, 0.0) - return max([n for n in (2, 3, 4) if n * slot <= PARALLEL_SMALL_SHARE * room], default=0) - - -def own_path_parallel_note(a_parallel, fam: dict, model: str, vram_gb: float, ctx: int) -> list: - """What setup says about "parallel" for an own-path family: the recommendation, or how the asked count compares with - it (kept as asked: recommend, never force).""" - rec = own_path_parallel_recommend(fam, model, vram_gb, ctx) - slot = own_path_parallel_slot_gb(fam, ctx) - if a_parallel is None or a_parallel <= 1: - if not rec: - return ["Several requests at once (opt-in, --parallel N): left at one at a time, because this card cannot spare " - f"the room: each session takes ~{slot:.1f} GB of VRAM at this context, and where the card holds every " - "expert only for one session, more would move experts to the CPU and slow every request a lot (a " - "smaller context leaves room for more; docs/QWEN36.md)."] - if own_path_parallel_fits_all(fam, model, vram_gb, ctx, rec): - return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together instead of one after " - f"the other (each takes ~{slot:.1f} GB of VRAM at this context; docs/BATCHING.md)."] - return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together, so a second user or agent " - "starts at once instead of waiting for the first. The price on this card, which does not hold every expert: " - f"each session takes ~{slot:.1f} GB of VRAM from the expert cache, so a request alone runs about 4-11% " - "slower, and next to one-at-a-time WITH the draft layer the requests together are only 1.0-1.15x faster " - "(measured, Q4_K_XL: RTX 3060 12 GB at 8K context, 4 requests: 1.15x, alone -4%; A4000 / P100 16 GB at " - "32K, 2 requests: 1.0x, alone -7 to -11%). Worth it for several users at once, not for one chat " - "(docs/QWEN36.md)."] - lines = [f"parallel requests: {a_parallel} at once (each takes ~{slot:.1f} GB of VRAM at this context, " - f"{a_parallel * slot:.1f} GB in all)"] - if a_parallel > PARALLEL_MAX: - lines.append(f"the engine runs at most {PARALLEL_MAX} at once; it will use {PARALLEL_MAX}") - if not rec: - lines.append("recommended for this card: one at a time - there is no room for more sessions; kept as you chose") - elif a_parallel > rec: - lines.append(f"recommended for this card: {rec} - more slots leave fewer experts in VRAM, which can make every " - "request slower; kept as you chose") - return lines - - -def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted): - """Steps 2-7 for a family with its own engine path (OWN_PATH_FAMILIES: Qwen3.6-35B-A3B): the size, the context, the - engine, the GGUF (pinned revision, size and SHA-256), the tokenizer from the GGUF, the config and the start - script. The engine places the experts itself (every one in VRAM when they fit, else the most-used ones there and - the rest on the CPU), so there is no pack, profile or RAM budget to choose.""" - fam = OWN_PATH_FAMILIES[family] - say() - say(f" {fam['title']} - {fam['by']}: {fam['about']}") - ok(f"model: {fam['title']}") - if fam.get("license"): - say(f" Its license: {fam['license']}") - if multi: - warn(f"{fam['title']} runs on one GPU so far: using GPU {gpu.get('index', 0)} ({gpu_name(gpu)}) only") - names = list(fam["models"]) - if a.model and a.model not in names: - fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names)) - say() - for i, m in enumerate(names, 1): - d = fam["models"][m] - size = fam["sha256"][fam["file"].format(q=m)][0] - fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" - say(f" {i}) {m:10s} {d['about']}; download {size / 1e9:.1f} GB{fit}") - rec = own_path_size(fam, ram) - if not a.model: - say(f" Recommended for {ram:.0f} GB of RAM: {rec} (the largest that fits; any size can be chosen)") - model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], - str(names.index(rec) + 1), a.yes)) - 1] - if ram < fam["models"][model]["ram_gb"]: - confirm_risk(f"{model} needs about {fam['models'][model]['ram_gb']} GB of RAM; this PC has {ram:.0f} GB: the " - "OS may page and it may not start", bool(a.model), a.yes, - f"{model} needs about {fam['models'][model]['ram_gb']} GB of RAM", - f"choose a smaller size, or --model {model} --yes to install it anyway", " Install it anyway?") - warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose") - ok(f"size: {model}") - tag = fam["tag"] + model - rec_ctx = own_path_context(fam, gpu.get("vram_gb", 0.0)) - if a.context: - ctx = a.context - else: - ctxs = [c for c in CONTEXTS if c <= 262144] # the model's trained length; no rope scaling on this path yet - say() - say(" Context length = how much text the model can see at once. Its cache takes " - f"{fam['kv_bytes_per_token'] * 32768 / 2**30:.1f} GB of VRAM per 32K tokens, room the experts would use:") - for i, c in enumerate(ctxs, 1): - say(f" {i}) {c // 1024}K tokens" + (" (recommended for your GPU)" if c == rec_ctx else "")) - ctx = ctxs[int(ask("Context?", [str(i) for i in range(1, len(ctxs) + 1)], str(ctxs.index(rec_ctx) + 1), - a.yes)) - 1] - if ctx > 262144: - warn(f"{ctx // 1024}K is past {fam['title']}'s trained 262,144 positions and this engine path has no rope " - "scaling yet: kept as you chose, but answers past 256K are untested") - ok(f"context: {ctx} tokens") - vision = own_path_vision(a, fam, gpu, hip) - ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) - vram_gb = float(gpu.get("vram_gb", 0.0)) - par = getattr(a, "parallel", None) - par_said = False - if par is None and not a.yes: # offered, with its price; Enter keeps one at a time (never forced) - say() - for line in own_path_parallel_note(None, fam, model, vram_gb, ctx): - say(" " + line) - par_said = True - if own_path_parallel_recommend(fam, model, vram_gb, ctx): - n = int(ask("How many requests at once (1 = one at a time)?", [str(i) for i in range(1, PARALLEL_MAX + 1)], - "1", a.yes)) - par = n if n > 1 else None - 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"): - warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} " - "does not use them") - folder = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag - gguf = folder / fam["file"].format(q=model) - size = fam["sha256"][gguf.name][0] - part = gguf.with_name(gguf.name + ".part") - left = 0 if gguf.exists() and done(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9 - if left and free_gb(folder) < left + 1: - fail(f"not enough free disk space in {folder}: need ~{left + 1:.0f} GB", "use --models-dir on a bigger drive") - - step(3, "Python packages") - pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, - "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") - - step(4, "the PolyStrata engine") - llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision) - if vision != "none" and not (eng / VEXE).exists(): - warn("this engine has no image encoder: images off (run setup again with --build to compile it)") - vision = "none" - if fam["arch"] not in engine_families(eng): - fail(f"this engine ({meta.get('version')}) does not run {fam['title']} yet", - "update PolyStrata, or compile the engine with --build, and run setup again") - ok(f"engine: {eng / EXE}") - - step(5, f"downloading {fam['title']} {model}") - if gguf.exists() and done(gguf): - ok(f"{gguf.name} already downloaded") - else: - if a.gguf_dir: - fail(f"{gguf} is missing", f"put {gguf.name} in {folder}, or drop --gguf-dir to download it") - download(fam["hf"] + gguf.name, gguf) - verify_sha256(gguf, *fam["sha256"][gguf.name]) - ok(f"model file: {gguf}") - mmproj = folder / fam["mmproj"] - if vision != "none": # the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked - if mmproj.exists() and done(mmproj): - ok(f"{mmproj.name} already downloaded") - else: - if a.gguf_dir: - fail(f"{mmproj} is missing", f"put {mmproj.name} in {folder}, or drop --gguf-dir to download it") - download(fam["mmproj_hf"] + mmproj.name, mmproj, "vision encoder") - verify_sha256(mmproj, *fam["sha256"][mmproj.name]) - ok(f"vision encoder: {mmproj}") - - step(6, "preparing the model for PolyStrata") - data, _ = data_folder(a.data_dir) - pack = data / "packs" / tag.lower() # only the tokenizer: the engine reads the GGUF itself - if not (pack / "tokenizer" / "vocab.json").exists(): - run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(gguf), "--out", str(pack)], - env=dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py"))) - ok(f"tokenizer: {pack / 'tokenizer'}") - - step(7, "writing the start script") - args = ["--native", str(gguf), "--max-context", str(ctx), "--prefill", "auto", "--mtp", str(fam["mtp"])] - if a.vram_reserve_mib is not None: # VRAM left free for other programs: the experts take that much less - vram = gpu.get("vram_gb", 0.0) - if vram > 0: - args += ["--expert-vram", f"{max(vram - 3.0 - a.vram_reserve_mib / 1024, 0):.1f}"] - ok(f"VRAM kept free for other programs: about {a.vram_reserve_mib} MiB (the experts' share is set lower)") - cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), - "model_name": f"{fam['name']}-{model.lower()}", "arch": fam["arch"], - "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} - if cuda_tk == 12: - cfg["cuda"] = 12 - if hip: - cfg["backend"] = "hip" - if gpu.get("count", 1) > 1 or a.gpu is not None: - cfg["gpu"] = gpu["index"] - cfg["gpus_asked"] = True - if a.host: - cfg["host"] = a.host - if a.api_key: - cfg["api_key"] = a.api_key - if a.browser is not None: - cfg["open_browser"] = a.browser - cfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too - cfg_path = ROOT / f"strata-{tag.lower()}.json" - if vision != "none": - old_cfg = cfg_path if cfg_path.is_file() else adopted - vt = vision_tokens(getattr(a, "vision_tokens", None), vision, old_cfg) - cfg["args"].append("--vision") - cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(gguf), "gpu": vision == "gpu", - "max_tokens": vt} # the text model, opened vocab-only - if vision == "cpu": - cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) - elif getattr(a, "vision_tokens", None) is not None: - warn("--vision-tokens: images are off, so it is not used") - # requests at once ("parallel", opt-in): written only when given; the recommendation is said once - if par is not None: - if par >= 2: - cfg["parallel"] = par - for i, line in enumerate(own_path_parallel_note(par, fam, model, vram_gb, ctx)): - (ok if i == 0 else warn)(line) - else: - cfg["parallel"] = 1 - ok("parallel requests: one at a time (--parallel 1)") - write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) - script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) - ok(f"start script: {script.name}") - say() - say("All set.") - say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") - say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") - say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") - if vision != "none": - say(" Images: send them in the chat page, in chat.py (/image ) or over the API") - if par is None and not par_said: # the opt-in, said once (nothing changes) - for line in own_path_parallel_note(None, fam, model, vram_gb, ctx): - say(" " + line) - if a.no_start: - return 0 - return start(cfg_path, port) - - -def preview_family(a) -> int: - """--family qwen36-strata: a family setup knows but the engine does not run yet (PREVIEW_FAMILIES). Downloads the chosen - size (pinned revision, size and SHA-256 checked) and, with --vision, the image encoder - and says plainly that - PolyStrata cannot start it yet. Nothing is configured: no engine, no pack, no start script.""" - fam = PREVIEW_FAMILIES[a.family] - names = list(fam["models"]) - say() - say(f" {fam['title']} - {fam['by']}: {fam['about']}") - warn(f"this PolyStrata version does not run {fam['title']} yet (support is in development): setup downloads its " - "files, and the engine refuses them with a message until a version that runs it") - if a.model and a.model not in names: - fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names)) - ram = ram_gb() - for i, m in enumerate(names, 1): - d = fam["models"][m] - size = fam["sha256"][fam["file"].format(q=m)][0] - fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" - say(f" {i}) {m:10s} {d['about']}; download {size / 1e9:.1f} GB{fit}") - if a.check: - return 0 - model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], "1", a.yes)) - 1] - say(f" Its license: {fam['license']}") - want = [fam["file"].format(q=model)] - if a.vision in ("yes", "gpu", "cpu"): - want.append(fam["mmproj"]) - folder = Path(a.models_dir) / (fam["tag"] + model) - files = [folder / w for w in want] - left = sum(fam["sha256"][f.name][0] - (f.with_name(f.name + ".part").stat().st_size - if f.with_name(f.name + ".part").is_file() else 0) - for f in files if not (f.exists() and done(f))) / 1e9 - if left and free_gb(folder) < left + 1: - fail(f"not enough free disk space in {folder}: need ~{left + 1:.0f} GB", "use --models-dir on a bigger drive") - step(5, f"downloading {fam['title']} {model}") - for f in files: - url = (fam["mmproj_hf"] if f.name == fam["mmproj"] else fam["hf"]) + f.name - download(url, f, "vision encoder" if f.name == fam["mmproj"] else None) - verify_sha256(f, *fam["sha256"][f.name]) - ok(f"{fam['title']} {model}: {folder}") - say() - say(f"{fam['title']} is downloaded, but this PolyStrata version cannot run it yet (its engine path is in " - "development); nothing was configured. Run setup again without --family qwen36-strata to install a model it runs.") - return 0 - - -def main() -> int: - if sys.platform == "darwin": # a Mac: metal/setup_mac.py (the Metal engine) - return mac_setup(sys.argv[1:]) - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES), - help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5, glm = GLM 5.3 Flash (docs/GLM.md), deepseek = " - "DeepSeek V4 Flash, lfm25 = LFM2.5-24B-A2B, qwen36 = Qwen3.6-35B-A3B on strata-poly, ornith = " - "Ornith 1.5, gemma4 = Gemma 4 26B-A4B, tiel = Tiel Coder 35B-A3B, minicpmv = MiniCPM-V 4.7 " - "35B-A3B (docs/BACKENDS.md), qwen36-strata = Qwen3.6-35B-A3B on the Strata project's " - "own engine (UD-Q4_K_XL and up, 32 GB of RAM or more; pictures with --vision, several " - "requests at once with --parallel; docs/QWEN36.md)") - ap.add_argument("--model", choices=list(dict.fromkeys( - [*MODELS, *(m for f in FAMILIES.values() for m in f.get("models", {})), - *(m for f in PREVIEW_FAMILIES.values() for m in f["models"])]))) - ap.add_argument("--context", type=int) - ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"], - help="the RoPE extension for a context past the model's trained 262144: linear (position " - "interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " - "picks yarn; 'none' is refused for such a context") - ap.add_argument("--rope-scale", type=float, - help="the extension factor (default: the final context over the trained 262144, at least 1 - " - "1.5 for 384K, 2 for 512K, 1 inside the trained range)") - ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"], - help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " - "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") - ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], - help="let the model read images (yes = the encoder on the GPU)") - ap.add_argument("--vision-tokens", type=int, metavar="N", - help="the most image tokens a picture becomes (default 1024 with the encoder on the GPU, 300 on " - "the CPU): more reads small text and charts better, and takes longer to encode; remembered " - "for this model") - # image generation (Qwen-Image): in preview, not offered in setup or --help; the options still work (docs/IMAGES.md) - ap.add_argument("--images", choices=["qwen-image", "no"], - help=argparse.SUPPRESS) - ap.add_argument("--image-quant", choices=["Q4_K_M", "Q6_K", "Q8_0"], - help=argparse.SUPPRESS) - ap.add_argument("--image-backend", choices=["cuda", "hip", "vulkan", "cpu"], - help=argparse.SUPPRESS) - ap.add_argument("--image-native", choices=["on", "off"], - help=argparse.SUPPRESS) - ap.add_argument("--image-gpu-policy", choices=["auto", "keep", "shrink", "unload"], - help=argparse.SUPPRESS) - ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF", - help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " - "(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md") - 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)") - ap.add_argument("--gpu", help="one GPU, numbered as nvidia-smi numbers them (AMD: as setup lists them) (default: asked when several can be " - "used; with --setup it is saved, when starting it is for that start only)") - ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them (AMD: as setup lists " - "them): \"0,2\", or \"all\" (every card that can); the first is the main one. " - "Saved, also when starting (see docs/MULTI_GPU.md)") - ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"), one " - "rising number per GPU after the first - not layers per card; default " - "auto, placed from each GPU's free VRAM") - ap.add_argument("--no-remote-expert-opt", action="store_true", - help="with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)") - ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " - "devices on your network (issue #26; set --api-key too)") - ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0); several keys: key1,key2") - ap.add_argument("--no-browser", dest="browser", action="store_false", default=None, - help="do not open the chat page in the browser when the model is ready (for a harness or an app " - "that uses the API; remembered for this model, also in run-.bat/.sh)") - ap.add_argument("--browser", dest="browser", action="store_true", - help="open the chat page again when the model is ready (the default; undoes --no-browser)") - ap.add_argument("--data-dir", help="where the model files go (~70-120 GB): default PolyStrata-data next to this folder, " - "remembered for every PolyStrata folder on this PC") - ap.add_argument("--models-dir", help="where the GGUF files go (default: /models)") - ap.add_argument("--gguf-dir", help="use GGUF files you already have (a folder with every shard: " - "-00001-of-0000N.gguf ... -0000N-of-0000N.gguf)") - ap.add_argument("--yes", action="store_true", help="accept the recommended answers") - ap.add_argument("--setup", action="store_true", help="install another model or change settings") - ap.add_argument("--no-start", action="store_true", help="install only, do not start the model") - ap.add_argument("--update", action="store_true", - help="update the installed engine, Python packages and model settings as a start would, without " - "starting the model (UPDATE.bat / update.sh run it after a git pull)") - ap.add_argument("--rollback-engine", action="store_true", - help="put back the engine an update replaced (kept in engine/.previous), and keep the current one there") - ap.add_argument("--build", action="store_true", help="compile the engine instead of using the ready-made one") - ap.add_argument("--source", choices=SOURCES, default=None, - help="where the model files come from: auto (default: Hugging Face), huggingface or modelscope " - "(mainland China: the same files, checked against ModelScope's published SHA-256; " - "STRATA_SOURCE)") - ap.add_argument("--inspect", nargs="+", metavar=("SOURCE", "VARIANT"), - help="what a GGUF is and whether PolyStrata runs it, from its headers only (no download): a file, a " - "folder, a URL, ms:owner/repo (ModelScope) or hf:owner/repo, and optionally a variant name") - ap.add_argument("--cuda", choices=["12", "13", "auto"], default=os.environ.get("STRATA_CUDA") or None, - help="NVIDIA: the CUDA toolkit of this model's engine. auto (default): CUDA 13, the ready-made " - "engine; CUDA 12 (experimental) when a chosen card is older than CUDA 13 supports (Pascal, " - "Volta). 12 also runs with an older driver (Windows 528+, Linux 525+). docs/OLDER_GPUS.md") - ap.add_argument("--prebuilt", default=os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL), - help="where the ready-made engine is (a URL folder or a local folder)") - ap.add_argument("--check", action="store_true", help="only check this PC and exit") - ap.add_argument("--calibrate", action="store_true", - help="tune the engine's settings for this PC (about 15-30 minutes, longer on a slow card), then start the model") - ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS), - help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " - "and code only (~110 MiB less VRAM, English answers 1-2%% faster), cyrillic = English, code " - "and the Cyrillic script (Ukrainian, Russian... answers decode ~30%% faster), fr = English, " - "code and French (French answers: 18%% more drafts accepted)") - ap.add_argument("--low-ram", choices=["auto", "on", "off", "resident", "mmap"], default="auto", - help="read the model's experts from one file in its folder instead of copying them all into RAM " - "(for a PC with a big GPU and little RAM); auto: when the experts would not fit the RAM. In " - "this mode the experts the GPU does not hold are copied into RAM once when they fit (resident), " - "else read through the OS file cache (mmap); resident / mmap force one of the two") - ap.add_argument("--resident-budget-gib", type=float, metavar="N", - 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; " - "more is kept as you choose, with a note)") - ap.add_argument("--vram-reserve-mib", type=int, metavar="N", - help="VRAM in MiB the engine leaves free for other programs (a game, another model; the engine's " - "default: 700); the expert cache takes that much less") - ap.add_argument("--parallel", type=int, metavar="N", - help="up to N requests decode together (batch slots, opt-in; default: one at a time, the others " - "wait). Each slot takes VRAM from the expert cache; setup says what it recommends") - ap.add_argument("--replicas", type=int, metavar="N", - help="several GPUs: run N independent engines, each on its own equal group of the chosen cards (2 " - "replicas on 4 cards = two 2-card engines), requests spread over them (opt-in; more total " - "throughput for a model that fits fewer cards; each replica holds its own copy of the model)") - ap.add_argument("--kv-streaming", choices=["auto", "on", "off"], default="auto", - help="from a 64K context: keep the KV cache in RAM and only the attention's window in VRAM (more " - "experts fit on the GPU); auto: when the RAM has room for it") - ap.add_argument("--backend", choices=["cuda", "hip", "sycl"], - help="cuda = NVIDIA (default), hip = AMD RX 7900 / 7800 / 7700 XT, RX 9060 XT / 9070 / AI PRO R9700 on " - "Linux or Windows (chosen by itself when the PC has no NVIDIA card PolyStrata can use), " - "sycl = Intel Arc, EXPERIMENTAL: Linux, built from source (docs/INTEL_ARC.md)") - ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) - a = ap.parse_args() - # a strata-poly family's own size (FAMILIES[f]["models"]) is checked by poly_setup, which names the family - if a.model and a.model not in MODELS and a.family not in PREVIEW_FAMILIES and not any(a.model in d.get("models", {}) for d in FAMILIES.values()): - ap.error(f"--model {a.model} is a size of " + ", ".join(f"--family {f}" for f, d in PREVIEW_FAMILIES.items() - if a.model in d["models"])) - if a.source: - os.environ["STRATA_SOURCE"] = a.source - if a.inspect: # headers only: nothing is installed - sys.exit(subprocess.run([sys.executable, str(ROOT / "tools" / "strata_inspect.py"), *a.inspect[:2]]).returncode) - if a.backend == "sycl": # Intel Arc: the SYCL port's own setup (sycl/setup_intel.py) - return sycl_setup(sys.argv[1:]) - if a.resident_budget_gib is not None and not a.resident_budget_gib > 0: - ap.error("--resident-budget-gib takes a number of GiB above 0, e.g. --resident-budget-gib 32") - if a.vision_tokens is not None and a.vision_tokens < 1: - ap.error("--vision-tokens takes a number of image tokens, 1 or more, e.g. --vision-tokens 768") - if a.vram_reserve_mib is not None and a.vram_reserve_mib < 0: - ap.error("--vram-reserve-mib takes a number of MiB, 0 or more, e.g. --vram-reserve-mib 2048") - if a.gpu is not None: # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report) - if "," in a.gpu: - a.gpus, a.gpu = a.gpus or a.gpu, None - elif a.gpu.strip().isdigit(): - a.gpu = int(a.gpu) - else: - 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}") - say("PolyStrata - Qwen3.8-Flash-Next, GLM 5.3 Flash and smaller MoE models on a normal PC (a GPU + system RAM + CPU)") - data, elsewhere = data_folder(a.data_dir) # the model files: in the data folder, found from any copy - roots = [data, *elsewhere] - if a.models_dir is None: - a.models_dir = str(data / "models") - - if a.rollback_engine: # #670 - return rollback_engine(12 if a.cuda == "12" else 13) - - # ---- 0. already installed: just start it - have = installed_configs() - if a.update: # #475: UPDATE.bat / update.sh - never starts the model - return update_install(have, a) - explicit = a.setup or a.model or a.family or a.check or a.no_start - adopted = None # #629: the earlier install this copy is set up like - if not have and not explicit: # a new copy of PolyStrata (an update unzipped elsewhere): set it - prev = previous_config(elsewhere, load_settings()) # up like the last one, from the files already here - if prev is not None: - ch = choices_from_config(prev) - if ch["model"]: - say(f" Found your earlier install in {prev.parent} ({prev.stem[len('strata-'):]}): setting up this " - "copy the same way - the model files are reused, nothing big is downloaded.") - a.family, a.model, a.context = ch["family"], ch["model"], a.context or ch["context"] - adopted = prev - a.kv = a.kv or ch["kv"] - a.vision = a.vision or ch["vision"] - a.experimental_speed_projection = a.experimental_speed_projection or ch["esp"] - a.host, a.api_key = a.host or ch["host"], a.api_key or ch["api_key"] - a.port = a.port or ch["port"] - if a.vram_reserve_mib is None: # #493: an explicit reserve set up before - a.vram_reserve_mib = ch.get("vram_reserve_mib") - if a.cuda is None and ch.get("cuda") == 12: # the experimental CUDA 12 engine, as before - a.cuda = "12" - if isinstance(ch.get("gpu"), list): # a layer split: set up across the same cards again - a.gpus = a.gpus or ",".join(str(g) for g in ch["gpu"]) - a.layer_split = a.layer_split or ch.get("layer_split") - else: - a.gpu = a.gpu if a.gpu is not None else ch.get("gpu") - a.yes = True - global GPU_PICK, OLD_GPUS - # starting an installed model: --gpus 0,2 (or all) saves those cards for it and starts on them (it used to start - # on the first one alone unless given with --setup), --gpu N runs this start on one card; neither: the saved - # choice, and asked once when the PC has cards that could share the model - run_gpu = start_gpus(a.gpus) or a.gpu - port = a.port or 8080 # a new install's port (issue #32: --port for an existing one) - if a.calibrate and (a.setup or a.check or not have): # #2036: said, not dropped - why = ("--setup" if a.setup else "--check" if a.check else "no model is installed yet") - warn(f"--calibrate does nothing with {why}: it tunes a model that is already installed. Run setup first, " - "then " + ("START-HERE.bat" if WIN else "./setup.sh") + " --calibrate [--model NAME]") - if have and a.calibrate and not (a.setup or a.check): - targets = calibration_targets(have, a.model, a.family) - if not targets: # #2036: --model names a model that is not installed - names = ", ".join(sorted({choices_from_config(c)["model"] or c.stem for c in have})) - fail(f"--calibrate: {a.model or a.family} is not installed (installed: {names})", - "calibrate an installed model, or set this one up first without --calibrate") - have = targets - if not a.build: - update_installed_engine(a.prebuilt) - pick_cfg = have[0] - if len(have) > 1: - say() - for i, c in enumerate(have, 1): - say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") - pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1] - if poly_config(json.loads(pick_cfg.read_text(encoding="utf-8-sig"))): - warn("--calibrate measures settings of the Qwen engine: strata-poly has none of them, so nothing is " - "tuned") - elif not calibrate_config(pick_cfg): # #447: said again where it is not lost above the start - say() - warn("this PC is NOT tuned: the tuning failed (the reason is above); the model " - + ("keeps" if a.no_start else "starts with") + " the default settings") - return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, - keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, - "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) - if have and not (a.setup or a.model or a.family or a.check or a.no_start): - if not a.build: - update_installed_engine(a.prebuilt) - if len(have) == 1: - return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, - keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, - "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) - say() - for i, c in enumerate(have, 1): - say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") - say(f" {len(have) + 1}) install another model / change settings") - pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes)) - if pick <= len(have): - return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, - keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab, - "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) - - # ---- 1. the PC - step(1, "checking your PC") - found = gpus() - amd = amd_gpus() - amd_ok = [g for g in amd if amd_problem(g) is None] - # older NVIDIA GPUs (Pascal / Volta): the experimental CUDA 12 engine, when chosen (docs/OLDER_GPUS.md) - OLD_GPUS = OLD_GPUS or old_gpus_opt_in(found, named_gpus(a.gpu, a.gpus), a.cuda, - other=bool(amd_ok) or a.backend == "hip") - if OLD_GPUS and a.backend != "hip": - warn(f"older NVIDIA GPUs (Pascal / Volta) can be used ({OLD_GPUS}): experimental, through a second engine " - "built with CUDA 12 (docs/OLDER_GPUS.md)") - nv_ok = any(gpu_problem(g) is None for g in found) - hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok)) - if a.backend is None and nv_ok and amd_ok: - # both kinds of card: asked (a first run on such a PC used to take NVIDIA without mentioning the Radeon) - say() - say(" This PC has NVIDIA and AMD cards PolyStrata can use:") - say(" 1) NVIDIA: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in found if gpu_problem(g) is None) - + " (recommended)") - say(" 2) AMD: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB{', unified memory' if g.get('uma') else ''})" - for g in amd_ok) - + f" ({'the ready-made AMD engine, no images' if WIN else 'compiled here, images on the CPU'}" - " - docs/AMD_HIP.md)") - hip = ask("Which cards?", ["1", "2"], "1", a.yes or a.check) == "2" - if a.check and not hip: - say(f" (the AMD card: {'START-HERE.bat' if WIN else './setup.sh'} --backend hip)") - cuda_tk = 13 # NVIDIA: the toolkit of this model's engine (cuda_choice) - if hip: # AMD: compiled here; Windows: ready-made - if WIN and a.gpus: - fail("several AMD cards sharing one model (--gpus) is Linux-only for now", "use one card: --gpu N") - say(" Your AMD GPUs:" if amd else " No AMD GPU found (" + ("Windows lists no AMD display adapter)." if WIN - else "the amdgpu driver's KFD topology is empty).")) - for g in amd: - say(f" GPU {g['index']}: {g['name']}, {amd_mem_text(g)} - " + (amd_problem(g) or "can be used")) - usable = [g for g in amd if amd_problem(g) is None] - if not WIN and (amd or amd_pci_devices()): # a warning only: recommend, never force - acc = amd_device_access_problem() - if acc: - warn(acc) - if not amd and not WIN: # the KFD topology is empty: name a Strix Halo the kernel sees - for d in amd_pci_devices(): - if d["pci_id"] in STRIX_HALO_PCI_IDS: - say(f" The kernel lists an AMD Strix Halo (PCI 1002:{d['pci_id']:04x}) but /dev/kfd's topology is " - "empty: ROCm cannot use it yet (docs/STRIX_HALO.md: the amdgpu driver and /dev/kfd access, " - "your user in the render and video groups)") - if not usable: - fail("no AMD GPU PolyStrata can use", f"the AMD backend runs on {AMD_CARDS}") - if a.gpus: # a layer split across these cards, the first one the main - chosen = amd_parse_gpus(a.gpus, amd) - gpu = chosen[0] - elif a.gpu is not None: - gpu = next((g for g in usable if g["index"] == a.gpu), None) - if gpu is None: - fail(f"AMD GPU {a.gpu} cannot be used", "use one of: " + ", ".join(f"--gpu {g['index']}" for g in usable)) - chosen = [gpu] - else: - gpu = min(usable, key=amd_rank) # a discrete card before an APU, then the most memory - chosen = [gpu] - if len(usable) > 1 and any(g.get("uma") for g in usable) != all(g.get("uma") for g in usable): - others = [g for g in usable if g is not gpu] - say(f" Using GPU {gpu['index']} ({gpu['name']}); setup recommends the card with its own memory over " - "the APU's shared memory. To use another: " - + ", ".join(f"--gpu {g['index']} ({g['name']})" for g in others)) - # the engine is compiled for every chosen card's architecture - gpu = {**gpu, "count": len(amd), "archs": sorted({g["arch"] for g in chosen})} - chosen = [gpu] + chosen[1:] - sel = [g["index"] for g in chosen] - multi = sel if len(sel) > 1 else [] - a.gpu = gpu["index"] if len(amd) > 1 else a.gpu - if multi: - ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)") - ok(f"GPU: {gpu['name']}, {amd_mem_text(gpu) if gpu.get('uma') else format(gpu['vram_gb'], '.1f') + ' GB VRAM'}, " - f"{gpu['arch']} (AMD: docs/{'STRIX_HALO' if is_strix_halo(gpu) else 'AMD_HIP'}.md)") - if WIN and str(gpu.get("arch") or "").startswith("gfx12"): # only a pointer; no default changes - say(" If Windows resets the AMD driver (VIDEO_ENGINE_TIMEOUT_DETECTED, flicker, the engine dies mid-answer): " - "docs/TROUBLESHOOTING.md, \"Windows AMD: the driver resets\"") - if gpu.get("uma"): - for line in igpu_notes(gpu, ram_gb()): - (warn if line.startswith("!") else say)(line.lstrip("!")) - else: - if not found: - fail("no NVIDIA GPU found (nvidia-smi did not answer)", - "install the NVIDIA driver from https://www.nvidia.com/drivers and restart the PC" - + (f"; AMD ({', '.join(AMD_ARCHS)}): --backend hip" if amd else "")) - if len(found) > 1 or gpu_problem(found[0]) is not None: - gpu_table(found) - sel = choose_gpus(a, found) # asked when two or more cards can share the model - multi = sel if len(sel) > 1 else [] - a.gpu = sel[0] # the main GPU: the checks and the sizing below are its - GPU_PICK = a.gpu - gpu = gpu_info(a.gpu) - chosen = [gpu_info(i) for i in sel] - gpu["archs"] = sorted({x["arch"] for x in chosen}) # the engine needs code for every one of them - if multi: - ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)") - ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {cc(gpu)}, driver {gpu['driver']}") - # one engine per model: its oldest card decides - cuda_tk, why = cuda_choice(gpu["archs"], a.cuda, FAMILIES.get(a.family, {}).get("engine") == "poly") - if why: - (warn if cuda_tk == 13 or str(a.cuda) == "12" else ok)(f"CUDA {cuda_tk}: {why}") - min_driver = CUDA12_MIN_DRIVER if cuda_tk == 12 else MIN_DRIVER - if driver_major(gpu) < min_driver: - fail(f"the NVIDIA driver is too old ({gpu['driver']}; {min_driver} or newer is needed)", - "update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again" + - ("" if cuda_tk == 12 else f" (or --cuda 12: the experimental CUDA 12 engine runs with driver " - f"{CUDA12_MIN_DRIVER} or newer, docs/OLDER_GPUS.md)")) - if gpu["vram_gb"] < 11: - warn("less than 12 GB of " + ("GPU memory (this APU's carve-out + shared memory)" if gpu.get("uma") else "VRAM") - + ": PolyStrata will run, but most experts stay on the CPU and it will be slow") - ram = ram_gb() - cpu, avx2, avx512 = cpu_info() - need = min(d["ram_gb"] for d in MODELS.values()) - low_ok = low_ram_fits("IQ1_M", ram, low_ram_vram(gpu)) and a.low_ram != "off" # the smallest model, mapped - # a family of strata-poly has its own estimate of the RAM it wants, by size and card (poly_setup) - own_ram = bool(a.family) and FAMILIES[a.family].get("engine") == "poly" - if ram < need - 4 and not a.check and not low_ok and not own_ram: - # every model keeps ALL its experts in RAM (23+ GB); VRAM only holds a copy of the most-used ones, so a - # bigger GPU does not lower this. The owner's rule: a stop by default, a risk the user can take (--model - # with --yes, or y) - confirm_risk(f"RAM: {ram:.0f} GB - the smallest model (the Coder) needs about {need} GB: PolyStrata keeps all of " - "the model's experts in RAM (23-50 GB, whatever the GPU), so the OS will page them from disk. " - "Expect it to be very slow, and it may not start at all.", bool(a.model), a.yes, - f"RAM: {ram:.0f} GB - the smallest model (the Coder) needs about {need} GB", - "PolyStrata keeps all of the model's experts in RAM (23-50 GB, whatever the GPU) and the GPU holds a " - "copy of the most-used ones: it needs 32 GB of RAM or more (48 GB for the full model); --model " - "NAME --yes installs one anyway. Qwen3.6, Ornith 1.5 and Gemma 4 want less: --family qwen36, " - "ornith or gemma4") - warn(f"going on with {ram:.0f} GB of RAM, as you chose") - ram_msg = (f"RAM: {ram:.0f} GB" if ram >= need - 4 or own_ram else f"RAM: {ram:.0f} GB (less than the {need} GB the smallest model needs)" - + ("; the GPU's VRAM makes up for it (the low-RAM mode)" if ram < need - 4 and low_ok else "")) - (ok if ram >= need - 4 or low_ok or own_ram else warn)(ram_msg) # #977: a RAM below every model's floor is not [ok] - pf = page_file_gb() - if pf is not None and pf < 4: - warn(page_file_advice(pf, page_file_setting())) - ok(f"CPU: {cpu} ({'AVX-512' if avx512 else 'AVX2' if avx2 else 'no AVX2'})") - link = None if hip else pcie_link(int(gpu.get("index", 0))) - if link is not None: - line, problem = pcie_lines(link) - ok(line) - if problem: - warn(problem) - floor = cpu_floor(avx2) - if floor == "unsupported": - fail("this CPU has neither AVX2 nor SSE4.2; PolyStrata needs at least SSE4.2 (Intel Nehalem, 2008, or newer)") - if not avx2: - # #394 #595 #623: the ready-made engine is AVX2; an older CPU gets one compiled here, whose CPU experts run on - # ggml-cpu's kernels for this CPU. Experimental: measured only on newer CPUs with the older path forced, and by - # users on a few Xeons. A warning, not a stop. - warn(f"this CPU has no AVX2: PolyStrata support for it is EXPERIMENTAL and slow. Setup compiles the engine on this " - f"PC for {'AVX' if floor == 'avx' else 'SSE4.2'} (STRATA_ISA_FLOOR={floor}; 10-20 minutes, once), and the " - "CPU's share of the experts runs on ggml-cpu's kernels, a few times slower than on an AVX2 CPU. " - "See \"Older CPUs\" in docs/INSTALL.md") - if hip and WIN: - fail("the older-CPU engine is compiled from source, and setup compiles the AMD engine on Linux only", - "use Linux for an AMD card on this CPU, or an NVIDIA card") - a.build = True - if a.check: - say() - any_fits = False - for m, d in MODELS.items(): - verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit" - if "glm" in d.get("families", ()): - verdict = poly_verdict(d, ram, gpu["vram_gb"], hip) - elif d.get("budget") and not unsloth_budget(m, ram, gpu): # Phase 2: all of them in RAM - verdict = ("EXPERIMENTAL, " if d.get("experimental") else "") + "fits (all of its experts in RAM)" - elif d.get("budget"): - verdict = (("EXPERIMENTAL, " if d.get("experimental") else "") + - f"fits with {resident_budget_gib(m, ram)} GiB of its experts in RAM, the rest " - "read from the SSD" if ram >= d["ram_gb"] else - f"slow here: {resident_budget_gib(m, ram)} GiB of its " - f"{int(d['arena_gb'] / 1.073741824)} GiB of experts in RAM, the rest read from the SSD " - "(setup asks first)" if ram >= UNSLOTH_MIN_RAM_GB else "does not fit") - elif low_ram_needed(m, ram) and low_ram_fits(m, ram, low_ram_vram(gpu)) and a.low_ram != "off": - verdict = (f"fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, low_ram_vram(gpu)):.0f}% " - "of its experts, " + ("the rest stays in RAM)" if low_ram_resident(m, ram, low_ram_vram(gpu)) - else "the rest is read from the SSD as needed)")) - if d.get("budget") and hip and d.get("nvidia_only"): # #429: not run on AMD yet - verdict += " - NVIDIA only so far, untested on AMD" - if hip and d.get("repo"): # the ready-made NVFP4 packs: no AMD kernels at all - verdict = "NVIDIA only (the AMD engine has no NVFP4 kernels)" - else: - any_fits = any_fits or not verdict.startswith("does not fit") - say(f" {m:8s} needs ~{d['ram_gb']} GB RAM: {verdict}") - for f, fd in FAMILIES.items(): # the families with sizes of their own - for m, d in fd.get("models", {}).items(): - any_fits = any_fits or poly_fits(d, ram, gpu["vram_gb"], hip) - say(f" {fd['title']} {m}: {poly_verdict(d, ram, gpu['vram_gb'], hip, bool(fd.get('windows')))}") - if not any_fits: - # #977: every size says "does not fit", so the verdict says so too (and the exit code, for scripts). It only - # reports: --model NAME --yes still installs one anyway. - say(f"\nThis PC cannot run PolyStrata yet: no model size fits {ram:.0f} GB of RAM (the smallest needs about " - f"{need} GB). --model NAME --yes installs one anyway, slowly.") - return 1 - say("\nThis PC can run PolyStrata. Run it again without --check to install.") - return 0 - - # ---- 2. the questions - step(2, "your choices") - fams = menu_families(hip) - if a.family: - family = a.family - else: - rec_fam = STRIX_HALO_FAMILY if strix_halo_recommends(gpu, ram) and STRIX_HALO_FAMILY in fams else fams[0] - for i, f in enumerate(fams, 1): - d = FAMILIES[f] - say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}" + (" [experimental]" if d.get("experimental") else "") - + family_menu_note(f, hip, gpu, avx2, avx512) - + (f" (recommended for Strix Halo: {STRIX_HALO_MODEL})" if f == rec_fam and rec_fam != fams[0] else "")) - for j, f in enumerate(OWN_PATH_FAMILIES, len(fams) + 1): # families with an engine path of their own - d = OWN_PATH_FAMILIES[f] - say(f" {j}) {d['title']:20s} {d['by']} - {d['about']} [new]") - allf = fams + list(OWN_PATH_FAMILIES) - family = allf[int(ask("Which model?", [str(i) for i in range(1, len(allf) + 1)], - str(allf.index(rec_fam) + 1), a.yes)) - 1] - if family in OWN_PATH_FAMILIES: # Qwen3.6: its own engine path, its own steps 2-7 - return install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted) - fam = FAMILIES[family] - if fam.get("ready") and hip: - # not a risk the user could take: the HIP engine has no NVFP4 expert kernels at all, so it would not start - fail(f"{fam['title']} runs on NVIDIA cards only: the AMD engine has no NVFP4 kernels", - "UD-IQ4_XS is about the same size and runs on AMD: --family unsloth --model UD-IQ4_XS") - if fam.get("ready") and a.gguf_dir: - warn(f"--gguf-dir does not apply to {fam['title']}: its files are ready-made packs, not GGUF shards") - a.gguf_dir = None - ok(f"model: {fam['title']}") - if fam.get("ready") and nvfp4_cpu_note(avx2, avx512): # #2347: a note (the AVX2 rows work), not a refusal - warn(nvfp4_cpu_note(avx2, avx512)) - if fam.get("license"): - say(f" Its license: {fam['license']}") - if fam.get("engine") == "poly": # another engine: its own questions and steps - return poly_setup(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, port, adopted) - say() - names = [m for m in MODELS if family in MODELS[m].get("families", ("qwen", "swift"))] - names.sort(key=lambda m: bool(MODELS[m].get("experimental"))) # an experimental size last, never the default - if a.model and a.model not in names: - # #444: say which family has that size, and (with --gguf-dir) which files PolyStrata can run at all - elsewhere_fams = [f for f in FAMILIES if a.model in family_models(f)] - fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names) - + (f" (or {a.model}: " + ", ".join(f"--family {f} --model {a.model}" for f in elsewhere_fams) + ")" - if elsewhere_fams else "") - + (f".\n {SUPPORTED_GGUFS}" if a.gguf_dir else "")) - installed = installed_size(family, names, have) - for i, m in enumerate(names, 1): - d = MODELS[m] - fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" - if d.get("budget"): - keeps = (f"~{resident_budget_gib(m, ram)} GB" if unsloth_budget(m, ram, gpu, a.resident_budget_gib) - else "all") - say(f" {i}) {m}{size_tag(family, m, installed)} {d['about']}; download {d['download_gb']:.0f} GB, keeps {keeps} of its " - f"{d['arena_gb']:.0f} GB of experts in RAM{fit}") - continue - if low_ram_needed(m, ram) and low_ram_fits(m, ram, low_ram_vram(gpu)) and a.low_ram != "off": - fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, low_ram_vram(gpu)):.0f}%, " - + ("the rest in RAM)" if low_ram_resident(m, ram, low_ram_vram(gpu)) else "the rest from the SSD)")) - 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}") - rec = str(names.index(installed or recommended_size(family, names, ram)) + 1) - model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1] - budget, q4_split = None, False - in_budget = bool(MODELS[model].get("budget")) and unsloth_budget(model, ram, gpu, a.resident_budget_gib) - if MODELS[model].get("budget"): - # Unsloth's files: every expert in RAM where they fit with UNSLOTH_RESIDENT_BESIDE_GB beside them (Phase 2, - # unsloth_budget), as ISTA's. Else a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM - # mode (no experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode had no layer split) - # unless the RAM holds the GGUFs and 24 GB more: then several, without the budget, if asked for (#498). #642: - # from RESIDENT_SPLIT_ENGINE several GPUs, when asked for, keep the budget (unsloth_together) - if MODELS[model].get("experimental"): - warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md)" + ( - ": most of its experts are read from the SSD while it answers, so it is several times slower than the " - "2-3-bit models" if in_budget else "") + "; quality checked against llama.cpp") - if hip and MODELS[model].get("nvidia_only"): - # #429 (jkuepker): checked before the 111 GB download. The HIP engine has no prompt kernels for its - # Q4_K / Q5_K experts (STRATA_MMQ_KQUANTS is CUDA-only) and it has not been run on AMD: asked, not refused - confirm_risk(f"{model} has not been run on AMD cards yet: its prompt kernels are NVIDIA-only, so on " - f"{gpu_name(gpu)} long prompts read much more slowly, and it may not work at all", - bool(a.model), a.yes, f"{model} is NVIDIA-only so far", "choose one of the 2-3-bit models, " - f"or --model {model} --yes to try it on AMD anyway", " Try it anyway?") - warn(f"installing {model} on an AMD card, as you chose (please report how it runs)") - if ram < MODELS[model]["ram_gb"]: - have = resident_budget_gib(model, ram) - total = int(MODELS[model]["arena_gb"] / 1.073741824) - confirm_risk(f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB: " - f"it would keep {have} GiB of its {total} GiB of experts in RAM and read the other " - f"{total - have} GiB from the SSD while it answers (single-digit tokens/s on most SSDs), and " - "it may run out of RAM", bool(a.model), a.yes, - f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB", - f"choose a smaller size, or --model {model} --yes to install it anyway", " Install it anyway?") - warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose") - if in_budget: - budget = budget_choice(model, ram, a.resident_budget_gib) - if multi and not unsloth_together(a, model, ram, gpu, chosen): - multi, sel, chosen = [], [gpu["index"]], [gpu] - q4_split = bool(multi) and not resident_split() # #498: on several GPUs without the RAM budget (#642: kept) - if not q4_split: - ok(f"RAM budget: {budget:g} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD") - else: - ok(f"all {MODELS[model]['arena_gb']:.0f} GB of {model}'s experts in RAM (they and " - f"{UNSLOTH_RESIDENT_BESIDE_GB} GiB more fit this PC's {ram:.0f} GB; --resident-budget-gib N keeps only " - "N GiB of them)") - if a.low_ram not in ("auto", "off"): - warn(f"--low-ram {a.low_ram} does not apply to {model}: it always reads part of its experts from the files") - elif a.resident_budget_gib is not None: - 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 " - "the low-RAM mode") - low_ram = low_ram_wanted(model, ram, a.low_ram) - # #642: the engines from RESIDENT_SPLIT_ENGINE run the low-RAM mode on the chosen cards as on one (decided below) - if low_ram and multi and not resident_split() and not low_ram_together(a, model, ram, gpu, chosen): - multi, sel, chosen = [], [gpu["index"]], [gpu] - # (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one - # before RESIDENT_SPLIT_ENGINE, #642) - if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4: - confirm_paging(model, ram, a.low_ram, a.yes, bool(a.model)) - ok(f"size: {model}") - if MODELS[model].get("license"): # the ready-made packs: each size has its own license - say(f" Its license: {MODELS[model]['license']}") - tag = fam["tag"] + model # names of the pack, config and start script - small = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole context - rec_ctx = 32768 if small < 14 else 65536 if small < 20 else 131072 - if budget is not None: # UD-Q4_K_XL: every GB of KV is a GB fewer of cached experts - rec_ctx = 8192 if small < 14 else 32768 - # #406: the RAM rule is part of the recommendation (the smaller of the two), no longer a cap over the user's choice - rec_ctx = min(rec_ctx, ram_ctx(model, ram, low_ram)) - if a.context: - ctx = a.context - else: - say() - say(" Context length = how much text the model can see at once (your chat, files, tool output).") - say(" Longer needs more VRAM for it, so fewer experts fit on the GPU:") - for i, c in enumerate(CONTEXTS, 1): - need_c = ctx_ram_need(model, c, low_ram) - note = (" (recommended for your GPU)" if c == rec_ctx else "") + \ - (" (experimental: setup adds rope scaling)" if c > 262144 else "") + \ - (f" (needs ~{need_c:.0f} GB RAM, this PC has {ram:.0f}: may run out of memory)" - if c > 131072 and need_c is not None and need_c > ram else "") - say(f" {i}) {c // 1024}K tokens{note}") - ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(CONTEXTS) + 1)], - str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] - # #406 #364: a context past the RAM rule (an explicit --context, a pick in the list, or the earlier install's) is - # kept, with what it risks. It used to become 128K: users ran 256K fine where setup's estimate said no. - need_gb = ctx_ram_need(model, ctx, low_ram) - if need_gb is not None and ram < need_gb and ctx > 131072: - warn(f"{ctx // 1024}K with {model} needs ~{need_gb:.0f} GB of RAM by setup's estimate " - f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest); this PC has " - f"{ram:.0f}. Kept as you chose: it may be slower or run out of RAM under load. {rec_ctx // 1024}K is the " - "recommended size.") - scaling = a.rope_scaling - if ctx > 262144 and scaling is None and not a.yes: - # the interactive path: one question, yarn preselected (llama.cpp's extension method, recall-tested - # here at 512K). With --yes nothing prints: resolve_rope takes yarn below and the ok() line says so. - say() - say(f" A {ctx // 1024}K context runs the model past its trained 262,144 positions: the rotary angles") - say(" get rescaled (llama.cpp's RoPE extension). yarn keeps the trained angles on the high-frequency") - say(" pairs and corrects the magnitudes; linear shrinks every angle. Override any time with") - say(" --rope-scaling.") - scaling = ask("RoPE extension method?", ["yarn", "linear"], "yarn", a.yes) - try: - scaling, rope_scale = resolve_rope(ctx, scaling, a.rope_scale) - except ValueError as e: - fail(str(e)) - if scaling is not None: - origin = ("final context / trained 262144; override with --rope-scale" if a.rope_scale is None - else "as requested") - ok(f"rope scaling: {scaling}, factor {rope_scale:g} ({origin})") - ok(f"context: {ctx} tokens") - # the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21) - kv = "fp16" if ctx <= 8192 else (a.kv or "int8") - if ctx > 8192 and not a.kv and not a.yes: - say() - say(" KV cache precision (the model's memory of the conversation):") - say(" 1) 8-bit (recommended: what every published number was measured with)") - say(" 2) 4-bit half the memory (about 4% faster at 128K), but measurably less precise on long") - say(" documents; long-context lookups (needle tests) still pass") - kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1] - if ctx > 8192: - ok(f"KV cache: {'8-bit' if kv == 'int8' else '4-bit (Hadamard-rotated)'}") - if MODELS[model].get("vision", fam.get("vision")) is False: # UD-IQ4_XS: images, unlike UD-Q4_K_XL - vision = "none" - if a.vision not in (None, "no", "none"): - warn(f"images are not available with {model} yet: off") - elif hip: - # MODEL-UPDATE: Unsloth's files on AMD (Linux) read images with the CPU encoder by default where their experts - # all stay in RAM (it takes no VRAM; measured on an R9700 with UD-Q4_K_XL and UD-Q5_K_XL, docs/QUANTS.md) - vision = hip_vision(a.vision if a.vision is not None or not unsloth_images_default(model, family, ram, gpu) - else "cpu") - elif a.vision: - vision = flash_vision_encoder(a.vision, gpu) if a.vision != "no" else "none" - vision = "none" if vision in ("no", "none") else vision - else: - small = 0 < float(gpu.get("vram_gb") or 0.0) < IMAGES_GPU_ENCODER_MIN_VRAM_GB - say() - say(" Images: the model can also read pictures (screenshots, photos, scanned pages). This adds a 0.9 GB") - if small: - say(" download. On a card under 24 GB the encoder runs on the CPU (a few seconds per picture, nothing taken") - say(" from the GPU, pictures read at up to 300 tokens; --vision-tokens 1024 for more detail): the GPU") - say(" encoder keeps ~1.4 GB of VRAM free, which costs 3-5% of text speed on 16 GB cards (measured) and") - say(" more on some PCs. --vision gpu if you want pictures in under a second.") - else: - say(" download and keeps ~1.4 GB of VRAM free for the image encoder, so text is a few % slower.") - # MODEL-UPDATE: on by default for Unsloth's files on a card with room for the encoder (16 GB and more) - default = "y" if unsloth_images_default(model, family, ram, gpu) else "n" - vision = flash_vision_encoder("yes", gpu) if ask("Do you want images?", ["y", "n"], default, a.yes) == "y" else "none" - ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) - if vision != "none" and MODELS[model].get("vision_untested"): - warn(f"images with {model} are untested: users report them working, but we have not run this file with " - "images (#967); tell us if the answers look wrong") - # The low-RAM mode's two variants. resident: the experts the GPU's cache does not hold (and, as far as RAM allows, - # the ones the prompt path borrows cache room from) are copied from the pack's experts.bin into RAM once, so - # nothing is read from the SSD while it answers (engine 0.1.30, --resident-experts; the engine falls back to mmap - # with a warning when they do not fit the RAM it finds free). mmap: they are read through the OS file cache. - # The GPU's share: its VRAM less the dense weights and buffers, this context's KV cache and the image encoder's room. - resident = False - if low_ram and not fam.get("ready"): # NVFP4's packs: the RAM-budget mode instead (step 7) - arena = MODELS[model]["arena_gb"] - vram = low_ram_vram(gpu) - (VISION[vision]["reserve_mib"] / 1024 if vision != "none" else 0) - share = low_ram_gpu_share(model, vram, ctx, kv) - rest = arena - low_ram_gpu_gb(model, vram, ctx, kv) - resident = a.low_ram == "resident" or (a.low_ram != "mmap" and low_ram_resident(model, ram, vram, ctx, kv)) - if multi: # every chosen card's share (the image encoder on the main one); #364 #384: the mapped variant - held = min(arena, low_ram_gpu_gb(model, vram, ctx, kv) + - sum(low_ram_gpu_gb(model, low_ram_vram(x), ctx, kv) for x in chosen[1:])) - share, rest = held / arena, arena - held - # #642: the resident variant on a split, by the same rule as on one card - what no card holds fits the RAM - resident = resident_split() and (a.low_ram == "resident" or - (a.low_ram != "mmap" and ram >= rest + LOW_RAM_HEADROOM_GB)) - if resident: - ok(f"low-RAM mode on {len(chosen)} GPUs: they hold ~{100 * share:.0f}% of {model}'s experts " - f"({arena:.0f} GB) and the other ~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy " - "in the model folder") - else: - ok(f"low-RAM mode on {len(chosen)} GPUs: {model}'s experts ({arena:.0f} GB) are read from the model " - f"folder through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPUs hold " - f"~{100 * share:.0f}% of them") - if share < 0.6: - warn("most of the experts are read from the SSD while it answers: expect it to be much slower " - "than with enough RAM (a faster SSD and a smaller size help)") - elif resident: - ok(f"low-RAM mode: the GPU holds ~{100 * share:.0f}% of {model}'s experts ({arena:.0f} GB) and the other " - f"~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy in the model folder") - else: - ok(f"low-RAM mode: {model}'s experts ({arena:.0f} GB) are read from the model folder through the OS file " - f"cache instead of a copy in RAM ({ram:.0f} GB); the GPU holds ~{100 * share:.0f}% of them") - if share < 0.6: - warn("most of the experts are read from the SSD while it answers: expect it to be much slower than " - "with enough RAM (a faster SSD and a smaller size help)") - # EXPERIMENTAL: the experimental-speed-projection control vector (data/experimental-speed-projection), off unless - # chosen here; with it loaded, the web app and the API switch it off per request - esp = None - esp_choice = (a.experimental_speed_projection or "").strip() - if family in ("qwen", "coder"): # the Coder: the same model's residual stream - if not esp_choice: - say() - say(" EXPERIMENTAL - speed projection: a small control vector applied while the model runs (layers 4-44).") - say(" It changes how the model answers: its package describes it as a refusal-direction projection (the") - say(" model declines far fewer requests). Off unless you choose it; when on, the web app can switch it off") - say(" per chat. Details: data/experimental-speed-projection/README.md") - esp_choice = "on" if ask("Turn on the experimental speed projection?", ["y", "n"], "n", a.yes) == "y" else "off" - if esp_choice.lower() not in ("off", "no", "n", "0"): - esp = ESP_VECTOR if esp_choice.lower() in ("on", "yes", "y", "1") else Path(esp_choice).expanduser().resolve() - if not esp.is_file(): - fail(f"the experimental speed projection's vector is missing: {esp}") - ok("experimental speed projection: " + ("ON (experimental)" if esp else "off")) - elif esp_choice.lower() not in ("", "off", "no", "n", "0"): - warn("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off" - if family == "swift" else f"the experimental speed projection is not tested with {model}: left off") - ready = bool(fam.get("ready")) # NVFP4: ready-made packs (NVFP4_REPOS), no GGUF shards - if ready: - models_dir = Path(a.models_dir) - for r in elsewhere: # already downloaded and checked in a PolyStrata folder elsewhere - if all(ready_verified(ready_where(r / "models", f), f[5]) for f in ready_files(model)): - models_dir = r / "models" - ok(f"model files found in {models_dir}") - break - shards = [ready_where(models_dir, f) for f in ready_files(model)] - else: - models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag - shards = gguf_dir_shards(models_dir, fam, model) if a.gguf_dir else \ - [models_dir / model_file(fam, model, i) for i in range(1, model_shards(fam, model) + 1)] - problem = gguf_dir_problem(models_dir, shards[0], fam, model) if a.gguf_dir else None - if problem: # #444: files PolyStrata cannot run, or another choice's files - fail(*problem) - if not ready and not a.gguf_dir and not all(sh.exists() and done(sh) for sh in shards): - for r in elsewhere: # already downloaded in a PolyStrata folder on another drive - cand = [r / "models" / tag / sh.name for sh in shards] - if all(c.exists() and done(c) for c in cand): - models_dir, shards = cand[0].parent, cand - ok(f"model files found in {models_dir}") - break - for s in ([] if ready else shards): # #173: a whole file copied in by hand has no finish mark - if s.exists() and not done(s) and whole_shard(s): - try: - mark(s, "whole (checked against its own tensor directory)") - except OSError as e: # a read-only folder (--gguf-dir on a share): the file is still whole - warn(f"{s.name} is whole but its finish mark cannot be written ({e})") - have_model = all(ready_verified(ready_where(models_dir, f), f[5]) for f in ready_files(model)) if ready else \ - all(s.exists() and (done(s) or a.gguf_dir) for s in shards) - # #425 (jctaborda): a download that resumes needs room only for what is still missing - the finished shards and - # the .part files already on the disk count - 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 - to_fetch = 0 if a.gguf_dir or have_model else max(MODELS[model]["download_gb"] - on_disk, 0) - # count only what step 6 will still write: a pack whose experts.bin is already there (the AVX-512 Q2_0 - # conversion, or the low-RAM mode's copy) and an existing MTP draft layer need no new room - pack_now = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() - pack_bin = ready or ((pack_now / "experts.bin").exists() and (pack_now / "index.txt").exists()) # ready: in the download - mtp_have = find_in(roots, "mtp/rt/experts.bin") is not None - q2_avx = model == "Q2_0" and avx512 and family == "qwen" - need = to_fetch + (2 if mtp_have else 8) + \ - (40 if q2_avx and not pack_bin else 0) + (1 if vision != "none" else 0) + \ - (MODELS[model]["arena_gb"] + 1 if low_ram and not q2_avx and not pack_bin else 0) - if free_gb(models_dir) < need: - fail(f"not enough free disk space in {models_dir}: need ~{need:.0f} GB" + - (f" ({on_disk:.0f} GB of the model is already there)" if on_disk >= 1 and not have_model else ""), - "use --models-dir on a bigger drive") - - # ---- 3. python packages - step(3, "Python packages") - pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, - "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") - - # ---- 4. the engine - step(4, "the PolyStrata engine") - llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision) - if ready and meta.get("source") != "local" and \ - tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) < MODELS[model]["engine"]: - # a ready-made engine from before NVFP4 cannot read these experts: one compiled from this source can - warn(f"the ready-made engine {meta.get('version')} has no NVFP4 experts yet: compiling the engine from this source") - eng = build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk) - meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) - lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk) - engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) - need_engine = MODELS[model].get("engine", UNSLOTH_ENGINE) - # checked before the 94-188 GB download - if MODELS[model].get("budget") and engine_ver < need_engine: - fail(f"{model} needs engine {'.'.join(map(str, need_engine))} or newer; this one is {meta.get('version')}", - "update PolyStrata (or compile the engine with --build) and run setup again") - ok(f"engine: {eng / EXE}") - - # ---- 5. the model files - step(5, f"downloading {fam['title']} {model}") - if ready: # pinned files of the pack's repository, each SHA-256-checked - say(f" The model files go in {models_dir / MODELS[model]['repo'].replace('/', '--')}") - if model_source() == "modelscope": - warn("these packs are on Hugging Face only: downloading them from " + hf_endpoint()) - ready_fetch(model, models_dir) - elif not a.gguf_dir: - missing = [s.name for s in shards if not (s.exists() and done(s))] - if missing: # #495: files downloaded by hand go here, or --gguf-dir - say(f" The model files go in {models_dir}") - say(f" Files you already have: put them here with their original names ({', '.join(missing)}), or use " - "--gguf-dir .") - if model_source() == "modelscope": - say(f" Downloading from ModelScope ({ms_endpoint()}); --source huggingface downloads from Hugging Face") - warn("ModelScope serves the repositories' current files, not the pinned revisions: each file is checked " - "against the SHA-256 ModelScope itself publishes (self-attested); the MTP tensors against the " - "pinned checkpoint's own hashes") - elif hf_endpoint() != HF_DEFAULT: - say(f" Downloading from {hf_endpoint()} (HF_ENDPOINT)") - for s in shards: - if s.exists() and done(s): - ok(f"{s.name} already downloaded") - continue - # the original's shard 2 is the same file for all its sizes and the Coder: reuse one that is already here - other = [p for p in Path(a.models_dir).glob("*/Qwen3.8-Flash-Next-GSQ-RCO-*-00002-of-00002.gguf") if done(p)] - if family in ("qwen", "coder") and s.name.endswith("00002-of-00002.gguf") and other and not s.exists(): - try: - os.link(other[0], s) - mark(s) - ok(f"{s.name} shared with {other[0].parent.name} (identical file)") - continue - except OSError: - pass - download(fam["hf"].format(q=model) + s.name, s) - if not ready: - check_shards(shards) - for s in ([] if ready else shards): # the Unsloth files: pinned sizes and SHA-256 - if s.name in fam.get("sha256", {}): - verify_sha256(s, *fam["sha256"][s.name]) - ok("model files present") - mmproj = Path(a.models_dir) / fam.get("mmproj", MMPROJ) - if not mmproj.exists(): # an earlier install's copy (the same file for every family) - mmproj = find_in(roots, f"models/{fam['mmproj']}") or mmproj - if vision != "none": - if not mmproj.exists() and a.gguf_dir and (Path(a.gguf_dir) / fam["mmproj"]).exists(): - mmproj = Path(a.gguf_dir) / fam["mmproj"] - else: - download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder") - if fam.get("mmproj_sha256"): # the NVFP4 family pins it by size and SHA-256 too - verify_sha256(mmproj, *fam["mmproj_sha256"]) - ok(f"vision encoder: {mmproj}") - if vision == "cpu" and "BF16" in mmproj.name: # a tip only (recommend, never force; #625) - say(" tip: on the CPU a Q8_0 copy of this encoder is a third smaller and about as exact (embedding " - "cosine 0.999 vs BF16); see 'A Q8_0 encoder' in docs/DETAILS.md") - - # ---- 6. the pack and the MTP draft layer - step(6, "preparing the model for PolyStrata") - pack = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() - env = dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py")) - if ready: # the downloaded pack folder is the pack, experts.bin included - pack = ready_paths(model, models_dir)["pack"] - elif model == "Q2_0" and avx512 and family == "qwen": - # the Q2_0 experts repacked for the AVX-512 kernel (the measured speed): a one-time ~40 GB conversion - if not (pack / "index.txt").exists() or not (pack / "experts.bin").exists(): # index.txt is written last - say(" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...") - run([sys.executable, str(ROOT / "tools" / "strata_pack.py"), "build", "--gguf", str(shards[0]), - "--out", str(pack), "--skip-hash", "--force"], env=env) # --force: #634 refuses an occupied pack - run([sys.executable, str(ROOT / "tools" / "pack_index.py"), "--pack", str(pack)], env=env) - if not (pack / "tokenizer" / "vocab.json").exists(): - run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(shards[0]), - "--out", str(pack)], env=env) # writes /tokenizer/ - elif not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists(): - # every tensor as the GGUF stores it; the experts are read from the GGUF at start (seconds to build) - # (UD-Q4_K_XL: --compat-bf16 - its Q8_0 hyper-connection projections become BF16, the form the engine reads) - run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), - *fam.get("pack_args", [])], env=env) - if low_ram and not ready and not (pack / "experts.bin").exists(): - say(f" Writing the experts into one file for the low-RAM mode (one time, {MODELS[model]['arena_gb']:.0f} GB) ...") - run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), - "--experts-bin"], env=env) - ok(f"model prepared: {pack}") - mtp = (find_in(roots, "mtp/rt/experts.bin") or data / "mtp/rt/experts.bin").parent.parent - rt = mtp / "rt" - corrupt = (rt / "experts.bin").exists() and mtp_corrupt(mtp, env) - if corrupt: - warn("some MTP tensors are not the checkpoint's (a download mirror that ignored range requests, #327): " - "fetching them again and rebuilding the draft layer") - if corrupt or not (rt / "experts.bin").exists(): - say(" The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:") - say(" only its ~5 GB of MTP tensors are downloaded.") - run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)], - env={**env, "STRATA_SOURCE": model_source()}) - run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0", - "--out", str(mtp / "mtp-q2_0.gguf")], env=env) - run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], - env=env) - # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en) - draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json") - refresh_draft_vocab(rt, draft_vocab or "cjk") - ok(f"MTP draft layer: {rt}") - for line in draft_vocab_note(gpu.get("vram_gb", 0.0), draft_vocab): # #474: a recommendation, nothing changes - say(" " + line) - - # ---- 7. the start script - step(7, "writing the start script") - sys.path.insert(0, str(ROOT / "tools")) - from gguf_reader import GGUFFile # the PLE table's shard: shard 2 (original) or 1 (Swift) - if ready: # the dense GGUF as --native and --native-dense-gguf (--native alone would look for a second shard), - rp = ready_paths(model, models_dir) # the FP8 n-gram table, the BF16 token embedding - ple = rp["ple"] - model_args = ["--pack", str(pack), "--native", str(rp["dense"]), "--native-dense-gguf", str(rp["dense"]), - "--ple-gguf", str(ple), "--embd-gguf", str(rp["embd"])] - else: - ple = next((s for s in shards if any(t.name == "per_layer_token_embd.weight" for t in GGUFFile(s).tensors)), None) - if ple is None: - fail("the model has no per_layer_token_embd tensor (is this a Qwen3.8-Flash-Next GGUF?)") - # (a 4-shard file: the engine finds the PLE table's shard itself from shard 1, the measured setup) - model_args = ["--pack", str(pack), "--native", str(shards[0]), - *(["--ple-gguf", str(ple)] if len(shards) <= 2 else [])] - args = [*model_args, - "--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto", - "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt), - "--max-context", str(ctx)] - if scaling is not None: # the resolved config: explicit flags as given, or the automatic yarn+factor - args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"] - if ctx > 8192: - args += ["--kv", kv] - if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE: - resident = False # an engine from before --resident-experts would refuse it - ok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through " - "the OS file cache (run setup again after the next engine update)") - if low_ram and ready: - # NVFP4 (68 GB of experts) on a PC whose RAM does not hold them: the RAM-budget mode, as Unsloth's files - the - # most-used experts outside VRAM pinned within RAM less 24 GB, the rest read from experts.bin. Mapped - # (--mmap-experts) on a 64 GB Windows PC, the experts it read stayed in the engine's working set: free RAM - # fell to 0.6 GB on the RTX 5070 PC (2026-10-13), where the budget mode kept 22 GB free - rb = resident_budget_gib(model, ram) - args += ["--resident-budget-gib", str(rb)] - ok(f"low-RAM mode: {rb} GiB of {model}'s experts kept in RAM (the most used), the rest read from the pack's " - "experts.bin on the SSD as needed") - elif low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped - args += ["--resident-experts" if resident else "--mmap-experts"] - disk = None if is_wsl() else rotational_disk(ple) # #605 (WSL's virtual disk says rotational) - if disk: - tensor = None if ready else next((t for t in GGUFFile(ple).tensors if t.name == "per_layer_token_embd.weight"), None) - size = ple.stat().st_size if ready else getattr(tensor, "expected_bytes", lambda: None)() - table_gb = size / 1e9 if size else 28.8 - if ram >= MODELS[model]["ram_gb"] + table_gb + 4: - args += ["--ple-io", "ram"] - ok(f"the model is on a rotational disk ({disk}): its {table_gb:.0f} GB n-gram table is kept in RAM " - "(--ple-io ram) - read from the disk at random, it can stall prompts for minutes (#605)") - else: - warn(f"the model is on a rotational disk ({disk}): its n-gram table is read from it at random, which can " - f"stall prompts for minutes (#605). An SSD is recommended; with ~{table_gb:.0f} GB more RAM, " - "--ple-io ram in the config's args keeps the table in RAM instead") - # KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions - # per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It - # costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 10.6 KB with K8V4, 7.5 KB with 4-bit, so only - # when it fits. - kv_ram_gb = kv_streaming_ram_gb(ctx, kv) # the branches below are kv_streaming_wanted, with its messages - # --kv-streaming on|off overrides the RAM test (the owner's rule); WSL stays off - it cannot stream. - stream_fits = ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1 - if is_wsl() and ctx >= 65536: - ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM") - if a.kv_streaming == "on": - warn("--kv-streaming on: WSL cannot stream the KV cache (its RAM copy must be pinned, and the driver pins " - "only about 1 GB there): off") - elif ctx >= 65536 and a.kv_streaming == "off": - ok("KV streaming off, as you chose (--kv-streaming off): the KV cache stays in VRAM") - elif ctx >= 65536 and (stream_fits or a.kv_streaming == "on"): - args += ["--kv-resident", "32768"] - ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM") - if not stream_fits: - warn(f"KV streaming needs ~{kv_ram_gb:.1f} GB of RAM beside the ~{MODELS[model]['ram_gb']} GB {model} " - f"uses; this PC has {ram:.0f}. Kept as you chose (--kv-streaming on): it may page or run out of RAM " - "under load") - if q4_split: # #498: no budget to take it out of - pass - elif budget is not None and a.resident_budget_gib is None: # its RAM comes out of the experts' budget - budget = resident_budget_gib(model, ram, kv_ram_gb) - ok(f"RAM budget: {budget} GiB (less the KV cache's RAM)") - elif budget is not None and budget > resident_budget_gib(model, ram, kv_ram_gb): - warn(f"the KV cache's {kv_ram_gb:.1f} GB of RAM come on top of your {budget:g} GiB RAM budget (setup " - f"would take them out of it: {resident_budget_gib(model, ram, kv_ram_gb)} GiB); kept as you chose") - elif ctx >= 65536: # #620: say why, so a regenerated config that lost --kv-resident is not a surprise - ok(f"KV streaming off: it needs ~{kv_ram_gb:.1f} GB of RAM beside the ~{MODELS[model]['ram_gb']} GB {model} " - f"uses, and this PC has {ram:.0f}; the KV cache stays in VRAM (fewer cached experts). --kv-streaming on " - "turns it on anyway") - elif a.kv_streaming == "on": - warn("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off") - if budget is not None and not q4_split: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N - args += ["--resident-budget-gib", f"{budget:g}"] # GiB kept in RAM (#498: a layer split had no budget) - if gpu.get("uma") and "--expert-cache" in args: - # #1715: the cache and the budget draw on the same RAM: a number that leaves the OS its room, not `auto` - slots = uma_expert_cache(model, ram, budget, kv_ram_gb if "--kv-resident" in args else 0.0) - if slots is not None: - args[args.index("--expert-cache") + 1] = str(slots) - ok(f"expert cache: {slots} slots (not auto): this GPU shares the RAM with the {budget:g} GiB budget, " - f"so setup leaves {UNSLOTH_RAM_LEFT_GB} GB of the RAM for the OS and the desktop (#1715). " - "--expert-cache N in the config's args sets it") - else: - warn(f"this GPU shares the RAM, and the {budget:g} GiB RAM budget leaves almost none for the expert " - "cache: it stays on auto, which may take the room the OS needs (#1715). A smaller " - "--resident-budget-gib leaves room") - if vision != "none": - args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])] - if vision == "gpu" and a.vram_reserve_mib is None and 0 < gpu.get("vram_gb", 0.0) <= 12.5: - # a tip only (recommend, never force): on a 12 GB card the encoder's 700 MiB can leave ~200 MiB free - print(f" tip: images on a {gpu['vram_gb']:.0f} GB card can leave little VRAM free; if a request stalls, " - f"run setup again with --vram-reserve-mib {VISION_GPU_SMALL_RESERVE_MIB}") - if a.vram_reserve_mib is not None: # #493: VRAM left free for other programs (only when given) - if "--vram-reserve-mib" in args: - i = args.index("--vram-reserve-mib") + 1 - if vision == "gpu" and a.vram_reserve_mib < int(args[i]): - warn(f"--vram-reserve-mib {a.vram_reserve_mib}: the image encoder on the GPU needs ~{args[i]} MiB of " - "it; kept as you chose (it may run out of VRAM when it reads a picture)") - args[i] = str(a.vram_reserve_mib) - else: - args += ["--vram-reserve-mib", str(a.vram_reserve_mib)] - ok(f"VRAM kept free for other programs: {a.vram_reserve_mib} MiB (--vram-reserve-mib; the expert cache takes " - "that much less)") - if not multi and family == "unsloth" and 0 < gpu.get("vram_gb", 0.0) <= UD_FIT_CARD_GB: - # a card of about 8 GB: the config setup would write may not start (measured on an A750). Pick the least - # harmful one that fits and say so; what the user chose with --context / --kv / --vram-reserve-mib is kept - res_arg = int(args[args.index("--vram-reserve-mib") + 1]) if "--vram-reserve-mib" in args[:-1] else None - vg = gpu["vram_gb"] - rt_mib = unsloth_runtime_mib(gpu) - fits = unsloth_vram_slack_mib(vg, ctx, kv, UD_FIT_ENGINE_RESERVE_MIB if res_arg is None else res_arg, True, - rt_mib) >= UD_FIT_MIN_SLACK_MIB - plan = None - if not fits: - plan = unsloth_small_card_plan(vg, ctx, kv, res_arg, ctx_fixed=bool(a.context), kv_fixed=bool(a.kv), - runtime_mib=rt_mib) - if plan is not None: - nctx, nkv, nmtp, slack = plan - changes = [] - if nctx != ctx: - args[args.index("--max-context") + 1] = str(nctx) - changes.append(f"context {ctx} -> {nctx}") - ctx = nctx - if nkv != kv: - if "--kv" in args[:-1]: - args[args.index("--kv") + 1] = nkv - else: - args += ["--kv", nkv] - changes.append(f"KV cache {kv} -> {nkv}") - kv = nkv - if not nmtp and "--mtp" in args[:-1]: - i = args.index("--mtp") - del args[i:i + 2] - changes.append("no MTP draft layer on the GPU (about 0.8 GB more for the expert cache; decode is slower)") - warn(f"with the usual settings {model} would not start on this {vg:.0f} GB card (setup's estimate: no VRAM " - "left for the expert cache). Setup chose the least harmful start that fits: " + ", ".join(changes) - + ". A bigger context, 8-bit KV or the draft layer need a card with more VRAM (or " - "--vram-reserve-mib 0, which leaves nothing for other programs).") - for line in unsloth_small_card_lines(model, vg, plan, fits): - warn(line) - if not multi and 0 < gpu.get("vram_gb", 0.0) < SMALL_CARD_GB: - # #496: on a 6 GB card the expert cache can get no room at all; the engine lowers its own reserve when that - # is what it takes, and says what is short when even that is not enough. Setup only says what helps. - for line in small_card_note(ctx, draft_vocab): # a recommendation: nothing changes - say(" " + line) - elif hip and a.vram_reserve_mib is None and linux_desktop(): - for line in desktop_reserve_note(): # #560 #516: a recommendation: nothing changes - say(" " + line) - if not hip and not multi and a.vram_reserve_mib is None and gpu_drives_display(gpu): - say(" tip: this card drives a display. If the PC freezes or the screen goes black once the model is loaded " - f"(#779), keep more VRAM free: run setup again with --vram-reserve-mib {DISPLAY_RESERVE_MIB}") # a tip only - if not hip: - for gi in ([g for g in multi] if multi else [gpu.get("index", 0)]): - gi = gi["index"] if isinstance(gi, dict) else gi - w = compute_mode_warning(gi, gpu_compute_mode(gi)) - if w: - warn(w) # #1445: a warning only, never a refusal - if esp is not None: - # the package's profile, with llama.cpp's flags (the engine takes the same ones) - args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44", - "--cvec-mode", "project", "--cvec-dir", "per-layer"] - cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), - "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"), - "lib_dirs": lib_dirs, "port": port} - if cuda_tk == 12: # the experimental CUDA 12 engine (engine-cuda12/) - cfg["cuda"] = 12 - if (uenv := unsloth_default_env(family, model, hip, in_budget)): - cfg["env"] = uenv - if hip: - cfg["backend"] = "hip" - # the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60% - # prompt speed on the 7900 XTX): only a table for this card's arch AND the installed hipBLASLt version (the - # engine refuses any other one and falls back to plain hipBLAS) - table = hipblaslt_table(gpu["arch"], lib_dirs, meta.get("hipblaslt_version")) - if table: - cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(table)} - if GFX1103_OPT_IN and gfx_arch_is(gpu["arch"], "gfx1103") and not WIN: - # the 780M's KFD queues are evicted (a GPU reset) while transparent huge pages move the pinned expert arena - cfg.setdefault("env", {})["STRATA_NO_ARENA_THP"] = "1" - # the exact gfx1151 speed switches measured on this chip (GFX1103_SWITCHES): the engine has no arch defaults - # for gfx1103, so setup writes them into the config. They are setup's own (SETUP_ENV), so a re-run refreshes - # them and turning the opt-in off takes them out again. - cfg.setdefault("env", {}).update(GFX1103_SWITCHES) - if GFX1150_OPT_IN and gfx_arch_is(gpu["arch"], "gfx1150"): - # the exact gfx1151 speed switches measured on this chip (GFX1150_SWITCHES): the engine has no arch defaults - # for gfx1150, so setup writes them into the config. They are setup's own (SETUP_ENV), so a re-run refreshes - # them and turning the opt-in off takes them out again. - cfg.setdefault("env", {}).update(GFX1150_SWITCHES) - # RDNA2 (gfx103x): the prompt's FP16 GEMMs through rocBLAS's best kernel per shape (tools/hip/tune_rocblas; - # the GDN input projection 6x faster below 1,152 tokens on a 6900 XT). The ids are valid for one rocBLAS - # build, which only the engine can read, so setup points it at the directory and the engine picks the file - # -rocblas-.txt for its own library, or runs the default kernels and says so in its log. - rocblas_tables = sorted(p.name for p in (ROOT / "tools" / "hip").glob(f"{gpu['arch']}-rocblas-*.txt")) - if rocblas_tables: - cfg.setdefault("env", {})["STRATA_ROCBLAS_TUNING"] = str(ROOT / "tools" / "hip") - ok(f"rocBLAS tuning tables for {gpu['arch']}: {', '.join(rocblas_tables)} (the engine takes the one of its rocBLAS build)") - if resident: # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable - cfg.setdefault("env", {})["STRATA_RESIDENT_PIN"] = "0" - if gpu["count"] > 1 or a.gpu is not None: - cfg["gpu"] = gpu["index"] # the engine is told this card (issue #51) - cfg["gpus_asked"] = True # chosen at setup: not asked again at start - if multi: # a layer split across these cards (the server adds the flag) - cfg["gpu"] = multi - cfg["layer_split"] = a.layer_split or "auto" - ok(f"layer split across GPUs {multi} ({cfg['layer_split']})") - recommend_remote_expert_opt(cfg, off=a.no_remote_expert_opt) - if a.replicas is not None and a.replicas >= 2: # data-parallel replicas (serve/replicas.py), opt-in - cards = multi if multi else [] - if not cards or len(cards) % a.replicas: - warn(f"--replicas {a.replicas}: needs the chosen GPUs ({cards or 'one'}) to divide into {a.replicas} equal " - "groups; not set (choose the cards with --gpu 0,1,2,3, or write the groups into the config: " - '"replicas": [{"gpus": [0, 1]}, {"gpus": [2, 3]}])') - else: - cfg["replicas"] = a.replicas - per = len(cards) // a.replicas - ok(f"{a.replicas} replicas of {per} GPU(s) each: {' | '.join(','.join(map(str, cards[i * per:(i + 1) * per])) for i in range(a.replicas))}") - if per > 1 and a.layer_split not in (None, "auto"): - warn("--layer-split is one engine's value; with replicas every group would get it: leave it at auto") - if (os.cpu_count() or 0) < 8 * a.replicas: - warn("each replica loads its own copy of the model into RAM and runs its own host threads: check the RAM") - if a.host: - cfg["host"] = a.host - if a.api_key: - cfg["api_key"] = a.api_key - if draft_vocab: - cfg["draft_vocab"] = draft_vocab - if a.browser is not None: # #609: only when given (else an earlier choice is carried over) - cfg["open_browser"] = a.browser - # #465: requests at once - written only when given (else an earlier "parallel" is carried over); a recommendation - streaming = "--kv-resident" in args - if a.parallel is not None: - if a.parallel >= 2: - cfg["parallel"] = a.parallel - for i, line in enumerate(parallel_note(a.parallel, [g.get("vram_gb", 0.0) for g in chosen], - MODELS[model]["arena_gb"], ctx, kv, streaming)): - (ok if i == 0 else warn)(line) - else: - cfg["parallel"] = 1 - ok("parallel requests: one at a time (--parallel 1)") - if vision != "none": - old_cfg = ROOT / f"strata-{tag.lower()}.json" - vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted) - cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), # the text model, opened vocab-only: - "model": str(ready_paths(model, models_dir)["dense"] if ready else shards[0]), - "gpu": vision == "gpu", "max_tokens": vt} - if vision == "cpu": - cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) - elif a.vision_tokens is not None: - warn("--vision-tokens: images are off for this model, so it is not used") - if a.images: # only when given: else an earlier "images" is carried over - cfg["images"] = setup_images(a, gpu, hip, Path(a.models_dir)) - cfg_path = ROOT / f"strata-{tag.lower()}.json" - cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA only - if cal is not None: - sys.path.insert(0, str(ROOT / "tools")) - import calibrate as CAL - cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) - if "env" in cal: # a calibration from before the env step leaves "env" as it is - cfg["env"] = CAL.apply_env(cfg.get("env"), cal["env"]) - ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) - else: # #642: measured counts (a calibration) win over the rule - cfg["args"] = recommend_pool_workers(cfg["args"]) - for line in two_socket_note(cpu_sockets()): # bench tips: text only, the config is not touched - say(" " + line) - for line in bench_tips(cfg["args"], cfg.get("env"), ram, MODELS[model]["ram_gb"], gpu.get("vram_gb", 0.0), vision, WIN): - say(" " + line) - write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) - script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) - # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it - if cal is None and not hip and not a.no_start and not a.yes and ask( - "Tune PolyStrata for this PC now? It measures a few engine settings (about 15-30 minutes, longer on a slow card; the PC is busy " - "meanwhile; later: START-HERE --calibrate)", ["y", "n"], "y", a.yes) == "y": - tuned = calibrate_config(cfg_path) - else: - tuned = None # not asked for: nothing to repeat below - ok(f"start script: {script.name}") - - say() - say("All set.") - say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") - say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") - if a.host and a.host not in ("127.0.0.1", "localhost"): - say(f" Other devices: the server window prints this PC's address (http://:{port}/)" - + ("" if a.api_key else " - no API key set: anyone on your network can use it")) - say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") - if vision != "none": - say(" Images: send them in the chat page, in chat.py (/image ) or over the API") - if cfg.get("images"): - say(f" Image generation: POST http://127.0.0.1:{port}/v1/images/generations (OpenAI's images API)") - if a.parallel is None: # #465: the opt-in, said once (nothing changes) - for line in parallel_note(None, [g.get("vram_gb", 0.0) for g in chosen], MODELS[model]["arena_gb"], ctx, kv, - "--kv-resident" in cfg["args"]): - say(" " + line) - if tuned is False: # #447: a failed tuning is repeated here, not only above - say(" Tuning: FAILED (the reason is above): the default settings stay - " - f"{'START-HERE.bat' if WIN else './setup.sh'} --calibrate tries again") - if a.no_start: - return 0 - # offered only when someone answers (--yes asks nothing), default no; the benchmark starts its own server and stops it - if not a.yes and sys.stdin.isatty() and ask( - "Run a quick benchmark now? It measures this install for about 10 minutes and writes a report you can share " - f"(later: {'BENCH.bat' if WIN else './bench.sh'})", ["y", "n"], "n", a.yes) == "y": - subprocess.call([sys.executable, str(ROOT / "tools" / "strata_bench.py"), "--config", str(cfg_path), "--port", str(port)]) - return start(cfg_path, port) - - -if __name__ == "__main__": - try: - sys.exit(main()) - except KeyboardInterrupt: - say("\nstopped.") - sys.exit(1) diff --git a/setup.sh b/setup.sh deleted file mode 100755 index e4d5677..0000000 --- a/setup.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/sh -# PolyStrata for Linux: the first run installs everything and starts the model; later runs just start it. -# Needs only an NVIDIA driver (or, for an AMD Radeon card, the kernel's amdgpu driver: see docs/AMD_HIP.md). -# Python (with venv) is installed through apt/dnf if it is missing (asks for sudo). -# NixOS (or STRATA_UV=1) with uv installed: uv makes the project venv; every other Linux uses the standard venv. -cd "$(dirname "$0")" || exit 1 -# Python 3.10+ that can make a venv WITH pip: Debian/Ubuntu ship `venv` without `ensurepip` (that is the separate -# python3-venv package), and a venv made without it has no pip -ok_py() { "$1" -c 'import sys, venv, ensurepip; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; } -# a .venv from an earlier run that failed half-way has a python but no pip: start it again -if [ -x .venv/bin/python ] && ! .venv/bin/python -m pip --version >/dev/null 2>&1; then - rm -rf .venv -fi -if [ ! -x .venv/bin/python ]; then - # uv's own Python only on NixOS (its Python cannot load pip wheels' libraries), or when asked: STRATA_UV=1. - # Everywhere else the standard venv stays the default (#662: a silent toolchain change was not wanted). - UV="" - if [ "${STRATA_UV:-}" = "1" ] || grep -qi '^ID=nixos' /etc/os-release 2>/dev/null; then - UV="$(command -v uv 2>/dev/null || true)" - fi - PY="" - if [ -n "$UV" ]; then - # Prefer uv's own interpreter: unlike Nix's Python, it works naturally with pip wheels using dlopen. - PY=3.12 - else - for c in python3 python; do - if command -v $c >/dev/null 2>&1 && ok_py $c; then - PY=$c; break - fi - done - fi - # macOS: the system Python is 3.9; a standalone Python 3.12 goes into .python (no sudo, no Homebrew; pinned) - if [ -z "$PY" ] && [ "$(uname -s)" = Darwin ]; then - if [ ! -x .python/python/bin/python3 ]; then - PBS="https://github.com/astral-sh/python-build-standalone/releases/download/20261009/cpython-3.12.15%2B20261009-aarch64-apple-darwin-install_only.tar.gz" - echo "Python 3.10+ is needed; downloading a standalone Python 3.12 into .python (25 MB) ..." - mkdir -p .python && curl -fL --retry 3 -o .python/python.tar.gz "$PBS" || { echo "could not download Python"; exit 1; } - if [ "$(shasum -a 256 .python/python.tar.gz | cut -d" " -f1)" != "83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8" ]; then - rm -f .python/python.tar.gz; echo "the Python download does not match its pinned SHA-256"; exit 1 - fi - tar xzf .python/python.tar.gz -C .python && rm -f .python/python.tar.gz - fi - PY=.python/python/bin/python3 - fi - if [ -z "$PY" ]; then - echo "Python 3.10+ with venv is needed; installing it (sudo will ask for your password) ..." - if command -v apt-get >/dev/null 2>&1; then - sudo apt-get update && sudo apt-get install -y python3 python3-venv python3-pip - elif command -v dnf >/dev/null 2>&1; then - sudo dnf install -y python3 python3-pip - elif command -v pacman >/dev/null 2>&1; then - sudo pacman -S --noconfirm python python-pip - fi - PY=python3 - if ! ok_py $PY; then - echo "Please install Python 3.10 or newer with venv (Ubuntu/Debian: sudo apt install python3-venv), then run" - echo "./setup.sh again. On NixOS, add uv to environment.systemPackages." - exit 1 - fi - fi - if [ -n "$UV" ]; then - # Force an uv-managed interpreter: pip wheels may dlopen libraries outside the Nix store. - "$UV" venv --managed-python --seed --python "$PY" .venv || { echo "Could not create the uv environment in .venv."; exit 1; } - else - # a private environment inside this folder (system Python stays untouched; newer distros refuse global pip) - $PY -m venv .venv || { rm -rf .venv; echo "could not create .venv: sudo apt install python3-venv"; exit 1; } - fi -fi -exec .venv/bin/python setup.py "$@" diff --git a/tools/hip/package_windows.py b/tools/hip/package_windows.py deleted file mode 100644 index fe32d04..0000000 --- a/tools/hip/package_windows.py +++ /dev/null @@ -1,173 +0,0 @@ -#!/usr/bin/env python3 -"""Package the Windows HIP engine as the ready-made zip setup.py downloads (strata-windows-x64-hip.zip). - - python tools/hip/package_windows.py --build build-hip-win --rocm \\ - --archs "gfx1100;gfx1201" --rocm-version 10.2.0a20260930 --out dist - -tools/hip/build_windows.bat runs it after the build. The zip holds: - - strata.exe, strata-device.exe, BUILD.json (backend "hip", the archs, the ROCm and hipBLASLt versions) - amdhip64_7.dll, amd_comgr.dll + what they import the HIP runtime beside the exes too (#468 #461: before System32) - rocm/bin/*.dll the ROCm DLLs the two programs load (their import tables, followed - through the ROCm DLLs, + amd_comgr.dll, which the HIP runtime loads - by name) and the Microsoft C++ runtime they import - rocm/bin/rocblas/library, rocm/bin/hipblaslt/library the GEMM kernels, for these archs only - rocm/.kpack/ rocBLAS's own device code for these archs (rocblas.dll finds it at - ../.kpack from its folder) - rocm/licenses/ the shipped components' licenses, and NOTICE.txt - -setup.py puts rocm/bin first on the engine's PATH (the config's lib_dirs). The AMD display driver (AMD Software: -Adrenalin Edition) is the only thing the user installs: TheRock's HIP runtime runs on top of it. -""" -from __future__ import annotations - -import argparse -import json -import os -import re -import shutil -import subprocess -import sys -import zipfile -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -ASSET = "strata-windows-x64-hip.zip" -PROGRAMS = ("strata.exe", "strata-device.exe") -DYNAMIC = ("amd_comgr.dll",) # LoadLibrary'd by amdhip64_7.dll: not in any import table -CRT = ("msvcp140.dll", "msvcp140_1.dll", "msvcp140_2.dll", "vcruntime140.dll", "vcruntime140_1.dll") -KPACKS = ("blas_lib",) # rocblas.dll's own device code; rocSOLVER's (27 MB per arch) is never launched by PolyStrata -LICENSES = ("rocblas", "rocsolver", "hipblas", "hipblas-common", "hipblaslt", "amd_comgr", "rocm-core") -NOTICE = """PolyStrata's Windows HIP engine ships these AMD ROCm components unmodified, from AMD's TheRock Python wheels -(ROCm {rocm}, https://nightly.repo.amd.com/rocm/whl-next/, built from https://github.com/ROCm/TheRock): - -{dlls} - -Licenses: rocBLAS, hipBLAS, hipBLAS-common, hipBLASLt (and its TensileLite host and origami libraries), rocm-core: MIT; -rocSOLVER: BSD 2-clause; amd_comgr: Apache 2.0 with LLVM exceptions (files in this folder). The HIP runtime -(amdhip64_7.dll, https://github.com/ROCm/rocm-systems/tree/develop/projects/clr) and rocm_kpack.dll (TheRock) are MIT -licensed; their wheels carry no license file. The Microsoft Visual C++ runtime DLLs (msvcp140*.dll, -vcruntime140*.dll) are redistributable under the Visual Studio license (Distributable Code). -""" - - -def imports(objdump: Path, dll: Path) -> list[str]: - text = subprocess.run([str(objdump), "-p", str(dll)], capture_output=True, text=True, check=True).stdout - return [m.group(1) for m in re.finditer(r"DLL Name:\s*(\S+)", text)] - - -def crt_dir() -> Path | None: - """The MSVC redist folder with the C++ runtime DLLs (vcvars sets VCToolsRedistDir).""" - base = os.environ.get("VCToolsRedistDir") - if not base: - return None - hits = sorted(Path(base, "x64").glob("Microsoft.VC*.CRT")) - return hits[-1] if hits else None - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--build", required=True, type=Path) - ap.add_argument("--rocm", required=True, type=Path, help="the ROCm root (rocm-sdk path --root)") - ap.add_argument("--archs", required=True, help="the archs the engine was compiled for, ';'-separated") - ap.add_argument("--rocm-version", required=True) - ap.add_argument("--out", required=True, type=Path) - a = ap.parse_args() - archs = [x for x in re.split(r"[;, ]+", a.archs) if x] - rbin = a.rocm / "bin" - objdump = a.rocm / "lib" / "llvm" / "bin" / "llvm-objdump.exe" - stage = a.out / "strata-windows-x64-hip" - shutil.rmtree(stage, ignore_errors=True) - (stage / "rocm" / "bin").mkdir(parents=True) - - for p in PROGRAMS: - shutil.copy2(a.build / p, stage / p) - - # the ROCm DLLs: the programs' imports, followed through the ROCm DLLs themselves - rocm_dlls = {p.name.lower(): p for p in rbin.glob("*.dll")} - need, todo, crt = [], [stage / p for p in PROGRAMS] + [rbin / d for d in DYNAMIC], set() - while todo: - f = todo.pop() - for name in imports(objdump, f): - low = name.lower() - if low in CRT: - crt.add(low) - elif low in rocm_dlls and low not in need: - need.append(low) - todo.append(rocm_dlls[low]) - for d in DYNAMIC: - if d not in need: - need.append(d) - for d in sorted(need): - shutil.copy2(rocm_dlls[d], stage / "rocm" / "bin" / rocm_dlls[d].name) - cdir = crt_dir() - if cdir is None: - sys.exit("VCToolsRedistDir is not set: run this from a Visual Studio x64 developer prompt (vcvars64.bat)") - for d in sorted(crt): - shutil.copy2(cdir / d, stage / "rocm" / "bin" / d) - # #468 #461: the HIP runtime (and the compiler it loads by name) next to the exes as well - Windows searches the - # exe's folder before System32, where an AMD driver may install its own amdhip64_7.dll (found before PATH's - # rocm/bin); rocBLAS/hipBLASLt stay in rocm/bin, which they resolve their kernel libraries and ../.kpack from - # #461: and everything those two import (amdhip64_7.dll needs rocm_kpack.dll and the C++ runtime, or its full-path - # load fails with error 126 and Windows falls back to System32's copy): the closure of their PE import tables - sys.path.insert(0, str(Path(__file__).resolve().parent)) - from dll_closure import dll_closure - roots = sorted(f.name for pat in ("amdhip64_*.dll", "amd_comgr*.dll") for f in (stage / "rocm" / "bin").glob(pat)) - for name in dll_closure(stage / "rocm" / "bin", roots): - shutil.copy2(stage / "rocm" / "bin" / name, stage / name) - - # the GEMM kernels and the libraries' own device code, for these archs - lib = stage / "rocm" / "bin" / "rocblas" / "library" - lib.mkdir(parents=True) - for f in (rbin / "rocblas" / "library").iterdir(): - m = re.search(r"gfx[0-9a-f]+", f.name) - if m is None or m.group() in archs: - if f.is_dir(): # the gfx1151 wheel keeps its rocBLAS kernels in library/gfx1151/ - shutil.copytree(f, lib / f.name) - else: - shutil.copy2(f, lib / f.name) - for arch in archs: - src = rbin / "hipblaslt" / "library" / arch - if src.is_dir(): # hipBLASLt has no RDNA2 (gfx1030) kernels - shutil.copytree(src, stage / "rocm" / "bin" / "hipblaslt" / "library" / arch) - kp = stage / "rocm" / ".kpack" - kp.mkdir() - kpack_src = a.rocm / ".kpack" - for arch in archs: - for k in KPACKS: - f = kpack_src / f"{k}_{arch}.kpack" - if not f.exists(): - sys.exit(f"missing {f}: install the rocm-sdk-device-{arch} wheel and run rocm-sdk init") - shutil.copy2(f, kp / f.name) - - lic = stage / "rocm" / "licenses" - lic.mkdir() - for comp in LICENSES: - for f in (a.rocm / "share" / "doc" / comp).glob("LICENSE*"): - shutil.copy2(f, lic / f"{comp}-{f.name}") - shipped = sorted(p.name for p in (stage / "rocm" / "bin").glob("*.dll")) - (lic / "NOTICE.txt").write_text(NOTICE.format(rocm=a.rocm_version, dlls="\n".join(" " + d for d in shipped)), - encoding="utf-8") - - version = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8")).group(1) - hl = (a.rocm / "include" / "hipblaslt" / "hipblaslt-version.h").read_text(encoding="utf-8") - hlv = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", hl).group(1)) for k in ("MAJOR", "MINOR", "PATCH")] - meta = {"source": "prebuilt", "backend": "hip", "platform": "windows-x64", "version": version, "archs": archs, - "rocm": a.rocm_version, "hipblaslt_version": hlv[0] * 100000 + hlv[1] * 100 + hlv[2], "vision": "none", - "lib_dirs": ["rocm/bin"]} - (stage / "BUILD.json").write_text(json.dumps(meta, indent=1), encoding="utf-8") - - z = a.out / ASSET - z.unlink(missing_ok=True) - with zipfile.ZipFile(z, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as f: - for p in sorted(stage.rglob("*")): - if p.is_file(): - f.write(p, p.relative_to(stage).as_posix()) - size = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file()) - print(f"{z}: {z.stat().st_size / 2**20:.0f} MiB ({size / 2**20:.0f} MiB unpacked), engine {version}, " - f"{', '.join(archs)}, ROCm {a.rocm_version}, DLLs: {', '.join(shipped)}") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/image/install.py b/tools/image/install.py deleted file mode 100644 index d0dba98..0000000 --- a/tools/image/install.py +++ /dev/null @@ -1,101 +0,0 @@ -"""tools/image/install.py - image generation (Qwen-Image-2.1-Turbo) for an existing PolyStrata install, or on its own: -compiles sd-cli for the backend (setup.py's build_image_engine), downloads and checks the three model files, and -writes the "images" section into a run config (or prints it). setup.py --images qwen-image does the same inside -the normal setup; this is the way to add it without running the whole setup again. - - python tools/image/install.py --config strata-q2_0.json (backend and size picked for this PC) - python tools/image/install.py --backend vulkan --quant Q8_0 --models-dir ~/models --print - python tools/image/install.py --backend hip --arch gfx1103 --build-only - ---gpu-policy auto|keep|shrink|unload: what the text model does during an image job (serve/images.py). -""" -from __future__ import annotations - -import argparse -import json -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -sys.path.insert(0, str(ROOT / "tools" / "image")) -import qimage as QI # noqa: E402 - - -def detect_gpu(S) -> tuple[dict | None, bool]: - """setup.py's view of this PC's GPU: (gpu dict, AMD?) - an NVIDIA card first, else an AMD one, else none.""" - try: - g = S.gpu_info() - if g: - return {**g, "vendor": "nvidia"}, False - except Exception: # noqa: BLE001 - no NVIDIA driver - pass - try: - amd = S.amd_gpus_win() if S.WIN else S.amd_gpus() - if amd: - g = min(amd, key=S.amd_rank) - return S.amd_apply_uma(dict(g)), True - except Exception: # noqa: BLE001 - pass - return None, False - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--backend", choices=QI.BACKENDS) - ap.add_argument("--arch", help="the GPU architecture to compile for (CUDA: 86, ...; HIP: gfx1103, ...)") - ap.add_argument("--quant", choices=QI.QUANTS) - ap.add_argument("--gpu-gb", type=float, help="the GPU memory the quant is picked for (default: detected)") - ap.add_argument("--models-dir", help="where the model files go (default: the data folder's models)") - ap.add_argument("--config", help="a run config (strata-.json) to write the \"images\" section into") - ap.add_argument("--gpu-policy", choices=["auto", "keep", "shrink", "unload"], default="auto") - ap.add_argument("--gpu", type=int, help="the GPU's number for the image job (default: the backend's first)") - ap.add_argument("--native", choices=["on", "off"], default="off", - help="EXPERIMENTAL: PolyStrata's own DiT runner on CUDA / HIP (the config's \"native\")") - ap.add_argument("--build-only", action="store_true", help="compile sd-cli only") - ap.add_argument("--print", action="store_true", help="print the images section instead of writing it") - ap.add_argument("--yes", action="store_true") - a = ap.parse_args(argv) - import setup as S - gpu, amd = detect_gpu(S) if not (a.backend and (a.arch or a.backend in ("vulkan", "cpu"))) else (None, False) - gpu = dict(gpu or {}) - if a.arch: - gpu["arch"] = a.arch - if a.gpu_gb is not None: - gpu["vram_gb"] = a.gpu_gb - ns = argparse.Namespace(images="qwen-image", image_backend=a.backend, image_quant=a.quant, - image_gpu_policy=a.gpu_policy, yes=a.yes) - backend, quant, gb = S.image_backend_choice(ns, gpu or None, amd or a.backend == "hip") - if backend in ("cuda", "hip") and not gpu.get("arch"): - S.fail(f"the {backend} build needs the GPU's architecture", "pass --arch (e.g. 86 or gfx1103)") - S.ok(f"image generation: {quant} on {backend}" + (f" ({gb:.0f} GB GPU memory)" if gb else "")) - exe, lib_dirs = S.build_image_engine(backend, gpu) - if a.build_only: - return 0 - if a.models_dir: - models = Path(a.models_dir).expanduser() - else: - data, _ = S.data_folder(None) - models = data / "models" - S.say(" " + QI.LICENSE_NOTE) - for name in (quant, "vae", "llm"): - repo, path, size, sha = QI.FILES[name] - dst = QI.local_path(models, name) - S.download(QI.file_url(name, S.hf_endpoint()), dst, f"image model: {Path(path).name}") - S.verify_sha256(dst, size, sha) - section = QI.image_config(backend, quant, exe, models, uma=QI.is_apu(gpu), gpu=a.gpu, lib_dirs=lib_dirs, - policy=a.gpu_policy, native=a.native == "on") - if a.print or not a.config: - print(json.dumps({"images": section}, indent=1)) - return 0 - path = Path(a.config) - cfg = json.loads(path.read_text(encoding="utf-8-sig")) if path.is_file() else {} - cfg["images"] = section - S.write_config(path, cfg) - S.ok(f"{path.name}: image generation added (POST /v1/images/generations once the server starts again)") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/image/qimage.py b/tools/image/qimage.py deleted file mode 100644 index 07c2aea..0000000 --- a/tools/image/qimage.py +++ /dev/null @@ -1,203 +0,0 @@ -"""tools/image/qimage.py - Qwen-Image-2.1-Turbo for PolyStrata's image endpoint: stable-diffusion.cpp (sd-cli) at a pinned -commit, built for this PC's GPU, and the model's three files at pinned Hugging Face revisions. - -setup.py (--images qwen-image) and tools/image/install.py use these pieces; serve/images.py runs the result. - - backend CUDA on an NVIDIA card, HIP on an AMD card with its own memory (Linux), Vulkan on an APU/iGPU (AMD's shared - memory: the HIP path's queue evictions reset a 780M on current firmware, NEW-MODELS-PLAN.md section 4), - on Intel and on AMD under Windows; CPU without a GPU. --image-backend picks another. - files the denoiser (DiT) quant by the GPU's memory: Q4_K_M up to 8 GB, Q6_K up to 12 GB, Q8_0 above (Unsloth's - LPIPS vs bf16: 0.153 / 0.055 / 0.036); the VAE (bf16); the Qwen3-VL-8B text encoder UD-Q4_K_XL (the - model card's choice). Each file is checked against the SHA-256 the Hugging Face API lists for it at the - pinned revision. - defaults 8 steps, CFG 1, euler, Turbo's own sigmas (serve/images.py), --diffusion-fa; on Vulkan also --vae-tiling - (an untiled 1024x1024 VAE decode is one dispatch long enough to trip the amdgpu job timeout on a 780M) - with --vae-tile-overlap 0.25. -""" -from __future__ import annotations - -import os -import shutil -import zipfile -from pathlib import Path - -SD_CPP_COMMIT = "2988060a4338a5dcd94721c964a8e87003c1ac8b" # "add TAEQI2.1 support for Qwen Image 2.1" (#2123) -SD_GGML_COMMIT = "d25b121ce1d6ae0c7e62ad080460d9fc1e46dd93" # its ggml submodule (leejet/ggml) -SD_CPP_ZIP = f"https://github.com/leejet/stable-diffusion.cpp/archive/{SD_CPP_COMMIT}.zip" -SD_GGML_ZIP = f"https://github.com/leejet/ggml/archive/{SD_GGML_COMMIT}.zip" - -# the LunarG Vulkan SDK for a Linux PC without Vulkan development files (headers, glslc): unpacked into third_party, -# no sudo; the version the 780M builds were made with -VULKAN_SDK_VERSION = "1.4.363.0" -VULKAN_SDK_URL = (f"https://sdk.lunarg.com/sdk/download/{VULKAN_SDK_VERSION}/linux/" - f"vulkansdk-linux-x86_64-{VULKAN_SDK_VERSION}.tar.xz") -VULKAN_SDK_SIZE = 366_564_872 -VULKAN_SDK_SHA256 = "197962f5cbf80baf2775a03336a01cee7c8745686c65aaa70d3f751ade4d7e43" - -REVISIONS = { # the `sha` of https://huggingface.co/api/models/, 2026-10-12 - "unsloth/Qwen-Image-2.1-Turbo-GGUF": "5d1f9f759ea877ae556cda88dbec958b62ad3809", - "unsloth/Qwen-Image-2.1-FP8": "bb21a8ba7f0371c19ad1f72c82a5e8fc10f39939", - "unsloth/Qwen3-VL-8B-Instruct-GGUF": "b93a7ee713758252c555be4210c00540df954dc2", -} -_DIT = "unsloth/Qwen-Image-2.1-Turbo-GGUF" -# name -> (repo, path in the repo, bytes, sha256): the Hub's LFS pointers at the pinned revisions -FILES = { - "Q4_K_M": (_DIT, "qwen-image-2.1-turbo-Q4_K_M.gguf", 4_199_565_120, - "8940e8b522af886e0c0f5afddf720e82dd223cb9a43580b5f61c4d740452ac20"), - "Q6_K": (_DIT, "qwen-image-2.1-turbo-Q6_K.gguf", 6_271_551_296, - "f4560fb47ad863ffed7e32737d3c42988c44bd0c459606777d7ffe2e895d0a70"), - "Q8_0": (_DIT, "qwen-image-2.1-turbo-Q8_0.gguf", 7_640_860_480, - "399d2ddc3636f36456e2f5bfa57187da4e38721bc046430317f42a9eab5b1712"), - "vae": ("unsloth/Qwen-Image-2.1-FP8", "vae/qwen_image_2.1_vae_bf16.safetensors", 675_508_656, - "71879ffd5321e6d10c3c87513e2b474b1252efa7f3dec2969214a9bf06a6dd5c"), - "llm": ("unsloth/Qwen3-VL-8B-Instruct-GGUF", "Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf", 5_148_699_488, - "e3d1a6e87c5cb31e054f2c3bc0dd82ffde052f613de5eef3665b7bd33c9b703e"), -} -QUANTS = ("Q4_K_M", "Q6_K", "Q8_0") -BACKENDS = ("cuda", "hip", "vulkan", "cpu") -LICENSE_NOTE = ("Qwen-Image-2.1-Turbo is under the Qwen Research License (not Apache 2.0): " - "https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo/blob/main/LICENSE - read it before you use the images " - "commercially") -MODEL_DIR = "qwen-image-2.1-turbo" -SD_EXE = "sd-cli.exe" if os.name == "nt" else "sd-cli" - - -def pick_quant(gpu_gb: float) -> str: - """The denoiser for a GPU with `gpu_gb` of memory: Q4_K_M up to 8 GB, Q6_K up to 12 GB, Q8_0 above.""" - if gpu_gb <= 8: - return "Q4_K_M" - if gpu_gb <= 12: - return "Q6_K" - return "Q8_0" - - -# AMD APUs (integrated GPUs on shared memory) by gfx target: Rembrandt 680M/660M, Mendocino 610M, Phoenix 780M/760M/ -# 740M, Strix Point 890M/880M, Strix Halo 8060S, Krackan, Raven/Renoir/Cezanne -APU_ARCHS = ("gfx1035", "gfx1036", "gfx1037", "gfx1103", "gfx1150", "gfx1151", "gfx1152", "gfx1153", - "gfx902", "gfx909", "gfx90c") - - -def is_apu(gpu: dict | None) -> bool: - """An integrated GPU on shared memory: setup's "uma" mark, or an APU's gfx target (setup marks only the APUs the - text engine supports).""" - if not gpu: - return False - return bool(gpu.get("uma")) or str(gpu.get("arch") or "").split(":")[0] in APU_ARCHS - - -def pick_backend(gpu: dict | None, win: bool) -> str: - """sd.cpp's backend for setup's GPU dict (vendor, uma, arch): see the module's docstring.""" - if not gpu: - return "cpu" - vendor = (gpu.get("vendor") or "nvidia").lower() - if vendor == "nvidia": - return "cuda" - if vendor == "amd": - return "vulkan" if is_apu(gpu) or win else "hip" - return "vulkan" # Intel (Arc) and others - - -def default_args(backend: str) -> list[str]: - """sd-cli's fixed arguments besides the ones serve/images.py writes per request.""" - # Vulkan: 256-pixel tiles at a quarter's overlap, not sd.cpp's half: the 780M's 1024x1024 decode takes 23 s instead - # of 45 s, at an LPIPS of 0.012 against the half-overlap image (Q8_0's own distance to bf16 is ~0.03) - return ["--diffusion-fa"] + (["--vae-tiling", "--vae-tile-overlap", "0.25"] if backend == "vulkan" else []) - - -def file_url(name: str, endpoint: str = "https://huggingface.co") -> str: - repo, path, _, _ = FILES[name] - return f"{endpoint.rstrip('/')}/{repo}/resolve/{REVISIONS[repo]}/{path}" - - -def local_path(models_dir: Path, name: str) -> Path: - return Path(models_dir) / MODEL_DIR / Path(FILES[name][1]).name - - -def cmake_defs(backend: str, arch=None, rocm: Path | None = None, cuda_root: Path | None = None) -> list[str]: - """CMake definitions for sd-cli on `backend`: arch = the CUDA compute capability ("86") or the gfx target.""" - defs = ["-DSD_BUILD_EXAMPLES=ON", "-DSD_WEBP=OFF", "-DSD_WEBM=OFF", "-DSD_BUILD_SHARED_LIBS=OFF", - "-DGGML_NATIVE=ON"] - if backend == "cuda": - defs += ["-DSD_CUDA=ON"] + ([f"-DCMAKE_CUDA_ARCHITECTURES={arch}"] if arch else []) - if cuda_root: - defs += [f"-DCUDAToolkit_ROOT={cuda_root}"] - elif backend == "hip": - if not rocm: - raise ValueError("the HIP build needs the ROCm folder") - gfx = str(arch).split(":")[0] - llvm = rocm / "lib" / "llvm" if (rocm / "lib" / "llvm" / "bin").is_dir() else rocm / "llvm" - bitcode = next((p for p in (llvm / "amdgcn" / "bitcode", rocm / "amdgcn" / "bitcode") if p.is_dir()), - llvm / "amdgcn" / "bitcode") - defs += ["-DSD_HIPBLAS=ON", f"-DGPU_TARGETS={gfx}", f"-DAMDGPU_TARGETS={gfx}", - f"-DCMAKE_C_COMPILER={llvm / 'bin' / 'clang'}", f"-DCMAKE_CXX_COMPILER={llvm / 'bin' / 'clang++'}", - f"-DCMAKE_HIP_COMPILER={llvm / 'bin' / 'clang++'}", - f"-DCMAKE_PREFIX_PATH={rocm};{rocm / 'lib' / 'rocm_sysdeps'};{llvm}", - f"-DCMAKE_HIP_FLAGS=--rocm-path={rocm} --rocm-device-lib-path={bitcode}"] - elif backend == "vulkan": - defs += ["-DSD_VULKAN=ON"] - elif backend != "cpu": - raise ValueError(f"unknown backend {backend!r}") - return defs - - -def unpack_source(third_party: Path, sd_zip: Path, ggml_zip: Path) -> Path: - """stable-diffusion.cpp's zip with its ggml submodule's zip inside (GitHub's archives leave submodules out) -> - third_party/stable-diffusion.cpp, stamped with the two commits.""" - dst = Path(third_party) / "stable-diffusion.cpp" - tmp = Path(third_party) / "_unpack-sd" - shutil.rmtree(tmp, ignore_errors=True) - for z, sub in ((sd_zip, "sd"), (ggml_zip, "ggml")): - with zipfile.ZipFile(z) as f: - f.extractall(tmp / sub) - top = next((tmp / "sd").iterdir()) - gtop = next((tmp / "ggml").iterdir()) - shutil.rmtree(top / "ggml", ignore_errors=True) - shutil.move(str(gtop), str(top / "ggml")) - shutil.rmtree(dst, ignore_errors=True) - shutil.move(str(top), str(dst)) - shutil.rmtree(tmp, ignore_errors=True) - (dst / ".strata-pin").write_text(f"{SD_CPP_COMMIT}\n{SD_GGML_COMMIT}\n", encoding="utf-8") - return dst - - -def source_ok(src: Path) -> bool: - pin = Path(src) / ".strata-pin" - return pin.is_file() and pin.read_text(encoding="utf-8").split() == [SD_CPP_COMMIT, SD_GGML_COMMIT] \ - and (Path(src) / "ggml" / "CMakeLists.txt").is_file() - - -NATIVE_DIR = Path(__file__).resolve().parent / "sdcpp_native" -NATIVE_BACKENDS = ("cuda", "hip") # where the native DiT runner (I2) is built in - - -def native_hash() -> str: - """A fingerprint of the native runner's sources (a change compiles sd-cli again).""" - import hashlib - h = hashlib.sha256() - for f in sorted(NATIVE_DIR.glob("*")): - if f.is_file() and f.suffix in (".cu", ".hpp", ".py"): - h.update(f.name.encode() + b"\0" + f.read_bytes().replace(b"\r\n", b"\n")) - return h.hexdigest()[:16] - - -def build_stamp(backend: str, arch) -> dict: - stamp = {"sd_cpp": SD_CPP_COMMIT, "ggml": SD_GGML_COMMIT, "backend": backend, "arch": str(arch or "")} - if backend in NATIVE_BACKENDS: - stamp["native"] = native_hash() - return stamp - - -def image_config(backend: str, quant: str, exe: Path, models_dir: Path, *, uma: bool = False, gpu=None, - lib_dirs=(), policy: str = "auto", native: bool = False) -> dict: - """The run config's "images" section (serve/images.py reads it).""" - cfg = {"model_name": "qwen-image-2.1-turbo", "exe": str(exe), "backend": backend, "quant": quant, - "diffusion_model": str(local_path(models_dir, quant)), "vae": str(local_path(models_dir, "vae")), - "llm": str(local_path(models_dir, "llm")), "args": default_args(backend), "gpu_policy": policy, - "uma": bool(uma), "sd_cpp": SD_CPP_COMMIT[:7]} - if backend in NATIVE_BACKENDS: - cfg["native"] = bool(native) # PolyStrata's DiT runner (--model-args qwen_image_2_1_native=1) - if gpu is not None: - cfg["gpu"] = gpu - if lib_dirs: - cfg["lib_dirs"] = [str(d) for d in lib_dirs] - return cfg diff --git a/tools/image/sdcpp_native/apply.py b/tools/image/sdcpp_native/apply.py deleted file mode 100644 index 5620ace..0000000 --- a/tools/image/sdcpp_native/apply.py +++ /dev/null @@ -1,75 +0,0 @@ -"""tools/image/sdcpp_native/apply.py - put PolyStrata's native Qwen-Image-2.1 DiT runner into a stable-diffusion.cpp -checkout at the pinned commit (tools/image/qimage.py SD_CPP_COMMIT). Idempotent; the stock runner stays the -default: sd-cli uses the native one only with --model-args qwen_image_2_1_native=1 (serve/images.py adds it when the -config's "native" is true), and only in CUDA / HIP builds. - - python tools/image/sdcpp_native/apply.py third_party/stable-diffusion.cpp - -Two new files (the kernels into ggml/src/ggml-cuda/, which ggml-cuda and ggml-hip compile by glob; the runner into -src/model/diffusion/) and two small edits (model_builders.cpp picks the runner; CMakeLists.txt defines SD_QI_NATIVE -for CUDA / HIP builds).""" -from __future__ import annotations - -import shutil -import sys -from pathlib import Path - -HERE = Path(__file__).resolve().parent -MARK = "// strata: native Qwen-Image-2.1 runner" - -BUILDER_OLD = """ if (version == VERSION_QWEN_IMAGE_2_1) { - result.diffusion = std::make_shared(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION), - tensor_storage_map, - "model.diffusion_model", - weight_manager, - sd_ctx_params->model_args); -""" -BUILDER_NEW = """ if (version == VERSION_QWEN_IMAGE_2_1) { -#ifdef SD_QI_NATIVE - """ + MARK + """ (--model-args qwen_image_2_1_native=1) - if (sd_ctx_params->model_args != nullptr && - std::strstr(sd_ctx_params->model_args, "qwen_image_2_1_native=1") != nullptr && - sd_ctx_params->diffusion_model_path != nullptr && sd_ctx_params->diffusion_model_path[0] != 0) { - result.diffusion = std::make_shared(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION), - tensor_storage_map, - "model.diffusion_model", - weight_manager, - sd_ctx_params->model_args, - sd_ctx_params->diffusion_model_path); - } else -#endif - result.diffusion = std::make_shared(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION), - tensor_storage_map, - "model.diffusion_model", - weight_manager, - sd_ctx_params->model_args); -""" -INCLUDE_OLD = '#include "model/diffusion/minit2i.hpp"\n' -INCLUDE_NEW = INCLUDE_OLD + "#ifdef SD_QI_NATIVE\n#include \"model/diffusion/qwen_image_2_1_native.hpp\" " + MARK + "\n#endif\n" -CMAKE_OLD = "target_include_directories(${SD_LIB} PUBLIC . src include)\n" -CMAKE_NEW = ("if (SD_CUDA OR SD_HIPBLAS) # " + MARK.lstrip("/ ") + "\n" - " target_compile_definitions(${SD_LIB} PRIVATE SD_QI_NATIVE)\nendif()\n" + CMAKE_OLD) - - -def edit(path: Path, old: str, new: str) -> None: - text = path.read_text(encoding="utf-8") - if new in text: - return - if text.count(old) != 1: - raise SystemExit(f"{path}: the expected code is not there (another stable-diffusion.cpp commit?)") - path.write_text(text.replace(old, new), encoding="utf-8") - - -def apply(sd: Path) -> None: - sd = Path(sd) - shutil.copy2(HERE / "qi21-native.cu", sd / "ggml" / "src" / "ggml-cuda" / "qi21-native.cu") - shutil.copy2(HERE / "qwen_image_2_1_native.hpp", sd / "src" / "model" / "diffusion" / "qwen_image_2_1_native.hpp") - builders = sd / "src" / "pipeline" / "model_builders.cpp" - edit(builders, INCLUDE_OLD, INCLUDE_NEW) - edit(builders, BUILDER_OLD, BUILDER_NEW) - edit(sd / "CMakeLists.txt", CMAKE_OLD, CMAKE_NEW) - - -if __name__ == "__main__": - apply(Path(sys.argv[1])) - print("native Qwen-Image-2.1 runner applied") diff --git a/tools/image/sdcpp_native/qi21-native.cu b/tools/image/sdcpp_native/qi21-native.cu deleted file mode 100644 index b263d1e..0000000 --- a/tools/image/sdcpp_native/qi21-native.cu +++ /dev/null @@ -1,679 +0,0 @@ -// qi21-native.cu - Strata's native kernels for the Qwen-Image-2.1 DiT inside stable-diffusion.cpp (CUDA and HIP). -// -// Copied into ggml/src/ggml-cuda/ by tools/image/sdcpp_native/apply.py, so ggml-cuda and ggml-hip compile it with -// their own toolchain and vendor headers. The host side (qwen_image_2_1_native.hpp) runs the GEMMs as ggml graphs -// on the same backend and calls these launchers on the backend's own stream, so everything stays stream-ordered. -// -// qi21_res_ln_mod x += h * tanh(g) (optional), then out = LayerNorm(x) * (1 + m) (no affine, eps) -// qi21_qkv_post per head: RMSNorm(q|k) * w, 3-axis RoPE from sd.cpp's pe table, K/V to fp16, head-major -// qi21_swiglu out = up * silu(gate) (gate = first half of the fused gate_up output) -// qi21_attn_causal plain fp32 attention for the text prefix (causal; once per prompt) -// qi21_attn_wmma gfx11 WMMA flash attention (fp16 in, fp32 softmax and accumulation) for the image tokens -#include "common.cuh" -#include "ggml-backend-impl.h" - -#include -#include - -namespace { - -constexpr int QI_D = 128; - -__device__ __forceinline__ float qi_block_sum(float v, float* red) { - // blockDim.x is a multiple of 32 and <= 1024 - for (int off = 16; off > 0; off >>= 1) v += __shfl_xor_sync(0xffffffff, v, off, 32); - const int w = threadIdx.x >> 5, l = threadIdx.x & 31; - __syncthreads(); - if (l == 0) red[w] = v; - __syncthreads(); - const int nw = blockDim.x >> 5; - float s = threadIdx.x < nw ? red[threadIdx.x] : 0.f; - if (w == 0) { - for (int off = 16; off > 0; off >>= 1) s += __shfl_xor_sync(0xffffffff, s, off, 32); - if (l == 0) red[0] = s; - } - __syncthreads(); - return red[0]; -} - -// x += h * tg (tg = tanh(gate), precomputed once per step), then out = LN(x) * (1 + m); float4, 256 threads, C % 1024 == 0 -template -__global__ void __launch_bounds__(256) k_res_ln_mod4(float* __restrict__ x, const float* __restrict__ h, - const float* __restrict__ tg, float* __restrict__ out, - const float* __restrict__ m, int C, float eps) { - __shared__ float red[32]; - const size_t row = blockIdx.x; - float4* xr = reinterpret_cast(x + row * C); - const float4* hr = reinterpret_cast(h + row * C); - const float4* t4 = reinterpret_cast(tg); - float4 v[8]; - int n = 0; - float s = 0.f; - for (int c = threadIdx.x; c < C / 4; c += blockDim.x) { - float4 a = xr[c]; - if (RES) { - const float4 hh = hr[c], gg = t4[c]; - a.x += hh.x * gg.x; a.y += hh.y * gg.y; a.z += hh.z * gg.z; a.w += hh.w * gg.w; - xr[c] = a; - } - v[n++] = a; - s += (a.x + a.y) + (a.z + a.w); - } - if (!LN) return; - const float mean = qi_block_sum(s, red) / C; - float q = 0.f; - for (int i = 0; i < n; ++i) { - const float dx = v[i].x - mean, dy = v[i].y - mean, dz = v[i].z - mean, dw = v[i].w - mean; - q += (dx * dx + dy * dy) + (dz * dz + dw * dw); - } - const float inv = rsqrtf(qi_block_sum(q, red) / C + eps); - const float4* m4 = reinterpret_cast(m); - float4* o4 = reinterpret_cast(out + row * C); - n = 0; - for (int c = threadIdx.x; c < C / 4; c += blockDim.x) { - const float4 mm = m4[c], a = v[n++]; - o4[c] = make_float4((a.x - mean) * inv * (1.f + mm.x), (a.y - mean) * inv * (1.f + mm.y), - (a.z - mean) * inv * (1.f + mm.z), (a.w - mean) * inv * (1.f + mm.w)); - } -} - -__global__ void k_tanh(const float* __restrict__ in, float* __restrict__ out, int n) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) out[i] = tanhf(in[i]); -} - -template -__global__ void __launch_bounds__(256) k_res_ln_mod(float* __restrict__ x, const float* __restrict__ h, - const float* __restrict__ g, float* __restrict__ out, - const float* __restrict__ m, int C, float eps) { - __shared__ float red[32]; - const size_t row = blockIdx.x; - float* xr = x + row * C; - float v[32]; - int n = 0; - float s = 0.f; - for (int c = threadIdx.x; c < C; c += blockDim.x) { - float a = xr[c]; - if (RES) { - a += h[row * C + c] * tanhf(g[c]); - xr[c] = a; - } - v[n++] = a; - s += a; - } - if (!LN) return; - const float mean = qi_block_sum(s, red) / C; - float q = 0.f; - for (int i = 0; i < n; ++i) q += (v[i] - mean) * (v[i] - mean); - const float inv = rsqrtf(qi_block_sum(q, red) / C + eps); - n = 0; - for (int c = threadIdx.x; c < C; c += blockDim.x) out[row * C + c] = (v[n++] - mean) * inv * (1.f + m[c]); -} - -// grid (T, H), block 128: one head of one token. src rows have stride ld (floats). -template -__global__ void __launch_bounds__(QI_D) k_qkv_post(const float* __restrict__ q, const float* __restrict__ k, - const float* __restrict__ v, int ld, const float* __restrict__ wq, - const float* __restrict__ wk, const float* __restrict__ pe, - QT* __restrict__ qo, half* __restrict__ qlo, int q_tstride, - half* __restrict__ ko, - half* __restrict__ vo, int kv_tstride, int kv_off, float eps) { - __shared__ float red[32]; - __shared__ float buf[QI_D]; - const int t = blockIdx.x, hh = blockIdx.y, d = threadIdx.x; - const size_t src = (size_t) t * ld + hh * QI_D + d; - const float* p = pe + ((size_t) t * (QI_D / 2) + (d >> 1)) * 4; - for (int which = 0; which < 2; ++which) { - const float x = which == 0 ? q[src] : k[src]; - const float ss = qi_block_sum(x * x, red); - const float y = x * rsqrtf(ss / QI_D + eps) * (which == 0 ? wq[d] : wk[d]); - buf[d] = y; - __syncthreads(); - const float x0 = buf[d & ~1], x1 = buf[d | 1]; - const float r = (d & 1) ? p[2] * x0 + p[3] * x1 : p[0] * x0 + p[1] * x1; - __syncthreads(); - if (which == 0) { - const size_t qi = ((size_t) hh * q_tstride + t) * QI_D + d; - qo[qi] = (QT) r; - if (qlo != nullptr) qlo[qi] = __float2half(r - __half2float(__float2half(r))); - } else { - ko[((size_t) hh * kv_tstride + kv_off + t) * QI_D + d] = __float2half(r); - } - } - vo[((size_t) hh * kv_tstride + kv_off + t) * QI_D + d] = __float2half(v[src]); -} - -// warp per head: grid (T, H/8), block 256; lane holds dims 4*lane..+3 (two RoPE pairs), no shared memory -template -__device__ __forceinline__ void qi_store4(QT* dst, float a, float b, float c, float d); -template <> -__device__ __forceinline__ void qi_store4(float* dst, float a, float b, float c, float d) { - *reinterpret_cast(dst) = make_float4(a, b, c, d); -} -template <> -__device__ __forceinline__ void qi_store4(half* dst, float a, float b, float c, float d) { - half2 lo = __floats2half2_rn(a, b), hi2 = __floats2half2_rn(c, d); - uint2 u; - u.x = *reinterpret_cast(&lo); - u.y = *reinterpret_cast(&hi2); - *reinterpret_cast(dst) = u; -} - -template -__global__ void __launch_bounds__(256) k_qkv_post_w(const float* __restrict__ q, const float* __restrict__ k, - const float* __restrict__ v, int ld, const float* __restrict__ wq, - const float* __restrict__ wk, const float* __restrict__ pe, - QT* __restrict__ qo, int q_tstride, half* __restrict__ ko, - half* __restrict__ vo, int kv_tstride, int kv_off, float eps) { - const int t = blockIdx.x, lane = threadIdx.x & 31, hh = blockIdx.y * 8 + (threadIdx.x >> 5); - const int d = lane * 4; - const size_t src = (size_t) t * ld + hh * QI_D + d; - const float4 p0 = *reinterpret_cast(pe + ((size_t) t * (QI_D / 2) + lane * 2) * 4); - const float4 p1 = *reinterpret_cast(pe + ((size_t) t * (QI_D / 2) + lane * 2 + 1) * 4); - for (int which = 0; which < 2; ++which) { - const float4 x = *reinterpret_cast((which == 0 ? q : k) + src); - float ss = x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w; - for (int off = 16; off > 0; off >>= 1) ss += __shfl_xor_sync(0xffffffff, ss, off, 32); - const float inv = rsqrtf(ss / QI_D + eps); - const float4 w = *reinterpret_cast((which == 0 ? wq : wk) + d); - const float y0 = x.x * inv * w.x, y1 = x.y * inv * w.y, y2 = x.z * inv * w.z, y3 = x.w * inv * w.w; - const float r0 = p0.x * y0 + p0.y * y1, r1 = p0.z * y0 + p0.w * y1; - const float r2 = p1.x * y2 + p1.y * y3, r3 = p1.z * y2 + p1.w * y3; - if (which == 0) - qi_store4(qo + ((size_t) hh * q_tstride + t) * QI_D + d, r0, r1, r2, r3); - else - qi_store4(ko + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, r0, r1, r2, r3); - } - const float4 vv = *reinterpret_cast(v + src); - qi_store4(vo + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, vv.x, vv.y, vv.z, vv.w); -} - -__global__ void k_swiglu(const float* __restrict__ gu, float* __restrict__ out, int F, int64_t n) { - const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - const int64_t t = i / F, c = i % F; - const float g = gu[t * 2 * F + c], u = gu[t * 2 * F + F + c]; - out[i] = u * (g / (1.f + expf(-g))); -} - -// grid (Lq, H), block 128, dynamic smem Lk floats. q fp32 head-major [H][q_tstride][128], k/v fp16 [H][kv_tstride][128], -// out token-major [Lq][H*128]. causal: query i sees keys 0..i. -__global__ void __launch_bounds__(QI_D) k_attn_causal(const float* __restrict__ q, int q_tstride, - const half* __restrict__ k, const half* __restrict__ v, - int kv_tstride, float* __restrict__ out, int H, int Lk, - int causal, float scale) { - extern __shared__ float s[]; - __shared__ float red[32]; - __shared__ float qs[QI_D]; - const int i = blockIdx.x, hh = blockIdx.y, d = threadIdx.x; - qs[d] = q[((size_t) hh * q_tstride + i) * QI_D + d]; - __syncthreads(); - const int n = causal ? i + 1 : Lk; - float mx = -INFINITY; - for (int j = d; j < n; j += QI_D) { - const half* kr = k + ((size_t) hh * kv_tstride + j) * QI_D; - float dot = 0.f; - for (int c = 0; c < QI_D; ++c) dot += qs[c] * __half2float(kr[c]); - s[j] = dot * scale; - mx = fmaxf(mx, s[j]); - } - // block max - for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, off, 32)); - __syncthreads(); - if ((d & 31) == 0) red[d >> 5] = mx; - __syncthreads(); - mx = red[0]; - for (int w = 1; w < QI_D / 32; ++w) mx = fmaxf(mx, red[w]); - __syncthreads(); - float sum = 0.f; - for (int j = d; j < n; j += QI_D) { - s[j] = expf(s[j] - mx); - sum += s[j]; - } - sum = qi_block_sum(sum, red); - float acc = 0.f; - for (int j = 0; j < n; ++j) acc += s[j] * __half2float(v[((size_t) hh * kv_tstride + j) * QI_D + d]); - out[(size_t) i * H * QI_D + hh * QI_D + d] = acc / sum; -} - -#if defined(GGML_USE_HIP) -// WMMA fragments: gfx11 (RDNA3) lanes hold 16 k-values of their row/column (lanes 16..31 duplicate 0..15) and C row -// 2i + (lane >> 4); gfx12 (RDNA4) lanes hold 8 k-values at offset 8 * (lane >> 4) and C row 8 * (lane >> 4) + i. -#if defined(RDNA4) -#define QI_KL 8 -#define QI_KOFF(hi) ((hi) * 8) -#define QI_ROW(i, hi) ((hi) * 8 + (i)) -#define QI_WMMA __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12 -#else -#define QI_KL 16 -#define QI_KOFF(hi) 0 -#define QI_ROW(i, hi) (2 * (i) + (hi)) -#define QI_WMMA __builtin_amdgcn_wmma_f32_16x16x16_f16_w32 -#endif -typedef _Float16 qi_h16 __attribute__((ext_vector_type(QI_KL))); -typedef float qi_f8 __attribute__((ext_vector_type(8))); -constexpr int FA_BQ = 128, FA_BKV = 64, FA_NW = 8, FA_KLD = QI_D + 8, FA_VLD = FA_BKV + 8, FA_PLD = FA_BKV + 8; - -// a lane's fragment of the 16 k-values starting at p (this lane's half on gfx12) -__device__ __forceinline__ qi_h16 qi_ld16(const _Float16* p, int hi) { -#if QI_KL == 8 - return __builtin_bit_cast(qi_h16, *reinterpret_cast(p + QI_KOFF(hi))); -#else - (void) hi; - const uint4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); - const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; - return __builtin_bit_cast(qi_h16, w); -#endif -} - -// gfx11 WMMA flash attention: q fp16 head-major [H][q_tstride][128], k/v fp16 head-major [H][kv_tstride][128] -// (no mask), out fp32 token-major [nq][H*128]. 8 waves x 16 query rows; 64-key tiles through LDS (V transposed). -template -__global__ void __launch_bounds__(FA_NW * 32) k_attn_wmma(const _Float16* __restrict__ Q, const _Float16* __restrict__ Qlo, - int q_tstride, - const _Float16* __restrict__ K, const _Float16* __restrict__ V, - int kv_tstride, float* __restrict__ O, int H, int nq, int nkv, - float scale_log2) { -#if defined(RDNA3) || defined(RDNA4) - __shared__ __align__(16) _Float16 sK[FA_BKV][FA_KLD]; - __shared__ __align__(16) _Float16 sVt[QI_D][FA_VLD]; - __shared__ __align__(16) _Float16 sP[FA_NW][16][FA_PLD]; - const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; - const int head = blockIdx.y, q0 = blockIdx.x * FA_BQ + wave * 16; - const _Float16* Qh = Q + (size_t) head * q_tstride * QI_D; - const _Float16* Kh = K + (size_t) head * kv_tstride * QI_D; - const _Float16* Vh = V + (size_t) head * kv_tstride * QI_D; - qi_h16 qa[QI_D / 16], ql[LO ? QI_D / 16 : 1]; - { - const int qr = min(q0 + l16, nq - 1); - for (int c = 0; c < QI_D / 16; ++c) qa[c] = qi_ld16(Qh + (size_t) qr * QI_D + c * 16, hi); - if (LO) { - const _Float16* Ql = Qlo + (size_t) head * q_tstride * QI_D; - for (int c = 0; c < QI_D / 16; ++c) ql[c] = qi_ld16(Ql + (size_t) qr * QI_D + c * 16, hi); - } - } - qi_f8 o[QI_D / 16]; - for (int c = 0; c < QI_D / 16; ++c) o[c] = qi_f8{}; - float m[8], l[8]; - for (int i = 0; i < 8; ++i) { m[i] = -INFINITY; l[i] = 0.f; } - for (int k0 = 0; k0 < nkv; k0 += FA_BKV) { - __syncthreads(); - for (int e = tid * 8; e < FA_BKV * QI_D; e += FA_NW * 32 * 8) { - const int r = e / QI_D, c = e % QI_D, key = k0 + r; - uint4 kv = make_uint4(0, 0, 0, 0); - if (key < nkv) kv = *reinterpret_cast(Kh + (size_t) key * QI_D + c); - *reinterpret_cast(&sK[r][c]) = kv; - } - for (int e = tid; e < (FA_BKV / 4) * (QI_D / 8); e += FA_NW * 32) { - const int r4 = (e / (QI_D / 8)) * 4, c = (e % (QI_D / 8)) * 8; - _Float16 vv[4][8]; - for (int j = 0; j < 4; ++j) { - uint4 x = make_uint4(0, 0, 0, 0); - if (k0 + r4 + j < nkv) x = *reinterpret_cast(Vh + (size_t) (k0 + r4 + j) * QI_D + c); - *reinterpret_cast(vv[j]) = x; - } - for (int dd = 0; dd < 8; ++dd) { - _Float16 w4[4] = {vv[0][dd], vv[1][dd], vv[2][dd], vv[3][dd]}; - *reinterpret_cast(&sVt[c + dd][r4]) = *reinterpret_cast(w4); - } - } - __syncthreads(); - qi_f8 s[FA_BKV / 16]; - for (int t = 0; t < FA_BKV / 16; ++t) { - s[t] = qi_f8{}; - for (int c = 0; c < QI_D / 16; ++c) { - const qi_h16 kb = qi_ld16(&sK[t * 16 + l16][c * 16], hi); - s[t] = QI_WMMA(qa[c], kb, s[t]); - if (LO) s[t] = QI_WMMA(ql[LO ? c : 0], kb, s[t]); - } - } - float alpha[8]; - for (int i = 0; i < 8; ++i) { - float mx = -INFINITY; - for (int t = 0; t < FA_BKV / 16; ++t) { - const float val = k0 + t * 16 + l16 < nkv ? s[t][i] * scale_log2 : -INFINITY; - s[t][i] = val; - mx = fmaxf(mx, val); - } - for (int off = 1; off < 16; off <<= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 32)); - const float mnew = fmaxf(m[i], mx); - alpha[i] = exp2f(m[i] - mnew); - float sum = 0.f; - for (int t = 0; t < FA_BKV / 16; ++t) { - const float pv = exp2f(s[t][i] - mnew); - s[t][i] = pv; - sum += pv; - } - for (int off = 1; off < 16; off <<= 1) sum += __shfl_xor(sum, off, 32); - l[i] = l[i] * alpha[i] + sum; - m[i] = mnew; - } - for (int c = 0; c < QI_D / 16; ++c) - for (int i = 0; i < 8; ++i) o[c][i] *= alpha[i]; - for (int t = 0; t < FA_BKV / 16; ++t) - for (int i = 0; i < 8; ++i) sP[wave][QI_ROW(i, hi)][t * 16 + l16] = (_Float16) s[t][i]; - __builtin_amdgcn_s_waitcnt(0); - __builtin_amdgcn_wave_barrier(); - for (int kc = 0; kc < FA_BKV / 16; ++kc) { - const qi_h16 pa = qi_ld16(&sP[wave][l16][kc * 16], hi); - for (int c = 0; c < QI_D / 16; ++c) - o[c] = QI_WMMA(pa, qi_ld16(&sVt[c * 16 + l16][kc * 16], hi), o[c]); - } - } - for (int c = 0; c < QI_D / 16; ++c) - for (int i = 0; i < 8; ++i) { - const int row = q0 + QI_ROW(i, hi); - if (row < nq) O[(size_t) row * H * QI_D + head * QI_D + c * 16 + l16] = o[c][i] / l[i]; - } -#else - __builtin_trap(); -#endif -} -#endif // GGML_USE_HIP - -#if !defined(GGML_USE_HIP) -// NVIDIA (sm_80+): mma.sync m16n8k16 f16 -> f32 flash attention. 8 warps x 16 queries per block, 64-key tiles of K -// and V (row-major) double-buffered with cp.async, ldmatrix (.trans for V) fragments, fp32 online softmax, P in fp16. -// q fp16 head-major [H][q_tstride][128], k/v fp16 head-major [H][kv_tstride][128], out fp32 token-major [nq][H*128]. -constexpr int MF_NW = 8, MF_BQ = MF_NW * 16, MF_BKV = 64, MF_LD = QI_D + 8; -constexpr size_t MF_SMEM = (size_t) 4 * MF_BKV * MF_LD * sizeof(half); - -__device__ __forceinline__ void qi_mma16816(float* c, const uint32_t* a, const uint32_t* b) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 - asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n" - : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) - : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); -#else - (void) c; (void) a; (void) b; - __trap(); -#endif -} -__device__ __forceinline__ uint32_t qi_pack2(float x, float y) { - half2 h = __floats2half2_rn(x, y); - return *reinterpret_cast(&h); -} -__device__ __forceinline__ void qi_ldsm_x4(uint32_t* r, const half* p, bool trans) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 - const uint32_t a = (uint32_t) __cvta_generic_to_shared(p); - if (trans) - asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n" - : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); - else - asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" - : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); -#else - (void) r; (void) p; (void) trans; -#endif -} -__device__ __forceinline__ void qi_cp16(half* dst, const half* src, bool ok) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 - const uint32_t a = (uint32_t) __cvta_generic_to_shared(dst); - const int n = ok ? 16 : 0; - asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" :: "r"(a), "l"(src), "r"(n)); -#else - (void) dst; (void) src; (void) ok; -#endif -} - -__global__ void __launch_bounds__(MF_NW * 32) k_attn_mma(const half* __restrict__ Q, int q_tstride, - const half* __restrict__ K, const half* __restrict__ V, - int kv_tstride, float* __restrict__ O, int H, int nq, int nkv, - float scale_log2) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 - extern __shared__ __align__(16) half qi_smem[]; - const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; - const int r = lane >> 2, c2 = (lane & 3) * 2, lr = lane & 7, lq = lane >> 3; - const int head = blockIdx.y, q0 = blockIdx.x * MF_BQ + warp * 16; - const half* Qh = Q + (size_t) head * q_tstride * QI_D; - const half* Kh = K + (size_t) head * kv_tstride * QI_D; - const half* Vh = V + (size_t) head * kv_tstride * QI_D; - auto tile = [&](int st, int kv) { return qi_smem + ((st * 2 + kv) * MF_BKV) * MF_LD; }; - auto load = [&](int st, int k0) { - for (int e = tid * 8; e < MF_BKV * QI_D; e += MF_NW * 32 * 8) { - const int rr = e / QI_D, cc = e % QI_D, key = k0 + rr; - const bool ok = key < nkv; - const size_t off = (size_t) (ok ? key : 0) * QI_D + cc; - qi_cp16(tile(st, 0) + rr * MF_LD + cc, Kh + off, ok); - qi_cp16(tile(st, 1) + rr * MF_LD + cc, Vh + off, ok); - } - asm volatile("cp.async.commit_group;\n"); - }; - uint32_t qa[QI_D / 16][4]; - { - const int r0 = min(q0 + r, nq - 1), r1 = min(q0 + r + 8, nq - 1); - for (int kc = 0; kc < QI_D / 16; ++kc) { - qa[kc][0] = *reinterpret_cast(Qh + (size_t) r0 * QI_D + kc * 16 + c2); - qa[kc][1] = *reinterpret_cast(Qh + (size_t) r1 * QI_D + kc * 16 + c2); - qa[kc][2] = *reinterpret_cast(Qh + (size_t) r0 * QI_D + kc * 16 + c2 + 8); - qa[kc][3] = *reinterpret_cast(Qh + (size_t) r1 * QI_D + kc * 16 + c2 + 8); - } - } - float o[QI_D / 8][4]; - for (int n = 0; n < QI_D / 8; ++n) o[n][0] = o[n][1] = o[n][2] = o[n][3] = 0.f; - float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.f, l1 = 0.f; - const int ntiles = (nkv + MF_BKV - 1) / MF_BKV; - load(0, 0); - for (int it = 0; it < ntiles; ++it) { - const int st = it & 1, k0 = it * MF_BKV; - if (it + 1 < ntiles) { - load(st ^ 1, k0 + MF_BKV); - asm volatile("cp.async.wait_group 1;\n"); - } else { - asm volatile("cp.async.wait_group 0;\n"); - } - __syncthreads(); - const half* sK = tile(st, 0); - const half* sV = tile(st, 1); - float s[MF_BKV / 8][4]; - for (int t = 0; t < MF_BKV / 8; ++t) { - s[t][0] = s[t][1] = s[t][2] = s[t][3] = 0.f; - for (int kc = 0; kc < QI_D / 16; kc += 2) { - uint32_t b[4]; - qi_ldsm_x4(b, sK + (t * 8 + lr) * MF_LD + kc * 16 + lq * 8, false); - qi_mma16816(s[t], qa[kc], b); - qi_mma16816(s[t], qa[kc + 1], b + 2); - } - } - float mx0 = -INFINITY, mx1 = -INFINITY; - for (int t = 0; t < MF_BKV / 8; ++t) - for (int j = 0; j < 2; ++j) { - const bool ok = k0 + t * 8 + c2 + j < nkv; - s[t][j] = ok ? s[t][j] * scale_log2 : -INFINITY; - s[t][2 + j] = ok ? s[t][2 + j] * scale_log2 : -INFINITY; - mx0 = fmaxf(mx0, s[t][j]); - mx1 = fmaxf(mx1, s[t][2 + j]); - } - for (int off = 1; off < 4; off <<= 1) { - mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffff, mx0, off)); - mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffff, mx1, off)); - } - const float mn0 = fmaxf(m0, mx0), mn1 = fmaxf(m1, mx1); - const float a0 = exp2f(m0 - mn0), a1 = exp2f(m1 - mn1); - float sum0 = 0.f, sum1 = 0.f; - for (int t = 0; t < MF_BKV / 8; ++t) - for (int j = 0; j < 2; ++j) { - s[t][j] = exp2f(s[t][j] - mn0); - s[t][2 + j] = exp2f(s[t][2 + j] - mn1); - sum0 += s[t][j]; - sum1 += s[t][2 + j]; - } - for (int off = 1; off < 4; off <<= 1) { - sum0 += __shfl_xor_sync(0xffffffff, sum0, off); - sum1 += __shfl_xor_sync(0xffffffff, sum1, off); - } - l0 = l0 * a0 + sum0; - l1 = l1 * a1 + sum1; - m0 = mn0; - m1 = mn1; - for (int n = 0; n < QI_D / 8; ++n) { - o[n][0] *= a0; o[n][1] *= a0; o[n][2] *= a1; o[n][3] *= a1; - } - for (int kc = 0; kc < MF_BKV / 16; ++kc) { - uint32_t pa[4]; - pa[0] = qi_pack2(s[2 * kc][0], s[2 * kc][1]); - pa[1] = qi_pack2(s[2 * kc][2], s[2 * kc][3]); - pa[2] = qi_pack2(s[2 * kc + 1][0], s[2 * kc + 1][1]); - pa[3] = qi_pack2(s[2 * kc + 1][2], s[2 * kc + 1][3]); - for (int n = 0; n < QI_D / 8; n += 2) { - uint32_t b[4]; - qi_ldsm_x4(b, sV + (kc * 16 + (lq & 1) * 8 + lr) * MF_LD + n * 8 + (lq >> 1) * 8, true); - qi_mma16816(o[n], pa, b); - qi_mma16816(o[n + 1], pa, b + 2); - } - } - __syncthreads(); - } - const int row0 = q0 + r, row1 = q0 + r + 8; - for (int n = 0; n < QI_D / 8; ++n) { - if (row0 < nq) - *reinterpret_cast(O + (size_t) row0 * H * QI_D + head * QI_D + n * 8 + c2) = - make_float2(o[n][0] / l0, o[n][1] / l0); - if (row1 < nq) - *reinterpret_cast(O + (size_t) row1 * H * QI_D + head * QI_D + n * 8 + c2) = - make_float2(o[n][2] / l1, o[n][3] / l1); - } -#else - __trap(); -#endif -} -#endif // !GGML_USE_HIP - -inline cudaStream_t qi_s(void* s) { return static_cast(s); } - -} // namespace - -extern "C" { - -void* qi21_stream(ggml_backend_t backend) { - return static_cast(backend->context)->stream(); -} - -// 1 when this backend's GPU runs qi21_attn_wmma (an RDNA3 / gfx11 or RDNA4 / gfx12 card in a HIP build; -// STRATA_QI_GFX12_ATTN=0 keeps ggml's attention on gfx12, where this kernel is not measured yet) -int qi21_has_wmma_attn(ggml_backend_t backend) { -#if defined(GGML_USE_HIP) - const int dev = static_cast(backend->context)->device; - const int cc = ggml_cuda_info().devices[dev].cc; - if (GGML_CUDA_CC_IS_RDNA3(cc)) return 1; - const char* g12 = getenv("STRATA_QI_GFX12_ATTN"); - return GGML_CUDA_CC_IS_RDNA4(cc) && g12 != nullptr && g12[0] == '1' ? 1 : 0; -#else - // NVIDIA Ampere or newer: the mma.sync kernel (STRATA_QI_GGML_ATTN=1 in the runner keeps ggml's) - const int dev = static_cast(backend->context)->device; - return GGML_CUDA_CC_IS_NVIDIA(ggml_cuda_info().devices[dev].cc) && - ggml_cuda_info().devices[dev].cc >= GGML_CUDA_CC_AMPERE ? 1 : 0; -#endif -} - -int qi21_tanh(void* stream, const float* in, float* out, int n) { - k_tanh<<<(n + 255) / 256, 256, 0, qi_s(stream)>>>(in, out, n); - return cudaGetLastError() == cudaSuccess ? 0 : 2; -} - -// g: the gate row as tanh(gate) already when tg != 0 (the float4 kernel), the raw gate otherwise -int qi21_res_ln_mod2(void* stream, float* x, const float* h, const float* tg, float* out, const float* m, int T, int C, - float eps) { - if (C % 1024 != 0 || C > 8 * 1024) return 1; - if (h != nullptr && out != nullptr) - k_res_ln_mod4<<>>(x, h, tg, out, m, C, eps); - else if (h != nullptr) - k_res_ln_mod4<<>>(x, h, tg, out, m, C, eps); - else - k_res_ln_mod4<<>>(x, h, tg, out, m, C, eps); - return cudaGetLastError() == cudaSuccess ? 0 : 2; -} - -int qi21_res_ln_mod(void* stream, float* x, const float* h, const float* g, float* out, const float* m, int T, int C, - float eps) { - if (C > 32 * 256) return 1; - if (h != nullptr && out != nullptr) - k_res_ln_mod<<>>(x, h, g, out, m, C, eps); - else if (h != nullptr) - k_res_ln_mod<<>>(x, h, g, out, m, C, eps); - else - k_res_ln_mod<<>>(x, h, g, out, m, C, eps); - return cudaGetLastError() == cudaSuccess ? 0 : 2; -} - -int qi21_qkv_post(void* stream, const float* q, const float* k, const float* v, int ld, const float* wq, const float* wk, - const float* pe, void* qo, void* qlo, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride, - int kv_off, int T, int H, float eps) { - if (qlo == nullptr && H % 8 == 0 && ld % 4 == 0 && getenv("STRATA_QI_OLD_QKV") == nullptr) { - const dim3 gw(T, H / 8); - if (q_f16) - k_qkv_post_w<<>>(q, k, v, ld, wq, wk, pe, static_cast(qo), q_tstride, - static_cast(ko), static_cast(vo), kv_tstride, - kv_off, eps); - else - k_qkv_post_w<<>>(q, k, v, ld, wq, wk, pe, static_cast(qo), - q_tstride, static_cast(ko), static_cast(vo), - kv_tstride, kv_off, eps); - return cudaGetLastError() == cudaSuccess ? 0 : 2; - } - const dim3 grid(T, H); - if (q_f16) - k_qkv_post<<>>(q, k, v, ld, wq, wk, pe, static_cast(qo), - static_cast(qlo), q_tstride, - static_cast(ko), static_cast(vo), kv_tstride, - kv_off, eps); - else - k_qkv_post<<>>(q, k, v, ld, wq, wk, pe, static_cast(qo), nullptr, - q_tstride, - static_cast(ko), static_cast(vo), kv_tstride, - kv_off, eps); - return cudaGetLastError() == cudaSuccess ? 0 : 2; -} - -int qi21_swiglu(void* stream, const float* gu, float* out, int T, int F) { - const int64_t n = (int64_t) T * F; - k_swiglu<<<(unsigned) ((n + 255) / 256), 256, 0, qi_s(stream)>>>(gu, out, F, n); - return cudaGetLastError() == cudaSuccess ? 0 : 2; -} - -int qi21_attn_causal(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride, - float* out, int H, int Lq, int Lk, int causal) { - const size_t smem = (size_t) Lk * sizeof(float); - if (smem > 48 * 1024) return 1; - k_attn_causal<<>>(q, q_tstride, static_cast(k), - static_cast(v), kv_tstride, out, H, Lk, - causal, 1.f / sqrtf((float) QI_D)); - return cudaGetLastError() == cudaSuccess ? 0 : 2; -} - -int qi21_attn_wmma(void* stream, const void* q, const void* qlo, int q_tstride, const void* k, const void* v, - int kv_tstride, float* out, int H, int nq, int nkv) { -#if defined(GGML_USE_HIP) - const dim3 grid((nq + FA_BQ - 1) / FA_BQ, H); - const float sl = (float) (1.0 / sqrt((double) QI_D) * 1.4426950408889634); - if (qlo != nullptr) - k_attn_wmma<<>>(static_cast(q), - static_cast(qlo), q_tstride, - static_cast(k), - static_cast(v), kv_tstride, out, H, - nq, nkv, sl); - else - k_attn_wmma<<>>(static_cast(q), nullptr, q_tstride, - static_cast(k), - static_cast(v), kv_tstride, out, H, - nq, nkv, sl); - return cudaGetLastError() == cudaSuccess ? 0 : 2; -#else - if (qlo != nullptr) return 1; // no hi/lo split on this path - static bool attr = false; - if (!attr) { - if (cudaFuncSetAttribute(k_attn_mma, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) MF_SMEM) != cudaSuccess) - return 2; - attr = true; - } - k_attn_mma<<>>( - static_cast(q), q_tstride, static_cast(k), static_cast(v), kv_tstride, out, - H, nq, nkv, (float) (1.0 / sqrt((double) QI_D) * 1.4426950408889634)); - return cudaGetLastError() == cudaSuccess ? 0 : 2; -#endif -} - -int qi21_memcpy_d2d(void* stream, void* dst, const void* src, size_t n) { - return cudaMemcpyAsync(dst, src, n, cudaMemcpyDeviceToDevice, qi_s(stream)) == cudaSuccess ? 0 : 2; -} - -} // extern "C" diff --git a/tools/image/sdcpp_native/qwen_image_2_1_native.hpp b/tools/image/sdcpp_native/qwen_image_2_1_native.hpp deleted file mode 100644 index ef845a7..0000000 --- a/tools/image/sdcpp_native/qwen_image_2_1_native.hpp +++ /dev/null @@ -1,601 +0,0 @@ -// qwen_image_2_1_native.hpp - Strata's native Qwen-Image-2.1 DiT runner for stable-diffusion.cpp (CUDA / HIP builds). -// -// Copied into src/model/diffusion/ by tools/image/sdcpp_native/apply.py and chosen by model_builders.cpp when the -// model args contain qwen_image_2_1_native=1. sd.cpp keeps the text encoder, the VAE, the sampler and the RNG; this -// runner replaces only QwenImage21Runner::compute (latent + timestep + text condition in, velocity out, on the host). -// -// Per step: the 32 blocks run on the image tokens only. The text prefix (causal within the text, timestep-free: -// its modulation row is the t = 0 one) goes through all blocks once per prompt and leaves each layer's K/V (fp16) -// behind - the same prefix cache sd.cpp keeps. GEMMs are ggml graphs on the runner's backend (the MMQ / BLAS -// kernels sd.cpp uses, same numerics); LayerNorm+modulate, gate+residual, q/k RMSNorm+RoPE, SwiGLU and (on gfx11) -// the image attention are Strata kernels (ggml/src/ggml-cuda/qi21-native.cu) on the backend's stream. Anything this -// runner does not cover (reference images, an unfused MLP, a CPU / Vulkan backend, too little VRAM) goes to the -// stock runner. -#ifndef __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__ -#define __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__ - -#include -#include -#include -#include - -#include "ggml-alloc.h" -#include "ggml-backend.h" -#include "ggml-cuda.h" -#include "gguf.h" -#include "model/diffusion/qwen_image_2_1.hpp" - -extern "C" { -void* qi21_stream(ggml_backend_t backend); -int qi21_has_wmma_attn(ggml_backend_t backend); -int qi21_res_ln_mod(void* stream, float* x, const float* h, const float* g, float* out, const float* m, int T, int C, - float eps); -int qi21_qkv_post(void* stream, const float* q, const float* k, const float* v, int ld, const float* wq, const float* wk, - const float* pe, void* qo, void* qlo, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride, - int kv_off, int T, int H, float eps); -int qi21_swiglu(void* stream, const float* gu, float* out, int T, int F); -int qi21_tanh(void* stream, const float* in, float* out, int n); -int qi21_res_ln_mod2(void* stream, float* x, const float* h, const float* tg, float* out, const float* m, int T, int C, - float eps); -int qi21_attn_causal(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride, - float* out, int H, int Lq, int Lk, int causal); -int qi21_attn_wmma(void* stream, const void* q, const void* qlo, int q_tstride, const void* k, const void* v, - int kv_tstride, float* out, int H, int nq, int nkv); -int qi21_memcpy_d2d(void* stream, void* dst, const void* src, size_t n); -} - -namespace Qwen { - - struct QwenImage21NativeRunner : public QwenImage21Runner { - static constexpr int64_t C = 4096, D = 128, H = 32, F = 12288; - std::string dit_path; - bool disabled = false; // a failure: the stock runner from here on - bool loaded = false; - bool wmma_attn = false; - bool timing = false; - bool said_why = false; - bool qsplit = false; - bool exact_attn = false; - bool fast_ln = true; - bool fuse_qkv = true; - - // weights (our own copy: the stock runner's params are never loaded, they load lazily on first use) - ggml_context* wctx = nullptr; - ggml_backend_buffer_t wbuf = nullptr; - std::map W; - - // activations, sized for t_cap image tokens and l_cap prefix tokens - ggml_context* actx = nullptr; - ggml_backend_buffer_t abuf = nullptr; - int64_t t_cap = 0, l_cap = 0; - ggml_tensor *x, *h, *q, *k, *v, *att, *gu, *mlp, *q16, *kw, *vw, *pe_img, *pe_txt, *latent, *outp, *timein, - *mod, *gates, *scale_out, *ctx_in, *pk, *pv; - - // the prefix cache: per layer K/V of the text tokens (fp16, head-major), for one condition - uint64_t prefix_key = 0; - int64_t prefix_len = -1; - - std::vector gbuf; // ggml graph metadata arena - - QwenImage21NativeRunner(ggml_backend_t backend, const String2TensorStorage& weights, const std::string& prefix, - std::shared_ptr weight_manager, const char* model_args, - std::string dit_path) - : QwenImage21Runner(backend, weights, prefix, weight_manager, model_args), dit_path(std::move(dit_path)) { - timing = getenv("STRATA_QI_TIMING") != nullptr; - qsplit = getenv("STRATA_QI_QSPLIT") != nullptr; // measured: no accuracy gain, +7% step time - exact_attn = getenv("STRATA_QI_EXACT_ATTN") != nullptr; - fuse_qkv = getenv("STRATA_QI_NO_QKV_FUSE") == nullptr; - fast_ln = getenv("STRATA_QI_FAST_LN") != nullptr; // measured: no gain on the 3060 (2.10 vs 2.10 s/step) - gbuf.resize(64 << 20); - } - - ~QwenImage21NativeRunner() override { release(); } - - std::string get_desc() override { return "qwen_image_2_1 (strata native)"; } - - void release() { - if (abuf) ggml_backend_buffer_free(abuf); - if (actx) ggml_free(actx); - if (wbuf) ggml_backend_buffer_free(wbuf); - if (wctx) ggml_free(wctx); - abuf = nullptr; actx = nullptr; wbuf = nullptr; wctx = nullptr; - W.clear(); - loaded = false; - t_cap = l_cap = 0; - prefix_len = -1; - } - - void fail(const char* why) { - LOG_WARN("Qwen Image 2.1 native: %s; using the stock runner", why); - release(); - disabled = true; - } - - ggml_tensor* w(const std::string& name) { - auto it = W.find("model.diffusion_model." + name); - return it == W.end() ? nullptr : it->second; - } - - // ---------------------------------------------------------------- weights - bool load_weights() { - ggml_context* meta = nullptr; - gguf_init_params gp{true, &meta}; - gguf_context* g = gguf_init_from_file(dit_path.c_str(), gp); - if (g == nullptr) return false; - const int64_t n = gguf_get_n_tensors(g); - wctx = ggml_init({(size_t) (n + 8) * ggml_tensor_overhead(), nullptr, true}); - struct Piece { ggml_tensor* t; size_t file_off, dst_off; }; - std::vector plan; - std::map widened; - const size_t base = gguf_get_data_offset(g); - // q, k and v of a block in one tensor when they have the same type (one GEMM, one activation quantize): - // rows stay rows, so the three weights are simply laid one after the other - auto qkv_name = [](int b, const char* w) { - return "model.diffusion_model.transformer_blocks." + std::to_string(b) + ".attn.to_" + w + ".weight"; - }; - std::map> fused_part; // q/k/v name -> (fused, offset) - if (fuse_qkv) { - for (int b = 0; b < config.num_layers; ++b) { - ggml_tensor* tq = ggml_get_tensor(meta, qkv_name(b, "q").c_str()); - ggml_tensor* tk = ggml_get_tensor(meta, qkv_name(b, "k").c_str()); - ggml_tensor* tv = ggml_get_tensor(meta, qkv_name(b, "v").c_str()); - if (!tq || !tk || !tv || tq->type != tk->type || tq->type != tv->type || tq->ne[0] != tk->ne[0] || - tq->ne[1] != tk->ne[1] || tq->ne[1] != tv->ne[1]) - continue; - ggml_tensor* f = ggml_new_tensor_2d(wctx, tq->type, tq->ne[0], 3 * tq->ne[1]); - const std::string fname = "model.diffusion_model.transformer_blocks." + std::to_string(b) + - ".attn.qkv.weight"; - ggml_set_name(f, fname.c_str()); - W[fname] = f; - const size_t nb = ggml_nbytes(tq); - fused_part[qkv_name(b, "q")] = {f, 0}; - fused_part[qkv_name(b, "k")] = {f, nb}; - fused_part[qkv_name(b, "v")] = {f, 2 * nb}; - } - } - for (int64_t i = 0; i < n; ++i) { - const char* name = gguf_get_tensor_name(g, i); - if (strncmp(name, "model.diffusion_model.", 22) != 0) continue; - auto fp = fused_part.find(name); - if (fp != fused_part.end()) { - plan.push_back({fp->second.first, base + gguf_get_tensor_offset(g, i), fp->second.second}); - continue; - } - ggml_tensor* src = ggml_get_tensor(meta, name); - // a 1-D norm weight in BF16 / F16 is kept as F32 (elementwise ops on it then work on every backend) - const bool widen = ggml_n_dims(src) == 1 && src->type != GGML_TYPE_F32; - ggml_tensor* t = widen ? ggml_new_tensor_1d(wctx, GGML_TYPE_F32, src->ne[0]) : ggml_dup_tensor(wctx, src); - if (widen) widened[t] = src->type; - ggml_set_name(t, name); - W[name] = t; - plan.push_back({t, base + gguf_get_tensor_offset(g, i), 0}); - } - wbuf = ggml_backend_alloc_ctx_tensors(wctx, runtime_backend); - if (wbuf == nullptr) { - gguf_free(g); - ggml_free(meta); - return false; - } - FILE* f = fopen(dit_path.c_str(), "rb"); - std::vector stage(64 << 20); - bool ok = f != nullptr; - for (auto& [t, off, dst_off] : plan) { - if (!ok) break; - auto wi = widened.find(t); - const bool part = std::string(ggml_get_name(t)).find(".attn.qkv.") != std::string::npos; - const size_t nb = part ? ggml_nbytes(t) / 3 - : wi == widened.end() ? ggml_nbytes(t) : ggml_row_size(wi->second, t->ne[0]); -#ifdef _WIN32 - ok = _fseeki64(f, (long long) off, SEEK_SET) == 0; -#else - ok = fseeko(f, (off_t) off, SEEK_SET) == 0; -#endif - if (wi != widened.end()) { - std::vector raw(nb); - std::vector f32(t->ne[0]); - ok = fread(raw.data(), 1, nb, f) == nb; - if (ok) { - ggml_get_type_traits(wi->second)->to_float(raw.data(), f32.data(), t->ne[0]); - ggml_backend_tensor_set(t, f32.data(), 0, f32.size() * sizeof(float)); - } - continue; - } - for (size_t done = 0; ok && done < nb;) { - const size_t c = std::min(stage.size(), nb - done); - ok = fread(stage.data(), 1, c, f) == c; - if (ok) ggml_backend_tensor_set(t, stage.data(), dst_off + done, c); - done += c; - } - } - if (f) fclose(f); - gguf_free(g); - ggml_free(meta); - if (!ok) return false; - for (int i = 0; i < config.num_layers; ++i) { - const std::string b = "transformer_blocks." + std::to_string(i) + "."; - if (w(b + "attn.qkv.weight") == nullptr && - (!w(b + "attn.to_q.weight") || !w(b + "attn.to_k.weight") || !w(b + "attn.to_v.weight"))) - return false; - for (const char* s : {"attn.to_out.0.weight", - "attn.norm_q.weight", "attn.norm_k.weight", "img_mlp.gate_up.weight", - "img_mlp.out.weight"}) { - if (w(b + s) == nullptr) return false; - } - if (w(b + "attn.norm_q.weight")->type != GGML_TYPE_F32 || w(b + "attn.norm_k.weight")->type != GGML_TYPE_F32) - return false; - } - for (const char* s : {"img_in.weight", "txt_in.text_norm.weight", "txt_in.in_layer.weight", "txt_in.out_layer.weight", - "time_text_embed.timestep_embedder.linear_1.weight", - "time_text_embed.timestep_embedder.linear_2.weight", "modulation.1.weight", - "norm_out.linear.weight", "proj_out.weight"}) { - if (w(s) == nullptr) return false; - } - LOG_INFO("Qwen Image 2.1 native: %zu tensors, %.2f GB on %s%s", W.size(), - ggml_backend_buffer_get_size(wbuf) / 1e9, ggml_backend_name(runtime_backend), - wmma_attn ? " (Strata attention)" : ""); - return true; - } - - // ---------------------------------------------------------------- activations - bool alloc_acts(int64_t T, int64_t L) { - if (T <= t_cap && L <= l_cap) return true; - if (abuf) ggml_backend_buffer_free(abuf); - if (actx) ggml_free(actx); - t_cap = std::max(T, t_cap); - l_cap = std::max(L, l_cap); - const int64_t R = std::max(t_cap, l_cap); // rows of the shared work buffers - actx = ggml_init({64 * ggml_tensor_overhead(), nullptr, true}); - x = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R); - h = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R); - q = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R); - k = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R); - v = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R); - att = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R); - gu = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 2 * F, R); - mlp = ggml_new_tensor_2d(actx, GGML_TYPE_F32, F, R); - q16 = ggml_new_tensor_3d(actx, GGML_TYPE_F32, D, R, H); // fp16 or fp32 queries, head-major - kw = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D, l_cap + t_cap, H); - vw = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D, l_cap + t_cap, H); - pe_img = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * D / 2, t_cap); - pe_txt = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * D / 2, std::max(l_cap, 1)); - latent = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.in_channels, t_cap); - outp = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.out_channels, t_cap); - timein = ggml_new_tensor_1d(actx, GGML_TYPE_F32, 2); - mod = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * C, 2); - gates = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * C, 2); // tanh(mod), the gate rows used - scale_out = ggml_new_tensor_1d(actx, GGML_TYPE_F32, C); - ctx_in = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.context_dim, std::max(l_cap, 1)); - pk = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D * H, std::max(l_cap, 1), config.num_layers); - pv = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D * H, std::max(l_cap, 1), config.num_layers); - abuf = ggml_backend_alloc_ctx_tensors(actx, runtime_backend); - prefix_len = -1; // the cache lived in the old buffer - return abuf != nullptr; - } - - // ---------------------------------------------------------------- ggml graph helpers - struct G { - ggml_context* ctx; - ggml_cgraph* gf; - }; - G begin() { - ggml_context* c = ggml_init({gbuf.size(), gbuf.data(), true}); - return {c, ggml_new_graph_custom(c, 256, false)}; - } - static ggml_tensor* rows(ggml_context* c, ggml_tensor* t, int64_t n, int64_t first = 0) { - return ggml_view_2d(c, t, t->ne[0], n, t->nb[1], first * t->nb[1]); - } - static void bind(ggml_tensor* node, ggml_tensor* storage, size_t offset = 0) { - node->data = (char*) storage->data + offset; - node->buffer = storage->buffer; - } - // compute a graph on the backend's stream (no wait). Nodes the caller did not bind get scratch space in - // `gu` (only the small prelude / head / txt_in graphs have such nodes, and gu is free then); views get - // their source's memory. - void run(G& g, std::initializer_list outs) { - for (auto* o : outs) ggml_build_forward_expand(g.gf, o); - size_t off = 0; - for (ggml_tensor* t = ggml_get_first_tensor(g.ctx); t; t = ggml_get_next_tensor(g.ctx, t)) { - if (t->view_src != nullptr) { - t->data = (char*) t->view_src->data + t->view_offs; - t->buffer = t->view_src->buffer; - } else if (t->data == nullptr) { - bind(t, gu, off); - off += GGML_PAD(ggml_nbytes(t), 256); - GGML_ASSERT(off <= ggml_nbytes(gu)); - } - } - ggml_backend_graph_compute_async(runtime_backend, g.gf); - ggml_free(g.ctx); - } - // dst[N x n] = W . src[K x n] (rows `first..`) - void gemm(G& g, ggml_tensor* weight, ggml_tensor* src, ggml_tensor* dst, int64_t n) { - ggml_tensor* y = ggml_mul_mat(g.ctx, weight, rows(g.ctx, src, n)); - bind(y, dst); - ggml_build_forward_expand(g.gf, y); - } - - // ---------------------------------------------------------------- the transformer blocks - // rows [0, n) of x are the tokens; mrow = 0 (image) or 1 (text prefix); pe: per-token rope table; - // attention: image -> [cached prefix K/V of the layer, these tokens' K/V]; prefix -> causal over itself, and - // each layer's K/V goes into the prefix cache. - bool blocks_pass(int64_t n, int mrow, ggml_tensor* pe, int64_t L) { - void* s = qi21_stream(runtime_backend); - const float* m = (const float*) mod->data + mrow * 4 * C; - const float *m0 = m, *m1 = m + C, *m2 = m + 2 * C, *m3 = m + 3 * C; - const float* tgr = (const float*) gates->data + mrow * 4 * C; // tanh of the same row - const float *t1 = tgr + C, *t3 = tgr + 3 * C; - auto res_ln = [&](float* xx, const float* hh, const float* graw, const float* tgate, float* out, - const float* mm) { - return fast_ln ? qi21_res_ln_mod2(s, xx, hh, tgate, out, mm, (int) n, (int) C, 1e-6f) - : qi21_res_ln_mod(s, xx, hh, graw, out, mm, (int) n, (int) C, 1e-6f); - }; - const bool prefix = mrow == 1; - const int64_t kvt = prefix ? n : L + n; // keys per head in the work K/V - const bool use_wmma = !prefix && wmma_attn && !exact_attn; - // fp16 queries carry ~5e-4 relative error into logits that reach the tens here: the low half of each - // query (q - fp16(q)) goes through a second WMMA (STRATA_QI_QSPLIT=0 drops it). It sits in the fp32-sized - // q16 buffer right after the fp16 high half. - const size_t qlo_off = (size_t) H * n * D * sizeof(ggml_fp16_t); - float* X = (float*) x->data; - float* Hh = (float*) h->data; - int rc = res_ln(X, nullptr, nullptr, nullptr, Hh, m0); - for (int i = 0; i < config.num_layers && rc == 0; ++i) { - const std::string b = "transformer_blocks." + std::to_string(i) + "."; - ggml_tensor* wqkv = w(b + "attn.qkv.weight"); - const float *qs = (const float*) q->data, *ks = (const float*) k->data, *vs = (const float*) v->data; - int ldq = (int) C; - { - G g = begin(); - if (wqkv != nullptr) { // [3C x n] into gu (free here), q | k | v per token - gemm(g, wqkv, h, gu, n); - qs = (const float*) gu->data; - ks = qs + C; - vs = qs + 2 * C; - ldq = (int) (3 * C); - } else { - gemm(g, w(b + "attn.to_q.weight"), h, q, n); - gemm(g, w(b + "attn.to_k.weight"), h, k, n); - gemm(g, w(b + "attn.to_v.weight"), h, v, n); - } - run(g, {}); - } - const int64_t off = prefix ? 0 : L; - rc = qi21_qkv_post(s, qs, ks, vs, ldq, - (const float*) w(b + "attn.norm_q.weight")->data, - (const float*) w(b + "attn.norm_k.weight")->data, (const float*) pe->data, q16->data, - use_wmma && qsplit ? (char*) q16->data + qlo_off : nullptr, use_wmma ? 1 : 0, (int) n, kw->data, vw->data, (int) kvt, (int) off, (int) n, (int) H, - 1e-6f); - if (rc) break; - const size_t pbytes = (size_t) L * D * sizeof(ggml_fp16_t); // one head's prefix rows - if (prefix) { - // keep this layer's text K/V (head-major rows 0..n) in the prefix cache, as [H][n][D] - for (int64_t hh = 0; hh < H && rc == 0; ++hh) { - char* pkd = (char*) pk->data + i * pk->nb[2] + hh * n * D * sizeof(ggml_fp16_t); - char* pvd = (char*) pv->data + i * pv->nb[2] + hh * n * D * sizeof(ggml_fp16_t); - rc = qi21_memcpy_d2d(s, pkd, (char*) kw->data + hh * kvt * D * sizeof(ggml_fp16_t), - n * D * sizeof(ggml_fp16_t)); - rc |= qi21_memcpy_d2d(s, pvd, (char*) vw->data + hh * kvt * D * sizeof(ggml_fp16_t), - n * D * sizeof(ggml_fp16_t)); - } - if (rc) break; - rc = qi21_attn_causal(s, (const float*) q16->data, (int) n, kw->data, vw->data, (int) kvt, - (float*) att->data, (int) H, (int) n, (int) n, 1); - } else { - for (int64_t hh = 0; hh < H && L > 0 && rc == 0; ++hh) { - const char* pks = (const char*) pk->data + i * pk->nb[2] + hh * pbytes; - const char* pvs = (const char*) pv->data + i * pv->nb[2] + hh * pbytes; - rc = qi21_memcpy_d2d(s, (char*) kw->data + hh * kvt * D * sizeof(ggml_fp16_t), pks, pbytes); - rc |= qi21_memcpy_d2d(s, (char*) vw->data + hh * kvt * D * sizeof(ggml_fp16_t), pvs, pbytes); - } - if (rc) break; - if (exact_attn) { - // reference: fp32 attention (fp16 K/V as every path has them), slow; STRATA_QI_EXACT_ATTN=1 - rc = qi21_attn_causal(s, (const float*) q16->data, (int) n, kw->data, vw->data, (int) kvt, - (float*) att->data, (int) H, (int) n, (int) kvt, 0); - } else if (use_wmma) { - rc = qi21_attn_wmma(s, q16->data, qsplit ? (char*) q16->data + qlo_off : nullptr, (int) n, - kw->data, vw->data, (int) kvt, (float*) att->data, (int) H, (int) n, - (int) kvt); - } else { - // ggml's flash attention (what sd.cpp runs on this backend) - G g = begin(); - ggml_tensor* qt = ggml_view_3d(g.ctx, q16, D, n, H, D * sizeof(float), n * D * sizeof(float), 0); - ggml_tensor* kt = ggml_view_3d(g.ctx, kw, D, kvt, H, D * sizeof(ggml_fp16_t), - kvt * D * sizeof(ggml_fp16_t), 0); - ggml_tensor* vt = ggml_view_3d(g.ctx, vw, D, kvt, H, D * sizeof(ggml_fp16_t), - kvt * D * sizeof(ggml_fp16_t), 0); - ggml_tensor* o = ggml_flash_attn_ext(g.ctx, qt, kt, vt, nullptr, 1.f / sqrtf((float) D), 0, 0); - ggml_flash_attn_ext_set_prec(o, GGML_PREC_F32); - if (!ggml_backend_supports_op(runtime_backend, o)) { - ggml_free(g.ctx); - rc = 3; - break; - } - bind(o, att); - run(g, {o}); - } - } - if (rc) break; - { - G g = begin(); - gemm(g, w(b + "attn.to_out.0.weight"), att, h, n); - run(g, {}); - } - rc = res_ln(X, Hh, m1, t1, Hh, m2); - if (rc) break; - { - G g = begin(); - gemm(g, w(b + "img_mlp.gate_up.weight"), h, gu, n); - run(g, {}); - } - rc = qi21_swiglu(s, (const float*) gu->data, (float*) mlp->data, (int) n, (int) F); - if (rc) break; - { - G g = begin(); - gemm(g, w(b + "img_mlp.out.weight"), mlp, h, n); - run(g, {}); - } - const bool last = i + 1 == config.num_layers; - rc = res_ln(X, Hh, m3, t3, last ? nullptr : Hh, m0); - } - if (rc) LOG_WARN("Qwen Image 2.1 native: a kernel failed (%d)", rc); - return rc == 0; - } - - // ---------------------------------------------------------------- compute - sd::Tensor compute(int n_threads, const DiffusionParams& inputs) override { - if (disabled) return QwenImage21Runner::compute(n_threads, inputs); - const auto& xin = tensor_or_empty(inputs.x); - const auto& context = tensor_or_empty(inputs.context); - const auto* extra = std::get_if(&inputs.extra); - const bool refs = inputs.ref_latents && inputs.ref_image_params.pass_to_dit && !inputs.ref_latents->empty(); - const char* why = nullptr; - if (xin.empty() || context.empty() || xin.dim() != 4 || xin.shape()[3] != 1 || - xin.shape()[2] != config.in_channels || context.shape()[0] != config.context_dim || - tensor_or_empty(inputs.timesteps).numel() != 1) - why = "unexpected input shapes"; - else if (refs) - why = "reference images"; - else if (!config.fused_mlp) - why = "an unfused MLP"; - else if (!ggml_backend_is_cuda(runtime_backend)) - why = "not a CUDA / HIP backend"; - if (why != nullptr) { - if (!said_why) LOG_INFO("Qwen Image 2.1 native: %s; this step runs on the stock runner", why); - said_why = true; - return QwenImage21Runner::compute(n_threads, inputs); - } - const auto t0 = std::chrono::steady_clock::now(); - if (!loaded) { - wmma_attn = qi21_has_wmma_attn(runtime_backend) && getenv("STRATA_QI_GGML_ATTN") == nullptr; - if (!load_weights()) { - fail("could not load the DiT weights onto the GPU"); - return QwenImage21Runner::compute(n_threads, inputs); - } - loaded = true; - } - const int64_t Wd = xin.shape()[0], Hd = xin.shape()[1], T = Wd * Hd, Lt = context.shape()[1]; - if (!alloc_acts(T, Lt)) { - fail("not enough GPU memory for the activations"); - return QwenImage21Runner::compute(n_threads, inputs); - } - // rope tables: sd.cpp's own layout and embedding for [text, image] - std::vector> shapes{{Hd, Wd}}; - QwenImage21Layout layout; - try { - layout = QwenImage21Layout::build(Lt, tensor_or_empty(extra ? extra->image_slots : nullptr), shapes); - } catch (const std::exception&) { - return QwenImage21Runner::compute(n_threads, inputs); - } - if (layout.segments.size() != 2 || layout.segments[0].image_index >= 0 || layout.prefix_length != Lt) { - if (!said_why) LOG_INFO("Qwen Image 2.1 native: images in the prompt; this step runs on the stock runner"); - said_why = true; - return QwenImage21Runner::compute(n_threads, inputs); - } - Rope::Embedding emb; - emb.ids.assign(layout.positions.begin(), layout.positions.end()); - emb.positions.token_count = emb.ids.size(); - for (auto region : layout.rope_layout.images) emb.positions.images.push_back(region); - emb.values = Rope::embed_nd(emb.ids, 1, 10000.f, config.axes_dim, emb.layout, &emb.frequencies); - std::vector pe_all = finish_rope_pe(std::move(emb)); - const size_t per_tok = 4 * D / 2; - if (pe_all.size() != (size_t) (Lt + T) * per_tok) { - fail("unexpected rope table size"); - return QwenImage21Runner::compute(n_threads, inputs); - } - ggml_backend_tensor_set(pe_img, pe_all.data() + Lt * per_tok, 0, T * per_tok * sizeof(float)); - // timestep embedding -> modulation rows (image: t, prefix: 0) and the final scale - const float tv[2] = {inputs.timesteps->data()[0], 0.f}; - ggml_backend_tensor_set(timein, tv, 0, sizeof(tv)); - { - G g = begin(); - ggml_tensor* te = ggml_timestep_embedding(g.ctx, timein, 256, 10000); - te = ggml_mul_mat(g.ctx, w("time_text_embed.timestep_embedder.linear_1.weight"), te); - te = ggml_silu(g.ctx, te); - te = ggml_mul_mat(g.ctx, w("time_text_embed.timestep_embedder.linear_2.weight"), te); - te = ggml_silu(g.ctx, te); - ggml_tensor* md = ggml_mul_mat(g.ctx, w("modulation.1.weight"), te); - ggml_tensor* sc = ggml_mul_mat(g.ctx, w("norm_out.linear.weight"), - ggml_view_1d(g.ctx, te, C, 0)); - bind(md, mod); - bind(sc, scale_out); - run(g, {md, sc}); - } - if (qi21_tanh(qi21_stream(runtime_backend), (const float*) mod->data, (float*) gates->data, - (int) (8 * C)) != 0) { - fail("the gate kernel failed"); - return QwenImage21Runner::compute(n_threads, inputs); - } - // the text prefix: once per condition - uint64_t key = extra != nullptr ? extra->prefix_id : 0; - { - uint64_t hsh = 1469598103934665603ull; - const unsigned char* p = (const unsigned char*) context.data(); - const size_t nb = context.numel() * sizeof(float); - for (size_t i = 0; i < nb; i += 61) hsh = (hsh ^ p[i]) * 1099511628211ull; - key = key * 31 + hsh; - } - if (key != prefix_key || prefix_len != Lt) { - ggml_backend_tensor_set(pe_txt, pe_all.data(), 0, Lt * per_tok * sizeof(float)); - ggml_backend_tensor_set(ctx_in, context.data(), 0, Lt * config.context_dim * sizeof(float)); - { - // txt_in: zero-centered RMSNorm (weight + 1) -> in_layer -> GELU -> out_layer, into x - G g = begin(); - ggml_tensor* t = ggml_rms_norm(g.ctx, rows(g.ctx, ctx_in, Lt), 1e-6f); - ggml_tensor* nw = ggml_scale_bias(g.ctx, w("txt_in.text_norm.weight"), 1.f, 1.f); - t = ggml_mul(g.ctx, t, nw); - t = ggml_mul_mat(g.ctx, w("txt_in.in_layer.weight"), t); - t = ggml_gelu(g.ctx, t); - t = ggml_mul_mat(g.ctx, w("txt_in.out_layer.weight"), t); - bind(t, x); - run(g, {t}); - } - if (!blocks_pass(Lt, 1, pe_txt, 0)) { - fail("the text prefix pass failed"); - return QwenImage21Runner::compute(n_threads, inputs); - } - prefix_key = key; - prefix_len = Lt; - } - // the image tokens: patchify (patch 1: token h*W + w, channels), img_in, the blocks, the output head - { - std::vector tok((size_t) T * config.in_channels); - const float* xs = xin.data(); - for (int64_t c = 0; c < config.in_channels; ++c) - for (int64_t t = 0; t < T; ++t) tok[(size_t) t * config.in_channels + c] = xs[(size_t) c * T + t]; - ggml_backend_tensor_set(latent, tok.data(), 0, tok.size() * sizeof(float)); - G g = begin(); - gemm(g, w("img_in.weight"), latent, x, T); - run(g, {}); - } - if (!blocks_pass(T, 0, pe_img, Lt)) { - fail("the image pass failed"); - return QwenImage21Runner::compute(n_threads, inputs); - } - { - G g = begin(); - ggml_tensor* t = ggml_norm(g.ctx, rows(g.ctx, x, T), 1e-6f); - t = ggml_mul(g.ctx, t, ggml_scale_bias(g.ctx, scale_out, 1.f, 1.f)); - t = ggml_mul_mat(g.ctx, w("proj_out.weight"), t); - bind(t, outp); - run(g, {t}); - } - ggml_backend_synchronize(runtime_backend); - std::vector o((size_t) T * config.out_channels); - ggml_backend_tensor_get(outp, o.data(), 0, o.size() * sizeof(float)); - sd::Tensor result({Wd, Hd, config.out_channels, 1}); - float* r = result.data(); - for (int64_t c = 0; c < config.out_channels; ++c) - for (int64_t t = 0; t < T; ++t) r[(size_t) c * T + t] = o[(size_t) t * config.out_channels + c]; - if (timing) { - const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - LOG_INFO("Qwen Image 2.1 native: step %.1f ms (%lld image tokens, prefix %lld)", ms, (long long) T, - (long long) Lt); - } - return restore_trailing_singleton_dims(std::move(result), xin.dim()); - } - }; - -} // namespace Qwen - -#endif // __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__ diff --git a/tools/requirements.txt b/tools/requirements.txt new file mode 100644 index 0000000..d5b592a --- /dev/null +++ b/tools/requirements.txt @@ -0,0 +1,3 @@ +# Offline tools only (tools/iq_pack.py, mtp_*.py, make_profile*.py, ...). Not needed to build or run the engines. +numpy +regex diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py deleted file mode 100644 index ed3a782..0000000 --- a/tools/strata_mcp.py +++ /dev/null @@ -1,1885 +0,0 @@ -#!/usr/bin/env python3 -"""tools/strata_mcp.py - an MCP server that lets an AI assistant install, start, check and stop PolyStrata. - - claude mcp add strata -- python /path/to/PolyStrata/tools/strata_mcp.py - -Add it to Claude Code, Claude Desktop, Cursor, VS Code, Codex ... (docs/MCP_SERVER.md has every client's snippet) and -ask your AI "install PolyStrata for this PC", "start PolyStrata", "is PolyStrata running?". It speaks MCP (JSON-RPC 2.0, one -message per line) over stdin/stdout, uses the Python standard library only (it runs before setup made .venv; Python -3.10 or newer), and offers a fixed set of tools: strata_status, strata_models, strata_install, strata_start, -strata_stop, strata_logs, strata_benchmark, strata_connect_info. - -Safety: no tool takes a shell command or a free path. Every argument is checked against setup.py's own choices -(models, families, contexts ...); the only path argument (install's data_dir) must be the PolyStrata data folder, a folder -inside the PolyStrata folder, or a new folder named PolyStrata* outside the system folders. Setup and the model run as -background processes this server starts itself; it keeps their process id and start time in .strata-mcp/ and only -ever stops a process it started (a PolyStrata started elsewhere, e.g. from its own window, is only asked over its API to -unload the model). - -Not to be confused with serve/mcp.py: that is PolyStrata's MCP *client* (the model calling your tools from the chat page). -This file is an MCP *server* for the AI assistant you already use. -""" -from __future__ import annotations - -import argparse -import importlib.util -import json -import os -import platform -import re -import shutil -import signal -import subprocess -import sys -import threading -import time -import traceback -import urllib.error -import urllib.request -from pathlib import Path - -PROTOCOL = "2025-06-18" -PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05") # the revisions this server answers in -VERSION = "0.1.0" -WIN = os.name == "nt" -DEFAULT_ROOT = Path(__file__).resolve().parent.parent -DEFAULT_PORT = 8080 -STATE_DIR = ".strata-mcp" # in the PolyStrata folder (git-ignored) - -# What setup.py offers, used only when setup.py cannot be imported (the numbers are setup's MODELS / FAMILIES / -# CONTEXTS; tools/test_strata_mcp.py checks they still match). -FALLBACK_MODELS = { - "Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0, "families": ("qwen",)}, - "IQ2_XS": {"about": "2-bit i-quant, a little better quality, close in speed", "download_gb": 68.0, "ram_gb": 48, - "arena_gb": 35.5}, - "IQ3_XXS": {"about": "3-bit i-quant, better quality, slower (more CPU work per token)", "download_gb": 75.8, - "ram_gb": 60, "arena_gb": 42.9}, - "IQ3_S": {"about": "3.5-bit i-quant, the best quality (matches the full model), the slowest; needs a 64 GB PC " - "with little else running", "download_gb": 83.6, "ram_gb": 62, "arena_gb": 50.3}, - "IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4, - "ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)}, - "UD-IQ4_XS": {"about": "~4-bit i-quant (Unsloth Dynamic), between IQ3_S and UD-Q4_K_XL in quality; on a PC with " - "less than ~80 GB of RAM part of its experts are read from the SSD", - "download_gb": 93.7, "ram_gb": 48, "arena_gb": 59.5, "families": ("unsloth",), "budget": True, - "vision": True}, - "3.0BIT": {"about": "the whole model: 3-bit GSQ-RCO experts, Q4_K attention", "download_gb": 113.6, - "ram_gb": 96, "arena_gb": 107.2, "families": ("glm",)}, - "UD-IQ2_XXS": {"about": "the whole model at about 2 bits (Unsloth): less RAM, reads faster, writes slower", - "download_gb": 101.8, "ram_gb": 82, "arena_gb": 92.5, "families": ("glm",)}, - "REAP50-Q3_K_M": {"about": "half the routed experts (REAP50), 3-bit K-quant: less RAM", "download_gb": 78.8, - "ram_gb": 60, "arena_gb": 72.1, "families": ("glm",)}, - "UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic): K-quant experts, between UD-IQ4_XS and UD-Q5_K_XL in quality", - "download_gb": 111.3, "ram_gb": 48, "arena_gb": 77.0, "families": ("unsloth",), "budget": True, - "vision": True}, # #967: images allowed (setup warns: untested with this file) - "UD-Q5_K_XL": {"about": "5-bit (Unsloth Dynamic): Q5_K experts with Q8_0 downs, close to Q8_0 in quality", - "download_gb": 158.3, "ram_gb": 108, "arena_gb": 98.4, "families": ("unsloth",), "budget": True, - "vision": True}, - "UD-Q6_K_XL": {"about": "6-bit (Unsloth Dynamic): Q6_K experts with Q8_0 downs", - "download_gb": 169.2, "ram_gb": 118, "arena_gb": 109.2, "families": ("unsloth",), "budget": True, - "vision": True}, - "Q8_0": {"about": "8-bit, the reference quality (every expert Q8_0); for a 192 GB PC", - "download_gb": 188.2, "ram_gb": 136, "arena_gb": 128.3, "families": ("unsloth",), "budget": True, - "vision": True}, - "NVFP4": {"about": "4-bit NVFP4 experts, GPTQ (sergqwer's strata-nvfp4 pack); RTX 50 has FP4 tensor cores, other " - "NVIDIA cards run it at 8-bit precision", "download_gb": 128.0, "ram_gb": 80, "arena_gb": 68.0, - "families": ("nvfp4",), "vision": True}, - "NVFP4-NVIDIA": {"about": "NVIDIA's own NVFP4 checkpoint (plain rounding), converted by sergqwer; the same size " - "and speed as NVFP4", "download_gb": 128.0, "ram_gb": 80, "arena_gb": 68.0, - "families": ("nvfp4",), "vision": True}, -} -FALLBACK_FAMILIES = { - "qwen": {"title": "Qwen3.8-Flash-Next", "about": "the original model", "tag": ""}, - "swift": {"title": "Swift 1.5", "about": "thinks much shorter (-63% thinking tokens, 1.8x sooner answers by its " - "authors' numbers)", "tag": "swift-"}, - "coder": {"title": "Qwen3.8-Flash-Next Coder", "about": "half the experts (code, tools, images kept): needs ~32 GB " - "of RAM, faster; weaker outside coding", "tag": "coder-"}, - "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "about": "UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL or Q8_0 " - "(94 to 188 GB downloads): every expert in RAM from " - "~80 GB (UD-IQ4_XS) to ~136 GB (Q8_0) of RAM, else " - "part of them read from the SSD", - "tag": "unsloth-", "vision": True}, - "nvfp4": {"title": "Qwen3.8-Flash-Next (NVFP4)", "about": "4-bit NVFP4 experts, NVIDIA cards; a 128 GB download, " - "~80 GB of RAM to keep every expert in RAM", - "tag": "nvfp4-"}, - "glm": {"title": "GLM 5.3 Flash", "about": "another model, with its own engine: Linux, one NVIDIA card (run on " - "32 GB), 64-128 GB of RAM", "tag": "glm-", "engine": "poly", - "vision": False, "experimental": True}, - "deepseek": {"title": "DeepSeek V4 Flash", "about": "another model on GLM's engine: Linux, one NVIDIA card (run on " - "32 GB), ~72 GB of RAM beside it; a 91 GB download, no images", - "tag": "dsv4-", "engine": "poly", "vision": False, "experimental": True, - "models": {"UD-IQ2_XXS": {"about": "2-bit i-quant experts (Unsloth Dynamic), 3-bit and MXFP4 where " - "they write", "download_gb": 90.9, "ram_gb": 72, "arena_gb": 83.9}}}, - "lfm25": {"title": "LFM2.5-24B-A2B", "about": "on the strata-poly engine: one NVIDIA card, Linux or Windows; a " - "15 GB file, ~20 GB of RAM beside an 8 GB card; four other sizes " - "too, no images", - "tag": "lfm25-", "engine": "poly", "vision": False, "experimental": True, - "models": {"UD-Q4_K_XL": {"about": "4-bit experts (Unsloth Dynamic), 5- and 6-bit where they write", - "download_gb": 14.9, "ram_gb": 20, "arena_gb": 14.0}, - "UD-Q3_K_XL": {"about": "3-bit i-quant experts, 4-bit where they write: the least RAM", - "download_gb": 10.9, "ram_gb": 16, "arena_gb": 10.2}, - "QAD-Q4_0": {"about": "Liquid AI's 4-bit file, trained for that quantization", - "download_gb": 13.6, "ram_gb": 18, "arena_gb": 12.9}, - "UD-Q6_K_XL": {"about": "6-bit experts, 8-bit where they write", - "download_gb": 21.9, "ram_gb": 27, "arena_gb": 20.9}, - "Q8_0": {"about": "8-bit throughout: the closest to the model as trained", - "download_gb": 25.5, "ram_gb": 31, "arena_gb": 24.4}}}, - # a family with sizes of its own ("models"): two of these have a size of one name - "qwen36": {"title": "Qwen3.6-35B-A3B", "about": "on the strata-poly engine: one NVIDIA card, Linux or Windows; a " - "17 GB file, ~21 GB of RAM beside an 8 GB card; a smaller and a " - "larger size too", - "tag": "qwen36-", "engine": "poly", "vision": True, "experimental": True, - "models": {"UD-Q3_K_M": {"about": "3-bit experts (Unsloth Dynamic), its draft block in the file", - "download_gb": 17.1, "ram_gb": 21, "arena_gb": 14.6}, - "UD-Q2_K_XL": {"about": "2- and 3-bit i-quant experts (Unsloth Dynamic): the least RAM", - "download_gb": 12.6, "ram_gb": 17, "arena_gb": 10.8}, - "UD-Q4_K_M": {"about": "4-bit experts (Unsloth Dynamic), 5- and 6-bit where they write", - "download_gb": 22.7, "ram_gb": 27, "arena_gb": 20.1}}}, - "ornith": {"title": "Ornith 1.5 35B-A3B", "about": "Qwen3.6-35B-A3B's architecture, other weights; a 17 GB file, " - "~22 GB of RAM beside an 8 GB card; a smaller and a larger " - "size too", "tag": "ornith-", - "engine": "poly", "vision": True, "experimental": True, - "models": {"APEX-I-COMPACT": {"about": "3- and 4-bit K-quant experts (APEX), its draft block in the " - "file", "download_gb": 17.4, "ram_gb": 22, "arena_gb": 15.8}, - "APEX-I-MINI": {"about": "2- and 3-bit experts (APEX): the least RAM", - "download_gb": 14.4, "ram_gb": 18, "arena_gb": 12.9}, - "APEX-I-QUALITY": {"about": "4- to 6-bit experts (APEX)", - "download_gb": 23.7, "ram_gb": 28, "arena_gb": 21.6}}}, - "gemma4": {"title": "Gemma 4 26B-A4B", "about": "on the strata-poly engine too; a 13 GB file, ~18 GB of RAM beside an 8 GB " - "card; a smaller and a larger size too", "tag": "gemma4-", - "engine": "poly", "vision": True, "experimental": True, - "models": {"UD-Q3_K_M": {"about": "3-bit experts (Unsloth Dynamic), and Google's draft model for it", - "download_gb": 13.2, "ram_gb": 18, "arena_gb": 10.3}, - "UD-Q2_K_XL": {"about": "2-bit i-quant experts (Unsloth Dynamic): the least RAM; the same " - "draft model", "download_gb": 11.0, "ram_gb": 15, "arena_gb": 8.7}, - "UD-Q4_K_M": {"about": "4- and 5-bit experts (Unsloth Dynamic); the same draft model", - "download_gb": 17.4, "ram_gb": 21, "arena_gb": 14.3}}}, - "tiel": {"title": "Tiel Coder 35B-A3B", "about": "Ornith 1.5 quantized for coding, with the Sharp chat template; a " - "17 GB file, ~21 GB of RAM beside an 8 GB card; a smaller and a " - "larger size too", "tag": "tiel-", - "engine": "poly", "vision": True, "experimental": True, - "models": {"UD-Q3_K_XL": {"about": "3-bit i-quant experts, 4-bit where they write; its draft block in " - "the file", "download_gb": 17.2, "ram_gb": 21, "arena_gb": 14.6}, - "UD-IQ3_XXS": {"about": "2-bit i-quant experts, 3-bit where they write: the least RAM", - "download_gb": 13.6, "ram_gb": 18, "arena_gb": 11.5}, - "UD-Q4_K_XL": {"about": "4-bit experts, 5- and 6-bit where they write", - "download_gb": 22.7, "ram_gb": 27, "arena_gb": 20.0}}}, - "minicpmv": {"title": "MiniCPM-V 4.7 35B-A3B", "about": "Qwen3.6-35B-A3B's architecture, OpenBMB's weights, and it " - "reads pictures too; a 22 GB file, ~25 GB of RAM beside an " - "8 GB card; a smaller and a larger size too", - "tag": "minicpmv-", "engine": "poly", "vision": True, "experimental": True, - "models": {"Q4_K_M": {"about": "4-bit experts (K-quant), 5- and 6-bit where they write", - "download_gb": 21.2, "ram_gb": 25, "arena_gb": 19.5}, - "mix_q3gud_im": {"about": "3- and 4-bit experts (imatrix mix): the least RAM", - "download_gb": 15.5, "ram_gb": 19, "arena_gb": 13.8}, - "Q6_K": {"about": "6-bit experts (K-quant)", - "download_gb": 28.5, "ram_gb": 31, "arena_gb": 26.4}}}, -} -FALLBACK_CONTEXTS = [8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288] -BENCH_PROMPT = ("Write a short story (about 300 words) about a lighthouse keeper who finds a message in a bottle. " - "Plain prose, no title.") - -if WIN: - import ctypes - from ctypes import wintypes - - _k32 = ctypes.WinDLL("kernel32", use_last_error=True) - _k32.OpenProcess.restype = wintypes.HANDLE - _k32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) - _k32.GetProcessTimes.argtypes = (wintypes.HANDLE, *(ctypes.POINTER(wintypes.FILETIME),) * 4) - _k32.GetExitCodeProcess.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)) - _k32.TerminateProcess.argtypes = (wintypes.HANDLE, wintypes.UINT) - _k32.WaitForSingleObject.argtypes = (wintypes.HANDLE, wintypes.DWORD) - _k32.CloseHandle.argtypes = (wintypes.HANDLE,) - _QUERY, _TERMINATE, _SYNCHRONIZE, _STILL_ACTIVE = 0x1000, 0x0001, 0x00100000, 259 - CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW, CREATE_BREAKAWAY_FROM_JOB = 0x200, 0x08000000, 0x01000000 - - -def log(msg: str) -> None: - """Diagnostics go to stderr: stdout carries only the protocol.""" - try: - sys.stderr.write(f"[strata-mcp] {msg}\n") - sys.stderr.flush() - except (OSError, ValueError): - pass - - -# ------------------------------------------------------------------------------------------------ processes -def proc_identity(pid) -> str | None: - """A token for a RUNNING process: its start time (so a reused process id is never mistaken for ours), or None - when no such process runs.""" - try: - pid = int(pid) - except (TypeError, ValueError): - return None - if pid <= 0: - return None - if WIN: - h = _k32.OpenProcess(_QUERY, False, pid) - if not h: - return None - try: - code = wintypes.DWORD() - if not _k32.GetExitCodeProcess(h, ctypes.byref(code)) or code.value != _STILL_ACTIVE: - return None - c, e, k, u = (wintypes.FILETIME() for _ in range(4)) - if not _k32.GetProcessTimes(h, ctypes.byref(c), ctypes.byref(e), ctypes.byref(k), ctypes.byref(u)): - return None - return f"win:{(c.dwHighDateTime << 32) | c.dwLowDateTime}" - finally: - _k32.CloseHandle(h) - stat = Path(f"/proc/{pid}/stat") - if Path("/proc/self/stat").exists(): - try: - fields = stat.read_text().rsplit(")", 1)[1].split() - except (OSError, IndexError): - return None - if fields[0] in ("Z", "X"): # a zombie has ended - return None - return f"linux:{fields[19]}" # field 22 of stat: the start time in clock ticks - try: # elsewhere (no /proc): alive, without a start time - os.kill(pid, 0) - return "pid" - except OSError: - return None - - -def proc_alive(pid, ident) -> bool: - return bool(ident) and proc_identity(pid) == ident - - -def proc_terminate(pid, ident) -> bool: - """Ask a process WE started to end (POSIX: SIGTERM, the server's clean path; Windows: TerminateProcess). Never - touches a process whose start time differs from the one recorded.""" - if not proc_alive(pid, ident): - return False - if WIN: - h = _k32.OpenProcess(_TERMINATE | _QUERY, False, int(pid)) - if not h: - return False - try: - return bool(_k32.TerminateProcess(h, 1)) - finally: - _k32.CloseHandle(h) - try: - os.kill(int(pid), signal.SIGTERM) - return True - except OSError: - return False - - -def proc_kill_tree(pid, ident) -> bool: - """End a process WE started together with the processes it started (setup's pip / cmake, the engine).""" - if not proc_alive(pid, ident): - return False - if WIN: - r = subprocess.run(["taskkill", "/PID", str(int(pid)), "/T", "/F"], capture_output=True, - creationflags=CREATE_NO_WINDOW) - return r.returncode == 0 - try: - os.killpg(int(pid), signal.SIGKILL) # started as a session leader: its group is its own - return True - except OSError: - try: - os.kill(int(pid), signal.SIGKILL) - return True - except OSError: - return False - - -def end_group_leftovers(pgid) -> None: - """POSIX: after the server WE started (a session leader) is gone, end what is left of its process group - an - engine it started but could not close (e.g. stopped while loading, before its own SIGTERM handler existed). - While any member lives, the group id cannot belong to anybody else.""" - if WIN or not pgid: - return - for sig, wait in ((signal.SIGTERM, 20.0), (signal.SIGKILL, 5.0)): - try: - os.killpg(int(pgid), sig) - except OSError: - return # no such group left - end = time.time() + wait - while time.time() < end: - try: - os.killpg(int(pgid), 0) - except OSError: - return - time.sleep(0.25) - - -def wait_gone(pid, ident, seconds: float) -> bool: - end = time.time() + seconds - while time.time() < end: - if not proc_alive(pid, ident): - return True - time.sleep(0.25) - return not proc_alive(pid, ident) - - -def spawn_detached(cmd: list, cwd: Path, log_path: Path, env: dict | None = None) -> subprocess.Popen: - """Start a background process whose output goes to log_path. It keeps running when the AI client (and this - server) ends: its own process group / session, no console window on Windows.""" - log_path.parent.mkdir(parents=True, exist_ok=True) - with open(log_path, "ab") as logf: - kw = dict(cwd=str(cwd), stdin=subprocess.DEVNULL, stdout=logf, stderr=subprocess.STDOUT, - env=env, close_fds=True) - if WIN: - flags = CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW - try: # out of the AI client's job, if it lets us - return subprocess.Popen(cmd, creationflags=flags | CREATE_BREAKAWAY_FROM_JOB, **kw) - except OSError: - return subprocess.Popen(cmd, creationflags=flags, **kw) - return subprocess.Popen(cmd, start_new_session=True, **kw) - - -def run_quiet(cmd, timeout=30) -> str: - """A command's stdout ('' when it is missing or fails), without a console window flashing up on Windows.""" - try: - return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL, - creationflags=CREATE_NO_WINDOW if WIN else 0).stdout or "" - except (OSError, subprocess.SubprocessError, ValueError): - return "" - - -def read_tail(path: Path, lines: int, max_bytes: int = 512 * 1024) -> list[str]: - """The last lines of a log; a progress line rewritten with \\r counts as its last version.""" - try: - with open(path, "rb") as f: - f.seek(0, os.SEEK_END) - size = f.tell() - f.seek(max(0, size - max_bytes)) - data = f.read().decode("utf-8", "replace") - except OSError: - return [] - out = [] - for raw in data.split("\n"): - part = [p for p in raw.split("\r") if p.strip()] - if part: - out.append(part[-1].rstrip()) - return out[-lines:] - - -def dir_size_gb(path: Path, limit_files: int = 20000) -> float: - total, n = 0, 0 - for base, _dirs, files in os.walk(path): - for f in files: - try: - total += os.stat(os.path.join(base, f)).st_size - except OSError: - pass - n += 1 - if n >= limit_files: - return round(total / 1e9, 1) - return round(total / 1e9, 1) - - -# ------------------------------------------------------------------------------------------------ HTTP -_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) # localhost: never through a proxy - - -def http_json(url: str, method="GET", body=None, api_key=None, timeout=3.0): - """(status, JSON or None); status 0 when nothing answers.""" - data = json.dumps(body).encode() if body is not None else (b"" if method == "POST" else None) - req = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"}) - if api_key: - req.add_header("Authorization", f"Bearer {api_key}") - try: - with _OPENER.open(req, timeout=timeout) as r: - raw = r.read() - status = r.status - except urllib.error.HTTPError as e: - raw, status = e.read(), e.code - except (OSError, ValueError): - return 0, None - try: - return status, json.loads(raw or b"null") - except ValueError: - return status, None - - -def port_free(port: int, host="127.0.0.1") -> bool: - import socket - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - s.bind((host, port)) - return True - except OSError: - return False - finally: - s.close() - - -# ------------------------------------------------------------------------------------------------ validation -class ToolError(Exception): - """A clear message for the AI (and its user): the tool result is an error, the server goes on.""" - - -def check_schema(schema: dict, args) -> dict: - """The tools' JSON schemas, enforced: object, known properties only, types, enums, ranges, patterns.""" - if args is None: - args = {} - if not isinstance(args, dict): - raise ToolError("arguments must be a JSON object") - props = schema.get("properties", {}) - for k in args: - if k not in props: - raise ToolError(f"unknown argument {k!r}; this tool takes: {', '.join(props) or 'no arguments'}") - for k in schema.get("required", []): - if k not in args: - raise ToolError(f"missing argument {k!r}") - for k, v in args.items(): - p = props[k] - t = p.get("type") - if t == "integer" and (isinstance(v, bool) or not isinstance(v, int)): - if isinstance(v, float) and v.is_integer(): - v = args[k] = int(v) - elif isinstance(v, str) and re.fullmatch(r"\d{1,7}", v.strip()): - v = args[k] = int(v.strip()) # some clients send numbers as strings - else: - raise ToolError(f"{k} must be a whole number") - if t == "boolean" and not isinstance(v, bool): - if v in ("true", "false"): - v = args[k] = v == "true" - else: - raise ToolError(f"{k} must be true or false") - if t == "string": - if not isinstance(v, str): - raise ToolError(f"{k} must be a string") - if len(v) > p.get("maxLength", 300) or "\x00" in v or "\n" in v or "\r" in v: - raise ToolError(f"{k} is too long or contains control characters") - if "pattern" in p and not re.fullmatch(p["pattern"], v): - raise ToolError(f"{k}={v!r} is not valid ({p.get('description', p['pattern'])})") - if "enum" in p and v not in p["enum"]: - raise ToolError(f"{k} must be one of: {', '.join(map(str, p['enum']))} (got {v!r})") - if t == "integer": - if "minimum" in p and v < p["minimum"] or "maximum" in p and v > p["maximum"]: - raise ToolError(f"{k} must be between {p.get('minimum')} and {p.get('maximum')} (got {v})") - return args - - -def is_inside(path: Path, root: Path) -> bool: - try: - path.relative_to(root) - return True - except ValueError: - return False - - -def norm(p) -> Path: - """A path to compare: absolute, links and Windows' short names (AI-SER~1) resolved, case folded on Windows.""" - return Path(os.path.normcase(os.path.realpath(os.path.abspath(str(p))))) - - -def system_folders() -> list[Path]: - if WIN: - env = [os.environ.get(k) for k in ("SystemRoot", "windir", "ProgramFiles", "ProgramFiles(x86)", "ProgramData", - "ProgramW6432")] - return [norm(p) for p in env if p] - return [norm(p) for p in ("/bin", "/boot", "/dev", "/etc", "/lib", "/lib32", "/lib64", "/proc", "/run", "/sbin", - "/sys", "/usr", "/var", "/snap")] - - -# ------------------------------------------------------------------------------------------------ PolyStrata -class Strata: - """One PolyStrata folder: what is installed there, the PC, and the processes this server started.""" - - def __init__(self, root: Path | str = DEFAULT_ROOT): - self.root = Path(root).resolve() - self.state_dir = self.root / STATE_DIR - self.lock = threading.Lock() # install / start / stop one at a time - self.children: list[subprocess.Popen] = [] # reaped now and then (no zombies on POSIX) - self._setup = None - self._setup_tried = False - self._hw_cache = None - self.python_override: str | None = None # tests: the interpreter that runs setup / the server - self.health_timeout = 2.0 - - # ---- setup.py's own tables and logic - def setup_module(self): - """setup.py imported as a module (its tables and its pure checks), or None. Its command runner is replaced - by one without console windows; nothing of its install path runs.""" - if not self._setup_tried: - self._setup_tried = True - try: - spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.root / "setup.py") - mod = importlib.util.module_from_spec(spec) - real = sys.stdout - sys.stdout = sys.stderr # nothing it prints may reach the protocol stream - try: - spec.loader.exec_module(mod) - finally: - sys.stdout = real - if all(hasattr(mod, a) for a in ("MODELS", "FAMILIES", "CONTEXTS")): - mod.out = lambda cmd: run_quiet(cmd, 60) - self._setup = mod - except (Exception, SystemExit) as e: # noqa: BLE001 - any failure: the built-in tables - log(f"setup.py could not be imported ({e}); using the built-in model table") - return self._setup - - def tables(self): - s = self.setup_module() - if s is not None: - return s.MODELS, s.FAMILIES, list(s.CONTEXTS), "setup.py" - return FALLBACK_MODELS, FALLBACK_FAMILIES, FALLBACK_CONTEXTS, "built-in table (setup.py not importable)" - - @staticmethod - def sizes_of(models, family) -> list: - """The family's sizes as setup lists them: an experimental one last (never the default).""" - return sorted((m for m in models if family in models[m].get("families", ("qwen", "swift"))), - key=lambda m: bool(models[m].get("experimental"))) - - def sizes(self, family) -> dict: - """A family's sizes, each with what the tables say of it: its own ("models"), else the ones that name it.""" - models, families, _ctx, _src = self.tables() - own = families[family].get("models") - return own if own is not None else {m: models[m] for m in self.sizes_of(models, family)} - - # ---- paths - def settings_path(self) -> Path: - if WIN: - return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "PolyStrata" / "settings.json" - return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "polystrata" / "settings.json" - - def data_dir(self) -> Path: - try: - s = json.loads(self.settings_path().read_text(encoding="utf-8")) - except (OSError, ValueError): - s = {} - d = s.get("data_dir") if isinstance(s, dict) else None - return Path(d) if d else self.root.parent / "PolyStrata-data" - - def allowed_roots(self) -> list[Path]: - return [norm(self.root), norm(self.data_dir())] - - def allowed(self, p) -> bool: - p = norm(p) - return any(is_inside(p, r) for r in self.allowed_roots()) - - def venv_python(self) -> Path: - return self.root / ".venv" / ("Scripts/python.exe" if WIN else "bin/python") - - def run_python(self) -> str: - return self.python_override or str(self.venv_python()) - - def state(self, name: str) -> dict: - try: - d = json.loads((self.state_dir / f"{name}.json").read_text(encoding="utf-8")) - return d if isinstance(d, dict) else {} - except (OSError, ValueError): - return {} - - def save_state(self, name: str, d: dict | None) -> None: - self.state_dir.mkdir(parents=True, exist_ok=True) - f = self.state_dir / f"{name}.json" - if d is None: - f.unlink(missing_ok=True) - else: - tmp = f.with_suffix(".tmp") - tmp.write_text(json.dumps(d, indent=1), encoding="utf-8") - os.replace(tmp, f) - - def reap(self): - self.children = [p for p in self.children if p.poll() is None] - - # ---- what is installed - def configs(self) -> list[Path]: - return sorted((p for p in self.root.glob("strata-*.json") if not p.name.endswith(".shared-settings.json")), - key=lambda p: p.stat().st_mtime, reverse=True) # #346: the Chat settings file is no config - - @staticmethod - def read_config(path: Path) -> dict: - try: - cfg = json.loads(path.read_text(encoding="utf-8-sig")) - return cfg if isinstance(cfg, dict) else {} - except (OSError, ValueError): - return {} - - def describe_config(self, path: Path) -> dict: - cfg = self.read_config(path) - a = cfg.get("args") if isinstance(cfg.get("args"), list) else [] - - def val(k): - return a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None - tag = path.stem[len("strata-"):] - missing = [p for p in [cfg.get("exe"), *[x for x in a if isinstance(x, str) and x.endswith(".gguf")]] - if not p or not Path(p).exists()] - script = self.root / f"run-{tag}.{'bat' if WIN else 'sh'}" - vis = cfg.get("vision") - return {"model": tag, "config": path.name, "model_name": cfg.get("model_name"), - "context": int(val("--max-context")) if str(val("--max-context") or "").isdigit() else None, - "kv": val("--kv"), "images": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "off", - "port": cfg.get("port", DEFAULT_PORT), "host": cfg.get("host", "127.0.0.1"), - "gpu": cfg.get("gpu"), "api_key_set": bool(cfg.get("api_key")), - "low_ram": "--resident-experts" in a or "--mmap-experts" in a, - "start_script": script.name if script.exists() else None, - "ready": not missing and bool(cfg), "missing_files": missing[:3], - "last_used": time.strftime("%Y-%m-%d %H:%M", time.localtime(path.stat().st_mtime))} - - def find_config(self, model: str | None) -> Path: - have = self.configs() - if not have: - raise ToolError("no model is installed in " + str(self.root) + " yet: install one first (strata_install)") - if not model: - return have[0] # the most recently used, as setup starts it - m = model.strip().lower() - exact = [c for c in have if c.stem[len("strata-"):] == m] - if exact: - return exact[0] - by_name = [c for c in have if str(self.read_config(c).get("model_name", "")).lower() == m] - if by_name: - return by_name[0] - ends = [c for c in have if c.stem.endswith("-" + m)] - if len(ends) == 1: - return ends[0] - raise ToolError(f"no installed model {model!r}; installed: " + - ", ".join(c.stem[len("strata-"):] for c in have)) - - def engine_info(self) -> dict: - for d in ("engine",): - try: - meta = json.loads((self.root / d / "BUILD.json").read_text()) - return {"folder": d, "version": meta.get("version"), "source": meta.get("source"), - "backend": meta.get("backend")} - except (OSError, ValueError): - continue - return {"folder": None, "version": None} - - def installed(self) -> dict: - data = self.data_dir() - items = {} - for sub in ("models", "packs"): - for base in dict.fromkeys([data, self.root]): - d = base / sub - if d.is_dir(): - for c in sorted(d.iterdir()): - if c.is_dir(): - ggufs = list(c.glob("*.gguf")) - entry = {"folder": str(c), "size_gb": dir_size_gb(c)} - if sub == "models": - entry["complete"] = bool(ggufs) and all( - g.with_name(g.name + ".done").exists() for g in ggufs) - entry["downloading"] = bool(list(c.glob("*.part"))) - items.setdefault(sub, []).append(entry) - mtp = data / "mtp" / "rt" / "experts.bin" - return {"strata_folder": str(self.root), "data_folder": str(data), "data_folder_exists": data.is_dir(), - "python_env": self.venv_python().exists(), "engine": self.engine_info(), - "models": [self.describe_config(c) for c in self.configs()], - "downloads": items.get("models", []), "prepared": items.get("packs", []), - "draft_layer": mtp.exists()} - - # ---- the PC - def hardware(self, fresh=False) -> dict: - if self._hw_cache and not fresh and time.time() - self._hw_cache[0] < 600: - hw = dict(self._hw_cache[1]) - else: - hw = self._hardware() - self._hw_cache = (time.time(), hw) - hw = dict(hw) - hw["disk_free_gb"] = self.disk_free(self.data_dir()) - return hw - - @staticmethod - def disk_free(p: Path) -> float | None: - p = Path(p) - while not p.exists() and p.parent != p: - p = p.parent - try: - return round(shutil.disk_usage(p).free / 1e9, 1) - except OSError: - return None - - def _hardware(self) -> dict: - S = self.setup_module() - hw = {"os": f"{platform.system()} {platform.release()}", "os_version": platform.version(), - "machine": platform.machine(), "python": platform.python_version()} - if not WIN and Path("/proc/version").exists(): - try: - hw["wsl"] = "microsoft" in Path("/proc/version").read_text().lower() - except OSError: - pass - try: - hw["ram_gb"] = round(S.ram_gb(), 1) if S else round(own_ram_gb(), 1) - except Exception: # noqa: BLE001 - hw["ram_gb"] = round(own_ram_gb(), 1) - if S and WIN: - try: - hw["page_file_gb"] = round(S.page_file_gb(), 1) - except Exception: # noqa: BLE001 - pass - try: - if S: - name, avx2, avx512 = S.cpu_info() - else: - name, avx2, avx512 = platform.processor() or "unknown CPU", None, None - hw["cpu"] = {"name": name, "cores": os.cpu_count(), "avx2": avx2, "avx512": avx512} - except Exception: # noqa: BLE001 - hw["cpu"] = {"name": platform.processor(), "cores": os.cpu_count()} - nv = [] - try: - nv = S.gpus() if S else own_nvidia_gpus() - except Exception: # noqa: BLE001 - nv = own_nvidia_gpus() - for g in nv: - g["vendor"] = "nvidia" - g["vram_gb"] = round(g["vram_gb"], 1) - try: - g["problem"] = S.gpu_problem(g) if S else (None if int(g["arch"]) >= 75 else "older than RTX 20") - except Exception: # noqa: BLE001 - g["problem"] = None - g["usable"] = g["problem"] is None - amd = [] - if not WIN: - try: - amd = S.amd_gpus() if S else [] - for g in amd: - g["vendor"] = "amd" - g["vram_gb"] = round(g["vram_gb"], 1) - g["problem"] = S.amd_problem(g) - g["usable"] = g["problem"] is None - except Exception: # noqa: BLE001 - amd = [] - if not amd and shutil.which("rocm-smi"): - amd = rocm_smi_gpus() - hw["gpus"] = nv + amd - if WIN: - hw["display_adapters"] = windows_video_controllers() - hw["nvidia_smi"] = bool(shutil.which("nvidia-smi")) - return hw - - def recommend(self, hw: dict) -> dict: - """setup.py's own rules: the size it preselects (IQ3_XXS from 60 GB of RAM, else the first, Q2_0), the - Coder below the full model's RAM (setup's RAM table), the low-RAM mode when the GPU makes up for the RAM, and - the context it preselects for the card's VRAM (32K under 14 GB, 64K under 20 GB, else 128K).""" - models, families, _ctx, _src = self.tables() - S = self.setup_module() - usable = [g for g in hw.get("gpus", []) if g.get("usable")] - ram = hw.get("ram_gb") or 0 - if not usable: - why = ("no NVIDIA RTX 20-series-or-newer GPU found (nvidia-smi did not list one)" - + ("; AMD cards run on Linux only" if WIN and any( - "amd" in str(a.get("name", "")).lower() or "radeon" in str(a.get("name", "")).lower() - for a in hw.get("display_adapters", [])) else "")) - return {"family": None, "model": None, "why": why} - best = max(usable, key=lambda g: (round(g["vram_gb"]), -g.get("index", 0))) - vram = best["vram_gb"] - backend = "hip" if best.get("vendor") == "amd" else "cuda" - - def low_fits(m): - try: - return S.low_ram_fits(m, ram, vram) if S else ram - 6 + max(0.0, vram - 5) >= models[m]["arena_gb"] - except Exception: # noqa: BLE001 - return False - notes = [] - if ram >= 60: - fam, model, why = "qwen", "IQ3_XXS", f"{ram:.0f} GB of RAM: setup's own pick from 60 GB (better quality)" - elif ram >= models["Q2_0"]["ram_gb"] - 4: - fam, model, why = "qwen", "Q2_0", f"{ram:.0f} GB of RAM: the full model's fastest size fits" - elif ram >= models["IQ1_M"]["ram_gb"] - 4: - fam, model, why = "coder", "IQ1_M", (f"{ram:.0f} GB of RAM: the full model needs ~48 GB; the Coder " - "(half the experts, best for code) needs ~32 GB") - elif low_fits("IQ1_M"): - fam, model, why = "coder", "IQ1_M", (f"{ram:.0f} GB of RAM is below the Coder's 32 GB, but the GPU's " - f"{vram:.0f} GB make up for it (setup's low-RAM mode: slower)") - else: - return {"family": None, "model": None, "why": f"{ram:.0f} GB of RAM: Qwen3.8-Flash-Next needs 32 GB or " - "more (its smallest, the Coder, keeps ~23 GB of experts in " - "RAM); the 11-24 GB models (family qwen36, ornith, " - "gemma4 or tiel: experimental) want 15-28 GB"} - ctx = 32768 if vram < 14 else 65536 if vram < 20 else 131072 - if vram < 11: - notes.append("less than 12 GB of VRAM: it runs, but slowly (most experts stay on the CPU)") - if hw.get("cpu", {}).get("avx2") is False: # #623: a warning, not a stop (setup compiles for it) - notes.append("this CPU has no AVX2: EXPERIMENTAL and slow - setup compiles the engine on this PC for the " - "older CPU (10-20 minutes), and the CPU's share of the experts runs a few times slower") - if backend == "hip": - notes.append("AMD (experimental, Linux): the engine is compiled during setup; no images") - cmd = (("START-HERE.bat --setup" if WIN else "./setup.sh --setup") + - f" --yes --family {fam} --model {model} --context {ctx}" + (" --backend hip" if backend == "hip" else "")) - return {"family": fam, "model": model, "title": families[fam]["title"] + " " + model, "context": ctx, - "backend": backend, "gpu": {k: best.get(k) for k in ("index", "name", "vram_gb")}, - "download_gb": models[model]["download_gb"], "why": why, "notes": notes, "setup_command": cmd} - - def model_table(self, hw: dict | None) -> list: - models, families, _ctx, _src = self.tables() - S = self.setup_module() - ram = (hw or {}).get("ram_gb") - usable = [g for g in (hw or {}).get("gpus", []) if g.get("usable")] - vram = max((g["vram_gb"] for g in usable), default=0.0) - have = {c.stem[len("strata-"):] for c in self.configs()} - out = [] - for f, fd in families.items(): - sizes = [] - for m, d in self.sizes(f).items(): - tag = (fd.get("tag", "") + m).lower() - verdict = None - if ram is not None: - verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit" - try: - if d.get("budget") and S and hasattr(S, "unsloth_budget") and not S.unsloth_budget(m, ram): - verdict = ("experimental: " if d.get("experimental") else "") + "fits (all of its experts in RAM)" - elif d.get("budget"): - verdict = (("experimental: " if d.get("experimental") else "") - + "part of its experts in RAM, the rest read from the SSD" - if ram >= d["ram_gb"] else - "slow here: part of its experts in RAM, the rest read from the SSD (setup " - "asks first)" if ram >= 48 else "does not fit") - elif S and m in models and S.low_ram_needed(m, ram) and S.low_ram_fits(m, ram, vram): - verdict = "fits in the low-RAM mode (slower: the GPU holds part of the experts)" - except Exception: # noqa: BLE001 - pass - sizes.append({"model": m, "about": d["about"], "download_gb": d["download_gb"], - "experimental": bool(d.get("experimental")), - "images": d.get("vision", fd.get("vision", True)) is not False, - "ram_needed_gb": d["ram_gb"], "experts_gb": d.get("arena_gb"), - "on_this_pc": verdict, "installed": tag in have, "id": tag}) - out.append({"family": f, "title": fd["title"], "about": fd.get("about"), - "experimental": bool(fd.get("experimental")), - "images": any(x["images"] for x in sizes) if sizes else fd.get("vision", True) is not False, - "sizes": sizes}) - return out - - # ---- the running server - def ports(self, port: int | None) -> list[int]: - if port: - return [port] - ps = [self.state("server").get("port")] + [self.describe_config(c)["port"] for c in self.configs()] - return list(dict.fromkeys(int(p) for p in [*ps, DEFAULT_PORT] if isinstance(p, int))) - - def api_key_for(self, port: int) -> str | None: - """The key a config of this folder set for that port (used for our own requests; never shown).""" - for c in self.configs(): - cfg = self.read_config(c) - if cfg.get("api_key") and int(cfg.get("port", DEFAULT_PORT)) == port: - return cfg["api_key"] - for c in self.configs(): - if self.read_config(c).get("api_key"): - return self.read_config(c)["api_key"] - return None - - def probe(self, port: int, deep=True) -> dict | None: - """What answers on 127.0.0.1:port: a PolyStrata server's facts, {"other": True} for something else, None for - nothing.""" - base = f"http://127.0.0.1:{port}" - st, health = http_json(base + "/health", timeout=self.health_timeout) - if st == 0: - return None - if st != 200 or not isinstance(health, dict) or health.get("service") != "strata": - return {"port": port, "other": True, "note": "something else answers on this port (not a PolyStrata server)"} - info = {"port": port, "url": base, "model": health.get("model"), "context": health.get("max_context"), - "images": health.get("images"), "loaded": health.get("loaded"), - "api_key_required": bool(health.get("api_key"))} - if not deep: - return info - key = self.api_key_for(port) - st, v1 = http_json(base + "/v1/status", api_key=key, timeout=self.health_timeout) - if st == 200 and isinstance(v1, dict): - info["engine_version"] = v1.get("engine") - info["uptime_s"] = v1.get("uptime_s") - info["requests_served"] = (v1.get("activity") or {}).get("requests") - m = v1.get("machine") or {} - if m.get("gpu"): - info["gpu"] = m["gpu"] - if m.get("ram"): - info["ram"] = m["ram"] - if v1.get("last_timings"): - lt = v1["last_timings"] - info["last_request"] = {k: lt.get(k) for k in ("prompt_n", "prompt_per_second", "predicted_n", - "predicted_per_second") if k in lt} - elif st == 401: - info["note"] = "the server wants an API key this folder's configs do not have" - st, s = http_json(base + "/status", api_key=key, timeout=self.health_timeout) - if st == 200 and isinstance(s, dict): - info["busy"] = bool(s.get("busy")) - info["activity"] = {k: s.get(k) for k in ("phase", "generated", "tokens_per_s", "queued", "elapsed_s") - if s.get(k) is not None} - if "gpu" not in info: # older servers: the Monitor's numbers - st, met = http_json(base + "/metrics", api_key=key, timeout=self.health_timeout) - if st == 200 and isinstance(met, dict): - hwn = met.get("hardware") or {} - if hwn.get("gpu_mem_total"): - info["gpu"] = {"used_mib": round(hwn.get("gpu_mem_used", 0) / 2**20), - "total_mib": round(hwn["gpu_mem_total"] / 2**20)} - if hwn.get("ram_total"): - info["ram"] = {"used_gib": round(hwn.get("ram_used", 0) / 2**30, 1), - "total_gib": round(hwn["ram_total"] / 2**30, 1)} - info["engine_version"] = (met.get("engine") or {}).get("version") - return info - - def tracked_server(self) -> dict | None: - """The server this MCP server started, while it still runs (else its record is cleared).""" - s = self.state("server") - if not s: - return None - if proc_alive(s.get("pid"), s.get("ident")): - return s - return {**s, "ended": True} - - # ---- install job - def install_job(self) -> dict | None: - j = self.state("install") - if not j: - return None - res = self.state("install-result") - running = proc_alive(j.get("pid"), j.get("ident")) - log_path = Path(j.get("log", "")) - tail = read_tail(log_path, 400) if log_path.name else [] - prog = install_progress(tail) - out = {"running": running, "started": j.get("started"), "model": j.get("model"), "family": j.get("family"), - "log": str(log_path), **prog} - if not running: - if res.get("job") == j.get("job") and "exit_code" in res: - out["exit_code"] = res["exit_code"] - out["finished"] = res.get("ended") - out["result"] = "installed" if res["exit_code"] == 0 else "failed" - else: - out["result"] = "ended unexpectedly (no exit code recorded)" - else: - out["result"] = "running" - out["last_lines"] = tail[-12:] - return out - - -def install_progress(lines: list[str]) -> dict: - """setup's progress from its output: the step, a download's percentage, a failure.""" - step, title, dl, err = None, None, None, None - for i, line in enumerate(lines): - m = re.search(r"=== Step (\d+): (.+?) ===", line) - if m: - step, title, err = int(m.group(1)), m.group(2), None - m = re.match(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)", line) - if m: - dl = {"file": m.group(1), "done_gb": float(m.group(2)), "total_gb": float(m.group(3)), - "percent": int(m.group(4))} - if line.strip().startswith("[X]"): - err = line.strip()[3:].strip() - if i + 1 < len(lines) and lines[i + 1].startswith(" "): - err += " - " + lines[i + 1].strip() - out = {"step": f"{step}/7: {title}" if step else None} - if dl: - out["download"] = dl - if err: - out["error"] = err - return out - - -def own_ram_gb() -> float: - if WIN: - class MS(ctypes.Structure): - _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), - *((n, ctypes.c_ulonglong) for n in ("tp", "ap", "tpf", "apf", "tv", "av", "aev"))] - m = MS() - m.dwLength = ctypes.sizeof(MS) - ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)) - return m.tp / 2**30 - try: - for line in open("/proc/meminfo"): - if line.startswith("MemTotal"): - total = int(line.split()[1]) * 1024 / 2**30 - try: # a container's limit (cgroup v2), as setup's ram_gb() - limit = open("/sys/fs/cgroup/memory.max").read().strip() - except OSError: - limit = "" - return min(total, int(limit) / 2**30) if limit.isdigit() else total - except OSError: - pass - return 0.0 - - -def own_nvidia_gpus() -> list: - s = run_quiet(["nvidia-smi", "--query-gpu=index,name,memory.total,compute_cap,driver_version", - "--format=csv,noheader,nounits"]) - found = [] - for line in s.strip().splitlines(): - try: - idx, name, mem, cc, drv = [x.strip() for x in line.split(",")] - found.append({"index": int(idx), "name": name, "vram_gb": float(mem) / 1024.0, - "arch": cc.replace(".", ""), "driver": drv}) - except ValueError: - continue - return found - - -def windows_video_controllers() -> list: - s = run_quiet(["powershell", "-NoProfile", "-NonInteractive", "-Command", - "Get-CimInstance Win32_VideoController | Select-Object Name,DriverVersion | ConvertTo-Json -Compress"]) - try: - d = json.loads(s) if s.strip() else [] - except ValueError: - return [] - d = [d] if isinstance(d, dict) else d - return [{"name": x.get("Name"), "driver": x.get("DriverVersion")} for x in d if isinstance(x, dict)] - - -def rocm_smi_gpus() -> list: - s = run_quiet(["rocm-smi", "--showproductname", "--showmeminfo", "vram", "--json"]) - try: - d = json.loads(s) - except ValueError: - return [] - out = [] - for i, (card, v) in enumerate(sorted(d.items())): - if not isinstance(v, dict) or not card.lower().startswith("card"): - continue - total = next((v[k] for k in v if "total" in k.lower() and "vram" in k.lower()), 0) - try: - vram = int(total) / 2**30 - except (TypeError, ValueError): - vram = 0.0 - out.append({"index": i, "name": v.get("Card Series") or v.get("Card SKU") or card, "vram_gb": round(vram, 1), - "vendor": "amd", "usable": None, "problem": "listed by rocm-smi (setup checks the card itself)"}) - return out - - -# ------------------------------------------------------------------------------------------------ the tools -GPUS_PATTERN = r"all|\d{1,2}(,\d{1,2}){1,7}" -MODEL_ID_PATTERN = r"[A-Za-z0-9][A-Za-z0-9_.-]{0,48}" - - -def tool_defs(models: dict, families: dict, contexts: list) -> list: - port = {"type": "integer", "minimum": 1024, "maximum": 65535, - "description": "the server's port (default: the installed model's port, usually 8080)"} - installed_model = {"type": "string", "pattern": MODEL_ID_PATTERN, "maxLength": 49, - "description": "an installed model's id as strata_status lists it (e.g. 'q2_0', " - "'coder-iq1_m', 'swift-iq3_xxs'); default: the most recently used one"} - ro = {"readOnlyHint": True, "destructiveHint": False, "openWorldHint": False} - return [ - {"name": "strata_status", "title": "PolyStrata status", - "description": "Is PolyStrata (the local AI model server) running, and what is installed? Reports the running " - "server (model, engine version, context, busy or idle, VRAM/RAM in use), the installed models " - "and data folder, an install in progress, this PC's hardware (OS, CPU, RAM, GPUs, free disk) " - "and the model size setup recommends for this PC. Read-only; call it first.", - "inputSchema": {"type": "object", "additionalProperties": False, "properties": { - "port": port, - "hardware": {"type": "boolean", "description": "include the hardware check and the recommendation " - "(default true; takes a second or two)"}}}, - "annotations": ro}, - {"name": "strata_models", "title": "PolyStrata models", - "description": "The models and sizes PolyStrata's setup offers (families: qwen = Qwen3.8-Flash-Next, swift = " - "Swift 1.5, coder = the Coder, unsloth = Unsloth's ~4-bit, glm = GLM 5.3 Flash, another " - "model with its own engine, deepseek = DeepSeek V4 Flash on that engine, lfm25 = LFM2.5-24B-A2B, " - "qwen36 = Qwen3.6-35B-A3B, ornith = Ornith 1.5, gemma4 = Gemma 4 26B-A4B and tiel = Tiel " - "Coder 35B-A3B, 11-25 GB models on that engine), with " - "download size, RAM needed, " - "whether each fits this PC, which are installed, the context lengths, and the recommendation. " - "Read-only.", - "inputSchema": {"type": "object", "additionalProperties": False, "properties": {}}, - "annotations": ro}, - {"name": "strata_install", "title": "Install PolyStrata", - "description": "Install a PolyStrata model on this PC by running PolyStrata's setup non-interactively in the " - "background (Python packages, the engine, a 13-114 GB model download, preparation, start " - "script). Without confirm=true it only returns the plan (what would be downloaded, disk " - "space): show it to the user and call again with confirm=true once they agree. Returns at " - "once; call it again (no arguments needed) to see the progress, or with cancel=true to stop " - "it (it resumes later). Defaults: the recommended model and context for this PC, images off. " - "After it finishes, start the model with strata_start.", - "inputSchema": {"type": "object", "additionalProperties": False, "properties": { - "family": {"type": "string", "enum": list(families), - "description": "qwen = Qwen3.8-Flash-Next (the original), swift = Swift 1.5 (thinks " - "shorter), coder = the Coder (half the experts, ~32 GB RAM, for code), " - "unsloth = Unsloth's 4- to 8-bit files (UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, " - "UD-Q6_K_XL, Q8_0): every expert in RAM where they fit, else part of them read " - "from the SSD, glm = GLM 5.3 " - "Flash (another model: Linux, one NVIDIA card, 64-128 GB of RAM, a 79 or " - "114 GB download, no images), deepseek = DeepSeek V4 Flash (GLM's " - "engine: Linux, one NVIDIA card, ~72 GB of RAM beside a 32 GB card, a 91 " - "GB download, no images), lfm25 = LFM2.5-24B-A2B, qwen36 = " - "Qwen3.6-35B-A3B, ornith = Ornith 1.5, gemma4 = Gemma 4 26B-A4B, tiel = " - "Tiel Coder 35B-A3B (GLM's engine: one NVIDIA card, an 11-25 GB download, " - "15-31 GB of RAM beside an 8 GB card by setup's estimate; images with " - "vision except LFM2.5)"}, - "model": {"type": "string", "enum": list(dict.fromkeys( - [*models, *(m for f in families.values() for m in f.get("models", ()))])), - "description": "the size (quantization): see strata_models"}, - "context": {"type": "integer", "enum": contexts, - "description": "context length in tokens (more needs more VRAM)"}, - "vision": {"type": "string", "enum": ["no", "yes", "gpu", "cpu"], - "description": "let the model read images (yes = the encoder on the GPU; ~0.9 GB more " - "download); default no"}, - "kv": {"type": "string", "enum": ["int8", "q4_0", "k8v4"], - "description": "KV cache precision above 8K context (default int8)"}, - "gpu": {"type": "integer", "minimum": 0, "maximum": 63, - "description": "one GPU, as nvidia-smi numbers them (default: the one with the most VRAM)"}, - "gpus": {"type": "string", "pattern": GPUS_PATTERN, "maxLength": 40, - "description": "several GPUs sharing the model: '0,2' or 'all' (experimental)"}, - "backend": {"type": "string", "enum": ["auto", "cuda", "hip"], - "description": "auto (default), cuda = NVIDIA, hip = AMD on Linux (experimental)"}, - "low_ram": {"type": "string", "enum": ["auto", "on", "off", "resident", "mmap"], - "description": "setup's low-RAM mode (default auto)"}, - "port": {**port, "description": "the port the model will listen on (default 8080)"}, - "data_dir": {"type": "string", "maxLength": 260, - "description": "where the model files go (default: the PolyStrata-data folder next to the " - "PolyStrata folder). Only the current data folder, a folder inside the PolyStrata " - "folder, or a new absolute path whose last folder is named PolyStrata... " - "(e.g. D:\\PolyStrata-data) outside system folders"}, - "confirm": {"type": "boolean", "description": "true = really start the install (after the user agreed " - "to the plan and the download size)"}, - "cancel": {"type": "boolean", "description": "true = stop the install in progress"}}}, - "annotations": {"readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, - "openWorldHint": True}}, - {"name": "strata_start", "title": "Start PolyStrata", - "description": "Start an installed PolyStrata model in the background (as its start script does, without " - "opening a browser) and wait until it answers. Loading takes 1-3 minutes and the PC can be " - "slow meanwhile; if it is not ready within wait_seconds this returns 'loading' - check again " - "with strata_status. The model keeps running until strata_stop.", - "inputSchema": {"type": "object", "additionalProperties": False, "properties": { - "model": installed_model, "port": port, - "gpu": {"type": "integer", "minimum": 0, "maximum": 63, - "description": "run on this GPU for this start (as nvidia-smi numbers them)"}, - "wait_seconds": {"type": "integer", "minimum": 0, "maximum": 600, - "description": "how long to wait for it to be ready (default 50: some AI apps end " - "a tool call after 60 s)"}}}, - "annotations": {"readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, - "openWorldHint": False}}, - {"name": "strata_stop", "title": "Stop PolyStrata", - "description": "Stop the PolyStrata model: the engine is unloaded through the server's own API (it frees its " - "VRAM and RAM itself), then the server this tool started is ended. A PolyStrata started " - "elsewhere (e.g. its own window) is only unloaded - close its window to end it. Refuses while " - "a request is running unless force=true.", - "inputSchema": {"type": "object", "additionalProperties": False, "properties": { - "port": port, - "force": {"type": "boolean", "description": "stop even while a request is running"}}}, - "annotations": {"readOnlyHint": False, "destructiveHint": True, "idempotentHint": True, - "openWorldHint": False}}, - {"name": "strata_logs", "title": "PolyStrata logs", - "description": "The last lines of a PolyStrata log: 'server' (the model server this tool started: loading, " - "requests, errors), 'engine' (the engine's own log for a model), 'setup' (the install). " - "Default: the setup log while an install runs, else the server log. Read-only.", - "inputSchema": {"type": "object", "additionalProperties": False, "properties": { - "source": {"type": "string", "enum": ["server", "engine", "setup"]}, - "model": installed_model, - "lines": {"type": "integer", "minimum": 1, "maximum": 500, "description": "default 80"}}}, - "annotations": ro}, - {"name": "strata_benchmark", "title": "PolyStrata speed test", - "description": "A short fixed request (greedy, thinking off) through the running PolyStrata server; reports " - "the output speed (tokens/s) and prompt speed. Takes 10-60 s. Refuses while the model is " - "busy.", - "inputSchema": {"type": "object", "additionalProperties": False, "properties": { - "port": port, - "max_tokens": {"type": "integer", "minimum": 16, "maximum": 512, "description": "default 200"}}}, - "annotations": {"readOnlyHint": True, "destructiveHint": False, "openWorldHint": False}}, - {"name": "strata_connect_info", "title": "Connect to PolyStrata", - "description": "How to point other apps at the local PolyStrata server: the OpenAI and Anthropic base URLs, " - "the model id, whether an API key is needed, and ready-to-paste settings for Claude Code, " - "Codex CLI, the OpenAI SDK, curl, Cursor/Continue/Open WebUI. Read-only.", - "inputSchema": {"type": "object", "additionalProperties": False, "properties": {"port": port}}, - "annotations": ro}, - ] - - -class Tools: - def __init__(self, strata: Strata): - self.s = strata - - def defs(self) -> list: - return tool_defs(*self.s.tables()[:3]) - - def call(self, name: str, args) -> dict: - defs = {d["name"]: d for d in self.defs()} - if name not in defs: - raise KeyError(name) - args = check_schema(defs[name]["inputSchema"], args) - return getattr(self, name)(**args) - - # ---- strata_status - def strata_status(self, port=None, hardware=True) -> dict: - s = self.s - s.reap() - servers = [] - for p in s.ports(port): - info = s.probe(p) - if info is not None: - servers.append(info) - tracked = s.tracked_server() - out = {} - running = [x for x in servers if not x.get("other")] - if tracked and not tracked.get("ended"): - mine = next((x for x in running if x["port"] == tracked["port"]), None) - if mine: - mine["started_by"] = f"this MCP server (pid {tracked['pid']})" - else: - out["loading"] = {"model": tracked.get("model"), "port": tracked["port"], "pid": tracked["pid"], - "since": tracked.get("started"), - "last_log_line": (read_tail(Path(tracked.get("log", "")), 1) or [None])[-1]} - elif tracked and tracked.get("ended"): - out["last_start"] = {"model": tracked.get("model"), "ended": True, - "last_log_lines": read_tail(Path(tracked.get("log", "")), 6)} - for x in running: - x.setdefault("started_by", "outside this MCP server (its own window, a start script or a service)") - out["running"] = running - others = [x for x in servers if x.get("other")] - if others: - out["ports_used_by_other_programs"] = others - if running: - r = running[0] - summary = (f"PolyStrata is running on port {r['port']}: {r.get('model')}" - + (", busy" if r.get("busy") else ", idle") - + ("" if r.get("loaded", True) else " (model unloaded; the next request loads it)")) - elif "loading" in out: - summary = f"PolyStrata is loading {out['loading']['model']} (port {out['loading']['port']})" - else: - summary = "PolyStrata is not running" - inst = s.installed() - job = s.install_job() - if job: - out["install"] = job - if job["running"]: - summary += f"; an install is running ({job.get('step') or 'starting'})" - if not inst["models"]: - summary += "; no model is installed yet" - else: - summary += "; installed: " + ", ".join(m["model"] for m in inst["models"]) - out["installed"] = inst - if hardware: - hw = s.hardware() - out["hardware"] = hw - out["recommendation"] = s.recommend(hw) - return {"summary": summary, **out} - - # ---- strata_models - def strata_models(self) -> dict: - s = self.s - hw = s.hardware() - _m, _f, contexts, src = s.tables() - rec = s.recommend(hw) - return {"summary": "Model families and sizes setup offers" + ( - f"; recommended for this PC: {rec['title']}, {rec['context'] // 1024}K context" - if rec.get("model") else f"; no model fits this PC: {rec['why']}"), - "families": s.model_table(hw), "contexts": contexts, - "context_note": "longer contexts need more VRAM (fewer experts fit on the GPU); past 262144 setup adds " - "rope scaling (experimental)", - "recommendation": rec, "source": src, - "this_pc": {"ram_gb": hw.get("ram_gb"), - "gpus": [{k: g.get(k) for k in ("index", "name", "vram_gb", "usable")} - for g in hw.get("gpus", [])]}} - - # ---- strata_install - def check_data_dir(self, raw: str) -> Path: - s = self.s - if raw.startswith("\\\\") or raw.startswith("//"): - raise ToolError("data_dir: network (UNC) paths are not allowed; use a local drive") - p = Path(os.path.expandvars(raw)).expanduser() - if not p.is_absolute(): - raise ToolError("data_dir must be an absolute path (e.g. D:\\PolyStrata-data or /mnt/big/PolyStrata-data)") - if ".." in p.parts: - raise ToolError("data_dir must not contain '..'") - n = norm(p) - current = norm(s.data_dir()) - if n == current or is_inside(n, norm(s.root)) or n == norm(s.root.parent / "PolyStrata-data"): - pass - else: - if not p.name.lower().startswith("polystrata"): - raise ToolError(f"data_dir {raw!r}: a new data folder must be named PolyStrata... (e.g. " - f"{Path(p.anchor or '/') / 'PolyStrata-data'}), so that no other folder is filled with " - "model files") - if not p.parent.is_dir(): - raise ToolError(f"data_dir {raw!r}: its parent folder {p.parent} does not exist") - if any(n == f or is_inside(n, f) for f in system_folders()): - raise ToolError(f"data_dir {raw!r} is inside a system folder") - if p.exists() and not p.is_dir(): - raise ToolError(f"data_dir {raw!r} is a file") - return p - - def strata_install(self, family=None, model=None, context=None, vision=None, kv=None, gpu=None, gpus=None, - backend=None, low_ram=None, port=None, data_dir=None, confirm=False, cancel=False) -> dict: - s = self.s - with s.lock: - job = s.install_job() - if cancel: - if not job or not job["running"]: - return {"summary": "no install is running", "install": job} - j = s.state("install") - res = s.state("install-result") - child = res.get("child_pid") if res.get("job") == j.get("job") else None - if child: - proc_kill_tree(child, res.get("child_ident")) - proc_kill_tree(j["pid"], j["ident"]) - wait_gone(j["pid"], j["ident"], 15) - return {"summary": "the install was stopped; calling strata_install again resumes it (downloads " - "continue where they stopped)", "install": s.install_job()} - if job and job["running"]: - return {"summary": f"an install is running: {job.get('step') or 'starting'}" - + (f", downloading {job['download']['file']} {job['download']['percent']}%" - if job.get("download") else ""), - "install": job, "follow": "call strata_install again for progress, or strata_logs " - "source=setup for the full output"} - given = [x for x in (family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, data_dir) - if x is not None] - if job and not given and not confirm: - return {"summary": f"the last install {job['result']}" + (f": {job['error']}" if job.get("error") else ""), - "install": job, - "next": "strata_start" if job.get("exit_code") == 0 else - "fix the problem above and call strata_install again with confirm=true (finished " - "steps are skipped)"} - plan, args = self.install_plan(family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, - data_dir) - tracked = s.tracked_server() - if tracked and not tracked.get("ended"): - raise ToolError("PolyStrata is running (started by strata_start): stop it first with strata_stop - setup " - "may update the engine files it uses") - if not confirm: - return {"summary": f"Plan: install {plan['title']} ({plan['download_gb']:.0f} GB download" - f"{' at most; part of it is already here' if plan['partly_downloaded'] else ''}). " - "Nothing was done yet: ask the user, then call strata_install again with the " - "same arguments and confirm=true.", "plan": plan} - if plan["disk_short"]: - raise ToolError(plan["disk_short"]) - return self.launch_install(plan, args) - - def install_plan(self, family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, data_dir): - s = self.s - models, families, contexts, _src = s.tables() - if gpu is not None and gpus is not None: - raise ToolError("give gpu (one card) or gpus (several), not both") - if backend == "hip" and WIN: - raise ToolError("the AMD (hip) backend runs on Linux only; on Windows PolyStrata needs an NVIDIA RTX 20 " - "series or newer card") - if sys.version_info < (3, 10) or (WIN and sys.maxsize <= 2**32): - raise ToolError("this Python is too old or 32-bit: PolyStrata's setup needs 64-bit Python 3.10+; run " - + ("START-HERE.bat" if WIN else "./setup.sh") + " once instead (it installs Python)") - hw = s.hardware() - rec = s.recommend(hw) - if model is None and family is None: - if not rec.get("model"): - raise ToolError("no model was given and none fits this PC: " + rec["why"]) - family, model = rec["family"], rec["model"] - context = context or rec["context"] - elif model is None: - sizes = s.sizes(family) - model = rec["model"] if rec.get("family") == family else ("IQ3_XXS" if "IQ3_XXS" in sizes and - hw.get("ram_gb", 0) >= 60 else next(iter(sizes))) - S = s.setup_module() - if families[family].get("engine") == "poly" and S and hw.get("ram_gb"): # setup's own pick for this PC - cards = [g["vram_gb"] for g in hw.get("gpus", []) if g.get("usable")] - model = S.poly_default(sizes, hw["ram_gb"], max(cards, default=0.0)) - elif family is None: - fams = [f for f in families if model in s.sizes(f)] - if len(fams) > 1: # a family's own size yields to MODELS' (Tiel's UD-Q4_K_XL) - fams = [f for f in fams if "models" not in families[f]] or fams - if len(fams) > 1 and "qwen" not in fams: - raise ToolError(f"{model} is a size of " + " and of ".join(families[f]["title"] for f in fams) - + ": give family too (" + " or ".join(fams) + ")") - family = "qwen" if "qwen" in fams else fams[0] - sizes = s.sizes(family) - if model not in sizes: - raise ToolError(f"{families[family]['title']} has no {model}; its sizes: {', '.join(sizes)}") - d = sizes[model] - if context is None: - usable = [g for g in hw.get("gpus", []) if g.get("usable")] - vram = max((g["vram_gb"] for g in usable), default=12) - context = 32768 if vram < 14 else 65536 if vram < 20 else 131072 - if d.get("budget") and (not hasattr(s.setup_module(), "unsloth_budget") or - s.setup_module().unsloth_budget(model, hw.get("ram_gb") or 0.0)): - context = 8192 if vram < 14 else 32768 - if families[family].get("engine") == "poly": - context = 32768 # the one it was measured with, setup's own default - if vision in ("yes", "gpu", "cpu") and d.get("vision", families[family].get("vision")) is False: - raise ToolError(f"images are not available with {families[family]['title']} {model} yet: use vision=no") - if vision is not None and backend == "hip" and vision != "no": - # setup.py's hip_vision rules (#990): the AMD backend has no GPU image encoder, but --vision cpu reads - # images on the CPU beside it (Linux; the ready-made Windows AMD engine has no encoder) - if vision == "cpu" and not WIN: - pass - elif vision == "cpu": - raise ToolError("images on the CPU with an AMD card are Linux-only for now: use vision=no") - else: - raise ToolError("the AMD backend has no GPU image encoder yet: use vision=cpu (images on the CPU, " - "Linux) or vision=no") - target = self.check_data_dir(data_dir) if data_dir else s.data_dir() - tag = (families[family].get("tag", "") + model) - have_dir = target / "models" / tag - partly = have_dir.is_dir() and any(have_dir.glob("*.gguf*")) - need = (8 if partly else d["download_gb"] + 8) + (1 if vision in ("yes", "gpu", "cpu") else 0) - free = s.disk_free(target) - short = None - if free is not None and free < need: - short = (f"not enough free disk space for {model}: about {need:.0f} GB needed at {target}, " - f"{free:.0f} GB free; free some space or choose data_dir on a bigger drive (e.g. D:\\PolyStrata-data)") - args = ["--yes", "--no-start", "--family", family, "--model", model, "--context", str(context), - "--vision", vision or "no"] - if family in ("qwen", "coder"): - args += ["--experimental-speed-projection", "off"] - for flag, v in (("--kv", kv), ("--gpu", gpu), ("--gpus", gpus), ("--low-ram", low_ram), ("--port", port), - ("--data-dir", str(target) if data_dir else None)): - if v is not None: - args += [flag, str(v)] - if backend in ("cuda", "hip"): - args += ["--backend", backend] - fit = None - ram = hw.get("ram_gb") - if ram is not None: - need_ram = d["ram_gb"] - fit = "fits" if ram >= need_ram else f"needs ~{need_ram} GB of RAM, this PC has {ram:.0f} GB" - installed = (s.root / f"strata-{tag.lower()}.json").exists() - plan = {"title": f"{families[family]['title']} {model}", "family": family, "model": model, - "context": context, "images": vision or "no", "download_gb": d["download_gb"], - "partly_downloaded": partly, "ram": fit, "data_folder": str(target), "disk_free_gb": free, - "disk_needed_gb": round(need), "disk_short": short, "already_installed": installed, - "setup_command": ("START-HERE.bat " if WIN else "./setup.sh ") + " ".join(args), - "takes": "about 20-90 minutes, mostly the download; the PC stays usable", - "recommended_for_this_pc": rec if rec.get("model") else None} - if installed: - plan["note"] = ("this model is already installed: running setup again updates the engine and applies " - "the options (finished steps are skipped)") - if families[family].get("license"): - plan["license"] = families[family]["license"] - if families[family].get("experimental") or d.get("experimental"): - plan["experimental"] = True - return plan, args - - def launch_install(self, plan: dict, args: list) -> dict: - s = self.s - s.state_dir.mkdir(parents=True, exist_ok=True) - job_id = f"{int(time.time())}-{os.getpid()}" - log_path = s.state_dir / "setup.log" - with open(log_path, "a", encoding="utf-8") as f: - f.write(f"\n===== strata-mcp: install {plan['title']} at {time.strftime('%Y-%m-%d %H:%M:%S')} =====\n") - spec = {"job": job_id, "root": str(s.root), "python": s.run_python(), "base_python": sys.executable, - "create_venv": s.python_override is None and not s.venv_python().exists(), - "args": args, "result": str(s.state_dir / "install-result.json")} - spec_path = s.state_dir / "install-job.json" - spec_path.write_text(json.dumps(spec, indent=1), encoding="utf-8") - s.save_state("install-result", None) - env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8") - p = spawn_detached([sys.executable, str(Path(__file__).resolve()), "--install-job", str(spec_path)], - s.root, log_path, env) - s.children.append(p) - time.sleep(0.2) - ident = proc_identity(p.pid) - if ident is None and p.poll() and s.state("install-result").get("job") != job_id: - raise ToolError("setup did not start: " + " | ".join(read_tail(log_path, 5))) - s.save_state("install", {"job": job_id, "pid": p.pid, "ident": ident, "log": str(log_path), - "model": plan["model"], "family": plan["family"], - "started": time.strftime("%Y-%m-%d %H:%M:%S"), "args": args}) - return {"summary": f"Install of {plan['title']} started in the background (about 20-90 minutes, mostly the " - f"{plan['download_gb']:.0f} GB download). Call strata_install again to see the progress; " - "when it is done, start it with strata_start.", - "plan": plan, "log": str(log_path), "pid": p.pid} - - # ---- strata_start - def strata_start(self, model=None, port=None, gpu=None, wait_seconds=50) -> dict: - s = self.s - with s.lock: - job = s.install_job() - if job and job["running"]: - raise ToolError("an install is still running (strata_install shows its progress); start the model " - "when it is done") - cfg_path = s.find_config(model) - desc = s.describe_config(cfg_path) - if not desc["ready"]: - raise ToolError(f"{cfg_path.name} refers to missing files ({', '.join(desc['missing_files'])}): run " - "the install again (strata_install with confirm=true) to repair it") - port = port or desc["port"] or DEFAULT_PORT - tracked = s.tracked_server() - if tracked and not tracked.get("ended"): - info = s.probe(tracked["port"]) - return {"summary": f"PolyStrata is already {'running' if info else 'loading'} ({tracked.get('model')}, " - f"port {tracked['port']}, started by this MCP server)" - + ("" if tracked.get("model") == desc["model"] else - ": stop it first (strata_stop) to start another model"), - "server": info} - info = s.probe(port, deep=False) - if info and not info.get("other"): - return {"summary": f"a PolyStrata server already runs on port {port} ({info.get('model')}), started " - "outside this MCP server; stop it (close its window) or use another port", - "server": info} - if info or not port_free(port): - raise ToolError(f"port {port} is used by another program; choose another port (port=...)") - py = s.run_python() - if not Path(py).exists(): - raise ToolError("PolyStrata's Python environment (.venv) is missing: run the install again") - cmd = [py, str(s.root / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), - "--port", str(port)] - if gpu is not None: - cmd += ["--gpu", str(gpu)] - log_path = s.state_dir / "server.log" - s.state_dir.mkdir(parents=True, exist_ok=True) - with open(log_path, "a", encoding="utf-8") as f: - f.write(f"\n===== strata-mcp: start {desc['model']} on port {port} at " - f"{time.strftime('%Y-%m-%d %H:%M:%S')} =====\n") - env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8") - try: - os.utime(cfg_path) # the most recently used model, as setup's start marks it - except OSError: - pass - p = spawn_detached(cmd, s.root, log_path, env) - s.children.append(p) - time.sleep(0.1) - ident = proc_identity(p.pid) - s.save_state("server", {"pid": p.pid, "ident": ident, "port": port, "model": desc["model"], - "config": cfg_path.name, "log": str(log_path), - "started": time.strftime("%Y-%m-%d %H:%M:%S")}) - return self.wait_ready(p, ident, port, desc, wait_seconds, log_path) - - def wait_ready(self, p, ident, port, desc, wait_seconds, log_path) -> dict: - s = self.s - end = time.time() + wait_seconds - while True: - if p.poll() is not None or not proc_alive(p.pid, ident): - tail = read_tail(log_path, 15) - end_group_leftovers(p.pid) - s.save_state("server", None) - raise ToolError(f"PolyStrata stopped while starting (exit code {p.poll()}). Its last output:\n" - + "\n".join(tail)) - info = s.probe(port) - if info and not info.get("other"): - return {"summary": f"PolyStrata is running: {info.get('model')} on http://127.0.0.1:{port}/v1 " - "(OpenAI and Anthropic APIs; chat page at http://127.0.0.1:" + str(port) + "/)", - "server": {**info, "pid": p.pid}} - if time.time() >= end: - return {"summary": f"PolyStrata is loading {desc['model']} (this takes 1-3 minutes; the PC may be slow " - "meanwhile). Check with strata_status in a minute.", - "loading": {"pid": p.pid, "port": port, - "last_log_line": (read_tail(log_path, 1) or [None])[-1]}} - time.sleep(1.0) - - # ---- strata_stop - def strata_stop(self, port=None, force=False) -> dict: - s = self.s - with s.lock: - tracked = s.tracked_server() - if tracked and tracked.get("ended"): - s.save_state("server", None) - tracked = None - if tracked: - port = tracked["port"] - key = s.api_key_for(port) - st, body = http_json(f"http://127.0.0.1:{port}/status", api_key=key, timeout=3) - if st == 200 and isinstance(body, dict) and body.get("busy") and not force: - raise ToolError("a request is running on PolyStrata right now; wait for it, or call strata_stop " - "with force=true to stop anyway") - st, body = http_json(f"http://127.0.0.1:{port}/unload", "POST", api_key=key, timeout=120) - unloaded = (body or {}).get("status") if isinstance(body, dict) else None - if st == 409 and not force: - raise ToolError("PolyStrata is busy (a request is running or queued); call again with force=true " - "to stop anyway") - proc_terminate(tracked["pid"], tracked["ident"]) # POSIX: SIGTERM = the server's own Ctrl+C path - clean = wait_gone(tracked["pid"], tracked["ident"], 30) - if not clean: - proc_kill_tree(tracked["pid"], tracked["ident"]) - wait_gone(tracked["pid"], tracked["ident"], 15) - s.reap() - gone = not proc_alive(tracked["pid"], tracked["ident"]) - if gone: - end_group_leftovers(tracked["pid"]) - s.save_state("server", None) - return {"summary": "PolyStrata stopped" + ("" if gone else " - but its process still runs; see strata_logs") - + (" (the engine unloaded itself first)" if unloaded == "unloaded" else ""), - "model": tracked.get("model"), "port": port, "engine_unloaded": unloaded, - "ended_cleanly": clean} - for p in s.ports(port): - info = s.probe(p, deep=False) - if info and not info.get("other"): - key = s.api_key_for(p) - st, body = http_json(f"http://127.0.0.1:{p}/unload", "POST", api_key=key, timeout=120) - r = body.get("status") if isinstance(body, dict) else None - if st == 409: - raise ToolError("PolyStrata is busy (a request is running); try again when it is done") - if st == 401: - raise ToolError("PolyStrata (started outside this MCP server) wants an API key this folder's " - "configs do not have; close its window to stop it") - return {"summary": f"PolyStrata on port {p} was started outside this MCP server (its own window or a " - f"service), so only its model was unloaded ({r}): its VRAM and RAM are free, " - "but the server still listens and loads the model again on the next request. " - "Close its window to end it completely.", - "port": p, "engine_unloaded": r} - return {"summary": "PolyStrata is not running"} - - # ---- strata_logs - def strata_logs(self, source=None, model=None, lines=80) -> dict: - s = self.s - if source is None: - job = s.install_job() - source = "setup" if job and job["running"] else "server" - if source == "setup": - path = s.state_dir / "setup.log" - elif source == "server": - path = s.state_dir / "server.log" - else: - cfg = s.find_config(model or (s.state("server").get("model"))) - raw = s.read_config(cfg).get("log") - if not raw: - raise ToolError(f"{cfg.name} names no engine log") - path = Path(raw) - if not s.allowed(path): - raise ToolError(f"{cfg.name}'s log {raw} is outside the PolyStrata folder and its data folder: not shown") - if not path.exists(): - return {"summary": f"no {source} log yet ({path})", "log": str(path), "lines": []} - tail = read_tail(path, lines) - return {"summary": f"last {len(tail)} lines of the {source} log", "log": str(path), "lines": tail} - - # ---- strata_benchmark - def strata_benchmark(self, port=None, max_tokens=200) -> dict: - s = self.s - target = None - for p in s.ports(port): - info = s.probe(p, deep=False) - if info and not info.get("other"): - target = info - break - if target is None: - raise ToolError("PolyStrata is not running: start it first (strata_start)") - p = target["port"] - key = s.api_key_for(p) - st, stat = http_json(f"http://127.0.0.1:{p}/status", api_key=key, timeout=3) - if st == 200 and isinstance(stat, dict) and (stat.get("busy") or stat.get("queued")): - raise ToolError("PolyStrata is busy with a request; run the speed test when it is idle") - body = {"model": target.get("model") or "strata", "max_tokens": max_tokens, "temperature": 0, - "reasoning_effort": "none", "stream": False, - "messages": [{"role": "user", "content": BENCH_PROMPT}]} - t0 = time.time() - st, r = http_json(f"http://127.0.0.1:{p}/v1/chat/completions", "POST", body, api_key=key, timeout=600) - wall = time.time() - t0 - if st != 200 or not isinstance(r, dict): - msg = (r or {}).get("error", {}).get("message") if isinstance(r, dict) else None - raise ToolError(f"the request failed (HTTP {st}): {msg or 'no answer'}") - usage, tm = r.get("usage") or {}, r.get("timings") or {} - n = usage.get("completion_tokens") or tm.get("predicted_n") or 0 - out = {"model": r.get("model"), "port": p, "prompt_tokens": usage.get("prompt_tokens"), - "output_tokens": n, "wall_s": round(wall, 2), - "output_tok_s": round(tm["predicted_per_second"], 1) if tm.get("predicted_per_second") else None, - "prompt_tok_s": round(tm["prompt_per_second"], 1) if tm.get("prompt_per_second") else None, - "wall_tok_s": round(n / wall, 1) if wall > 0 and n else None, - "finish_reason": ((r.get("choices") or [{}])[0]).get("finish_reason"), - "settings": f"greedy (temperature 0), thinking off, max_tokens {max_tokens}, a fixed story prompt"} - speed = out["output_tok_s"] or out["wall_tok_s"] - out["summary"] = (f"{n} tokens at {speed} tokens/s" + (f" (prompt {out['prompt_tok_s']} tokens/s)" - if out["prompt_tok_s"] else "") - + f", {wall:.1f} s in total") - out["note"] = ("output speed depends on the context length, the GPU's free VRAM and what else the PC does; " - "the first request after a start is slower") - return out - - # ---- strata_connect_info - def strata_connect_info(self, port=None) -> dict: - s = self.s - target = None - for p in s.ports(port): - info = s.probe(p, deep=False) - if info and not info.get("other"): - target = info - break - if port is None: - cfgs = s.configs() - port = target["port"] if target else (s.describe_config(cfgs[0])["port"] if cfgs else DEFAULT_PORT) - model = (target or {}).get("model") or "strata" - key_needed = (target or {}).get("api_key_required") - if key_needed is None: - key_needed = any(s.describe_config(c)["api_key_set"] for c in s.configs()) - key = ".json>" if key_needed else "none" - base = f"http://127.0.0.1:{port}" - return { - "summary": (f"PolyStrata {'runs' if target else 'will run'} at {base}: OpenAI base URL {base}/v1, Anthropic " - f"base URL {base}" + (" (an API key is required)" if key_needed else " (any API key works)")), - "running": bool(target), "openai_base_url": f"{base}/v1", "anthropic_base_url": base, - "anthropic_messages_endpoint": f"{base}/v1/messages", "chat_page": base + "/", "model": model, - "api_key": ("required: the \"api_key\" value in the PolyStrata folder's strata-.json" - if key_needed else "not required (send any value)"), - "examples": { - "claude_code": {"env": {"ANTHROPIC_BASE_URL": base, "ANTHROPIC_AUTH_TOKEN": key, - "ANTHROPIC_MODEL": "claude-sonnet-4-5"}, - "note": "Claude Code needs a Claude model name it knows; PolyStrata ignores the name"}, - "codex_cli": {"file": "~/.codex/config.toml", - "toml": f'model = "{model}"\nmodel_provider = "strata"\n\n[model_providers.strata]\n' - f'name = "PolyStrata"\nbase_url = "{base}/v1"\nwire_api = "chat"'}, - "openai_python": (f'from openai import OpenAI\nclient = OpenAI(base_url="{base}/v1", api_key="{key}")\n' - f'r = client.chat.completions.create(model="{model}", messages=[{{"role": "user", ' - f'"content": "Hello!"}}])\nprint(r.choices[0].message.content)'), - "curl": (f"curl {base}/v1/chat/completions -H \"Content-Type: application/json\" " - + (f"-H \"Authorization: Bearer {key}\" " if key_needed else "") - + f"-d '{{\"model\": \"{model}\", \"messages\": [{{\"role\": \"user\", \"content\": " - "\"Hello!\"}]}'"), - "openai_compatible_apps": {"base_url": f"{base}/v1", "api_key": key, "model": model, - "apps": "Cursor (Settings > Models > OpenAI base URL override), " - "Continue, Open WebUI, LM Studio clients, aider " - f"(--openai-api-base {base}/v1)"}}, - "other_devices": "the server listens on this PC only; to reach it from your network, run setup with " - "--host 0.0.0.0 --api-key (docs/DETAILS.md, 'Using it')"} - - -# ------------------------------------------------------------------------------------------------ MCP over stdio -INSTRUCTIONS = ("PolyStrata runs a large AI model (Qwen3.8-Flash-Next, a mixture of experts) locally on this PC's GPU and " - "RAM, with an OpenAI- and Anthropic-compatible server on http://127.0.0.1:8080. Call strata_status " - "first. To install: strata_install (it returns a plan; get the user's OK for the 58-111 GB download, " - "then call it with confirm=true; it runs in the background - call it again for progress). Then " - "strata_start, strata_stop, strata_logs for problems, strata_connect_info to point other apps at it.") - - -class McpServer: - def __init__(self, strata: Strata, out=None): - self.strata = strata - self.tools = Tools(strata) - self.out = out - self.write_lock = threading.Lock() - self.protocol = PROTOCOL - - def send(self, msg: dict) -> None: - data = (json.dumps(msg, ensure_ascii=False) + "\n").encode("utf-8") - with self.write_lock: - self.out.write(data) - self.out.flush() - - @staticmethod - def result(rid, result): - return {"jsonrpc": "2.0", "id": rid, "result": result} - - @staticmethod - def error(rid, code, message): - return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}} - - def handle(self, msg) -> dict | None: - """One JSON-RPC message -> its response (None for a notification or a response).""" - if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0": - return self.error(msg.get("id") if isinstance(msg, dict) else None, -32600, "invalid request") - if "method" not in msg: - return None # a response to something we never ask: ignored - method, rid, params = msg["method"], msg.get("id"), msg.get("params") or {} - if "id" not in msg: - return None # notifications (initialized, cancelled ...): nothing to say - if not isinstance(params, dict): - return self.error(rid, -32602, "params must be an object") - if method == "initialize": - asked = str(params.get("protocolVersion") or PROTOCOL) - self.protocol = asked if asked in PROTOCOLS else PROTOCOL - return self.result(rid, {"protocolVersion": self.protocol, - "capabilities": {"tools": {"listChanged": False}}, - "serverInfo": {"name": "strata", "title": "PolyStrata", "version": VERSION}, - "instructions": INSTRUCTIONS}) - if method == "ping": - return self.result(rid, {}) - if method == "tools/list": - return self.result(rid, {"tools": self.tools.defs()}) - if method == "tools/call": - name = params.get("name") - try: - res = self.tools.call(name, params.get("arguments")) - return self.result(rid, self.content(res, error=False)) - except KeyError: - return self.error(rid, -32602, f"unknown tool: {name}") - except ToolError as e: - return self.result(rid, self.content({"error": str(e)}, error=True)) - except Exception as e: # noqa: BLE001 - a bug must not end the server - log("tool failed:\n" + traceback.format_exc()) - return self.result(rid, self.content({"error": f"internal error in {name}: {e}"}, error=True)) - if method in ("resources/list", "prompts/list"): - return self.result(rid, {method.split("/")[0]: []}) - return self.error(rid, -32601, f"method not found: {method}") - - def content(self, res: dict, error: bool) -> dict: - text = json.dumps(res, indent=1, ensure_ascii=False) - out = {"content": [{"type": "text", "text": text}], "isError": error} - if self.protocol >= "2025-06-18": - out["structuredContent"] = res - return out - - def serve(self, inp) -> None: - """Read JSON-RPC lines until stdin closes; tool calls run in their own threads (a start waits for the model - while pings and status calls are still answered).""" - threads = [] - for raw in inp: - line = raw.decode("utf-8", "replace").strip() if isinstance(raw, bytes) else raw.strip() - if not line: - continue - try: - msg = json.loads(line) - except ValueError: - self.send(self.error(None, -32700, "parse error")) - continue - batch = isinstance(msg, list) - if batch or (isinstance(msg, dict) and msg.get("method") == "tools/call"): - t = threading.Thread(target=self._run, args=(msg,), daemon=True) - t.start() - threads.append(t) - threads = [x for x in threads if x.is_alive()] - else: - self._run(msg) - for t in threads: - t.join(timeout=5) - - def _run(self, msg) -> None: - if isinstance(msg, list): - out = [r for r in (self.handle(m) for m in msg) if r is not None] - if out: - data = (json.dumps(out, ensure_ascii=False) + "\n").encode("utf-8") - with self.write_lock: - self.out.write(data) - self.out.flush() - return - r = self.handle(msg) - if r is not None: - self.send(r) - - -# ------------------------------------------------------------------------------------------------ the install job -def install_job(spec_path: str) -> int: - """The background half of strata_install (this file started again with --install-job): make .venv like - START-HERE.bat / setup.sh do when it is missing, run setup, record its exit code.""" - spec = json.loads(Path(spec_path).read_text(encoding="utf-8")) - root = Path(spec["root"]) - result = Path(spec["result"]) - - def record(**kw): - try: - old = json.loads(result.read_text(encoding="utf-8")) if result.exists() else {} - except (OSError, ValueError): - old = {} - tmp = result.with_suffix(".tmp") - tmp.write_text(json.dumps({**old, "job": spec["job"], **kw}, indent=1), encoding="utf-8") - os.replace(tmp, result) - - py = Path(spec["python"]) - try: - if spec.get("create_venv"): - venv = root / ".venv" - if py.exists() and subprocess.run([str(py), "-m", "pip", "--version"], capture_output=True).returncode: - print("strata-mcp: .venv has no pip (an earlier run stopped half-way): making it again", flush=True) - shutil.rmtree(venv, ignore_errors=True) - if not py.exists(): - print(f"strata-mcp: creating PolyStrata's Python environment in {venv} ...", flush=True) - r = subprocess.run([spec["base_python"], "-m", "venv", str(venv)]) - if r.returncode or not py.exists(): - print("\n [X] could not create the Python environment (.venv)", flush=True) - print(" Linux: install python3-venv (sudo apt install python3-venv) or run ./setup.sh " - "once in a terminal", flush=True) - record(exit_code=1, ended=time.strftime("%Y-%m-%d %H:%M:%S")) - return 1 - cmd = [str(py), str(root / "setup.py"), *spec["args"]] - print("strata-mcp: running " + " ".join(cmd), flush=True) - env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8") - p = subprocess.Popen(cmd, cwd=str(root), stdin=subprocess.DEVNULL, env=env) - record(child_pid=p.pid, child_ident=proc_identity(p.pid)) - rc = p.wait() - except Exception as e: # noqa: BLE001 - print(f"\n [X] strata-mcp could not run setup: {e}", flush=True) - rc = 1 - print(f"strata-mcp: setup ended with exit code {rc}", flush=True) - record(exit_code=rc, ended=time.strftime("%Y-%m-%d %H:%M:%S")) - return rc - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="PolyStrata's MCP server (stdio): install, start, check and stop PolyStrata " - "from an AI assistant. See docs/MCP_SERVER.md.") - ap.add_argument("--root", help="the PolyStrata folder (default: the one this file is in)") - ap.add_argument("--install-job", help=argparse.SUPPRESS) - a = ap.parse_args(argv) - if a.install_job: - return install_job(a.install_job) - if sys.version_info < (3, 10): - log("Python 3.10 or newer is needed") - return 2 - root = Path(a.root).expanduser().resolve() if a.root else DEFAULT_ROOT - if not (root / "setup.py").is_file() or not (root / "serve" / "server.py").is_file(): - log(f"{root} is not a PolyStrata folder (no setup.py / serve/server.py)") - return 2 - out = sys.stdout.buffer - sys.stdout = sys.stderr # stray prints must never corrupt the protocol stream - server = McpServer(Strata(root), out) - log(f"ready (PolyStrata folder {root})") - try: - server.serve(sys.stdin.buffer) - except KeyboardInterrupt: - pass - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/test_docker_entrypoint.py b/tools/test_docker_entrypoint.py deleted file mode 100644 index 582415f..0000000 --- a/tools/test_docker_entrypoint.py +++ /dev/null @@ -1,117 +0,0 @@ -"""docker-entrypoint.sh keeps the install config on the /data volume as the one that counts (#1244): with REINSTALL=0 -and a config on the volume, /opt/strata/strata-.json is a link to it, even when a regular file is already there. -Runs the real script in a temporary tree with a stub for .venv/bin/python (POSIX sh and symlinks needed: skipped on -Windows). - - python -m unittest tools.test_docker_entrypoint -""" -from __future__ import annotations - -import os -import shutil -import subprocess -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -SH = shutil.which("sh") - - -@unittest.skipIf(os.name == "nt" or SH is None, "needs POSIX sh and symlinks") -class Entrypoint(unittest.TestCase): - def setUp(self): - self.tmp = Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) - self.opt = self.tmp / "opt" - self.data = self.tmp / "data" - (self.opt / ".venv" / "bin").mkdir(parents=True) - (self.data / "config").mkdir(parents=True) - # the stub "python": setup.py --setup writes the config the way setup does; a plain start prints what it would load - stub = self.opt / ".venv" / "bin" / "python" - stub.write_text('#!/bin/sh\nif [ "$2" = "--setup" ]; then echo \'{"args": ["from-setup"]}\' > strata-iq3_s.json\n' - 'else echo "STARTED WITH: $(cat strata-iq3_s.json)"; fi\n', encoding="utf-8") - stub.chmod(0o755) - script = (ROOT / "docker-entrypoint.sh").read_text(encoding="utf-8").replace("/opt/strata", str(self.opt)) - self.script = self.tmp / "entry.sh" - self.script.write_text(script, encoding="utf-8") - - def run_entry(self, reinstall, **extra): - env = dict(os.environ, STRATA_DATA=str(self.data), MODEL="IQ3_S", REINSTALL=reinstall, **extra) - r = subprocess.run([SH, str(self.script)], env=env, capture_output=True, text=True, timeout=60) - self.assertEqual(r.returncode, 0, r.stderr) - return r.stdout - - def test_edited_volume_config_wins_over_a_regular_file_in_opt(self): - (self.data / "config" / "strata-iq3_s.json").write_text('{"args": ["edited", "--kv-resident", "32768"]}\n') - (self.opt / "strata-iq3_s.json").write_text('{"args": ["stale"]}\n') # left by an earlier setup - out = self.run_entry("0") - self.assertIn("edited", out) - self.assertNotIn("stale", out) - self.assertTrue((self.opt / "strata-iq3_s.json").is_symlink()) - - def test_link_is_made_when_there_is_no_file(self): - (self.data / "config" / "strata-iq3_s.json").write_text('{"args": ["on-volume"]}\n') - self.assertIn("on-volume", self.run_entry("0")) - - def test_first_setup_copies_the_config_to_the_volume_and_the_next_start_links_it(self): - out = self.run_entry("0") # no config on the volume: setup runs - self.assertIn("from-setup", out) - cfg = self.data / "config" / "strata-iq3_s.json" - self.assertIn("from-setup", cfg.read_text()) - cfg.write_text('{"args": ["edited-later"]}\n') - self.assertIn("edited-later", self.run_entry("0")) # the regular file setup left is replaced by the link - - def test_existing_link_into_the_data_config_dir_is_kept(self): # a pod command that picked a config by linking - (self.data / "config" / "strata-iq3_s.json").write_text('{"args": ["plain"]}\n') - other = self.data / "config" / "strata-iq3_s.1x4.json" - other.write_text('{"args": ["batch8"]}\n') - os.symlink(other, self.opt / "strata-iq3_s.json") - out = self.run_entry("0") - self.assertIn("batch8", out) - self.assertNotIn("plain", out) - self.assertIn(f"Config: {other}", out) - - def test_link_to_somewhere_else_is_replaced(self): - (self.data / "config" / "strata-iq3_s.json").write_text('{"args": ["on-volume"]}\n') - elsewhere = self.tmp / "elsewhere.json" - elsewhere.write_text('{"args": ["elsewhere"]}\n') - os.symlink(elsewhere, self.opt / "strata-iq3_s.json") - self.assertIn("on-volume", self.run_entry("0")) - - def test_config_env_wins(self): - (self.data / "config" / "strata-iq3_s.json").write_text('{"args": ["plain"]}\n') - other = self.tmp / "mine.json" - other.write_text('{"args": ["mine"]}\n') - os.symlink(self.data / "config" / "strata-iq3_s.json", self.opt / "strata-iq3_s.json") - out = self.run_entry("0", CONFIG=str(other)) - self.assertIn("mine", out) - self.assertNotIn("plain", out) - self.assertIn(f"Config: {other}", out) - - def test_model_names_the_config_and_it_is_printed(self): - (self.data / "config" / "strata-iq3_s.json").write_text('{"args": ["by-model"]}\n') - out = self.run_entry("0") - self.assertIn("by-model", out) - self.assertIn(f"Config: {self.data}/config/strata-iq3_s.json", out) - - def warning_for(self, flags): - info = self.tmp / "cpuinfo" - info.write_text(f"processor\t: 0\nflags\t\t: {flags}\n") - (self.data / "config" / "strata-iq3_s.json").write_text('{"args": ["x"]}\n') - env = dict(os.environ, STRATA_DATA=str(self.data), MODEL="IQ3_S", REINSTALL="0", STRATA_CPUINFO=str(info)) - r = subprocess.run([SH, str(self.script)], env=env, capture_output=True, text=True, timeout=60) - self.assertEqual(r.returncode, 0, r.stderr) # a warning, never a stop (#1584) - return r.stderr - - def test_a_cpu_without_avx2_is_warned_not_stopped(self): - err = self.warning_for("fpu sse4_2 avx aes") - self.assertIn("no AVX2", err) - self.assertIn("docker build", err) - - def test_a_cpu_with_avx2_gets_no_warning(self): - self.assertEqual(self.warning_for("fpu sse4_2 avx avx2 fma"), "") - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_poly_prebuilt.py b/tools/test_poly_prebuilt.py deleted file mode 100644 index bfa34ba..0000000 --- a/tools/test_poly_prebuilt.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Tests for setup.py's ready-made strata-poly (get_poly_prebuilt) from a local release folder: the asset of this -source is installed, one for another source or another card is not, and an engine already there is kept. No GPU, -no network, no pip. - - python -m unittest tools.test_poly_prebuilt -""" -from __future__ import annotations - -import json -import sys -import tempfile -import unittest -import zipfile -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - -SRC = "0123456789abcdef" -GPU = {"arch": 89, "driver": "581.57"} - - -def release(folder: Path, src=SRC, archs=(75, 80, 86, 89, 120)) -> None: - with zipfile.ZipFile(folder / setup.POLY_ASSET.format(src=src), "w") as f: - f.writestr(setup.POLY_EXE, "new engine") - f.writestr(setup.VEXE, "new encoder") - f.writestr("BUILD.json", json.dumps({"source": "release", "archs": list(archs), "cuda": "13.0", "src": src, - "vision_src": src})) - - -class PolyPrebuilt(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = Path(self.tmp.name) / "repo" - self.rel = Path(self.tmp.name) / "release" - self.root.mkdir() - self.rel.mkdir() - self.eng = self.root / setup.ENGINE_POLY_DIR - for p in (mock.patch.object(setup, "ROOT", self.root), mock.patch.object(setup, "WIN", True), - mock.patch.object(setup, "POLY_PREBUILT_URL", str(self.rel)), - mock.patch.object(setup, "source_hash", lambda parts: SRC), - mock.patch.object(setup, "cpu_info", lambda: ("an AVX2 CPU", True, False)), - mock.patch.object(setup, "pip_cuda_libs", lambda toolkit=13: None)): - p.start() - self.addCleanup(p.stop) - self.addCleanup(self.tmp.cleanup) - - def test_installs_the_asset_of_this_source(self): - release(self.rel) - self.assertTrue(setup.get_poly_prebuilt(GPU)) - self.assertEqual((self.eng / setup.POLY_EXE).read_text(), "new engine") - self.assertEqual((self.eng / setup.VEXE).read_text(), "new encoder") - self.assertEqual(json.loads((self.eng / "BUILD.json").read_text())["source"], "release") - self.assertEqual(sorted(p.name for p in self.eng.iterdir()), sorted(["BUILD.json", setup.POLY_EXE, setup.VEXE])) - - def test_none_for_another_source(self): - release(self.rel, src="fedcba9876543210") - self.assertFalse(setup.get_poly_prebuilt(GPU)) - self.assertFalse((self.eng / setup.POLY_EXE).exists()) - - def test_none_for_a_card_it_has_no_code_for(self): - release(self.rel) - self.assertFalse(setup.get_poly_prebuilt({"arch": 90, "driver": "581.57"})) - self.assertFalse((self.eng / setup.POLY_EXE).exists()) - - def test_none_with_a_driver_older_than_cuda_13(self): - release(self.rel) - self.assertFalse(setup.get_poly_prebuilt({"arch": 89, "driver": "576.88"})) - - def test_none_for_a_cpu_without_avx2(self): - release(self.rel) - with mock.patch.object(setup, "cpu_info", lambda: ("an older CPU", False, False)): - self.assertFalse(setup.get_poly_prebuilt(GPU)) - - def test_a_failed_pip_leaves_the_engine_there(self): - self.eng.mkdir() - (self.eng / setup.POLY_EXE).write_text("compiled here") - release(self.rel) - with mock.patch.object(setup, "pip_cuda_libs", side_effect=SystemExit(1)): - with self.assertRaises(SystemExit): - setup.get_poly_prebuilt(GPU) - self.assertEqual((self.eng / setup.POLY_EXE).read_text(), "compiled here") - - def test_an_update_downloads_in_place_of_a_ready_made_engine_alone(self): - release(self.rel) - self.eng.mkdir() - cfg = {"exe": str(self.eng / setup.POLY_EXE), "args": []} - for source, want in (("local", "compiled here"), ("release", "new engine")): - (self.eng / setup.POLY_EXE).write_text("compiled here") - (self.eng / "BUILD.json").write_text(json.dumps({"source": source, "archs": [89], "src": "older"})) - with mock.patch.object(setup, "gpu_info", lambda i=None: GPU), \ - mock.patch.object(setup, "build_engine_poly", lambda *a: self.eng), \ - mock.patch.object(setup, "get_llama_cpp", lambda: None): - setup.update_poly_engine(dict(cfg)) - self.assertEqual((self.eng / setup.POLY_EXE).read_text(), want, source) - - def test_an_update_without_a_release_of_its_source_keeps_the_ready_made_engine(self): - release(self.rel, src="fedcba9876543210") - self.eng.mkdir() - (self.eng / setup.POLY_EXE).write_text("ready-made") - (self.eng / "BUILD.json").write_text(json.dumps({"source": "release", "archs": [89], "src": "older"})) - build = mock.Mock() - with mock.patch.object(setup, "gpu_info", lambda i=None: GPU), \ - mock.patch.object(setup, "build_engine_poly", build): - setup.update_poly_engine({"exe": str(self.eng / setup.POLY_EXE), "args": []}) - build.assert_not_called() - self.assertEqual((self.eng / setup.POLY_EXE).read_text(), "ready-made") - - def test_a_ready_made_engine_with_an_older_encoder_is_replaced(self): - release(self.rel) - self.eng.mkdir() - (self.eng / setup.POLY_EXE).write_text("ready-made") - (self.eng / "BUILD.json").write_text(json.dumps({"source": "release", "archs": [89], "src": SRC, - "vision_src": "older"})) - self.assertTrue(setup.get_poly_prebuilt(GPU)) - self.assertEqual((self.eng / setup.VEXE).read_text(), "new encoder") - - def test_an_engine_of_this_source_is_kept(self): - self.eng.mkdir() - (self.eng / setup.POLY_EXE).write_text("compiled here") - (self.eng / "BUILD.json").write_text(json.dumps({"source": "local", "archs": [89], "src": SRC})) - release(self.rel) - self.assertTrue(setup.get_poly_prebuilt(GPU)) - self.assertEqual((self.eng / setup.POLY_EXE).read_text(), "compiled here") - - def test_a_compile_after_it_is_for_this_card_alone(self): - release(self.rel) - setup.get_poly_prebuilt(GPU) - meta = json.loads((self.eng / "BUILD.json").read_text()) - meta["src"] = "a source it was not built from" - (self.eng / "BUILD.json").write_text(json.dumps(meta)) - with mock.patch.object(setup, "install_build_tools", side_effect=RuntimeError("compiles")) as tools: - with self.assertRaises(RuntimeError): - setup.build_engine_poly(GPU, True, None) - self.assertEqual(tools.call_args[0][0]["archs"], [89]) - - def compile_here(self, gpu, toolkit, vision="none"): - """build_engine_poly() with a compile that writes what it was asked: (the CMake definitions, the toolkit).""" - made = {} - - def cmake(src, bdir, target, defs, vcvars, script): - made.setdefault(target, defs) - out = bdir / "bin" if target == "strata-vision" else bdir - out.mkdir(parents=True, exist_ok=True) - (out / (setup.VEXE if target == "strata-vision" else setup.POLY_EXE)).write_text(f"{target} {toolkit}") - with mock.patch.object(setup, "install_build_tools", lambda g, yes: (str(self.root / "nvcc"), None)), \ - mock.patch.object(setup, "cmake_build", cmake), mock.patch.object(setup, "cuda_lib_dirs", lambda t: []), \ - mock.patch.object(setup, "source_version", lambda: "0.1.42"): - setup.build_engine_poly(gpu, True, None, vision, toolkit) - return made - - def test_cuda_12_compiles_in_place_of_a_ready_made_engine(self): - release(self.rel) - setup.get_poly_prebuilt(GPU) - made = self.compile_here(GPU, 12, "gpu") - self.assertEqual(sorted(made), ["strata-poly", "strata-vision"]) - self.assertNotIn("-DSTRATA_EXPERIMENTAL_SM60=ON", made["strata-poly"]) - meta = json.loads((self.eng / "BUILD.json").read_text()) - self.assertEqual((meta["toolkit"], meta["archs"], meta["source"]), (12, [89], "local")) - # the ready-made one is not taken back while the model asks for CUDA 12, and is when it no longer does - self.assertEqual(self.compile_here(GPU, 12, "gpu"), {}) - self.assertTrue(setup.get_poly_prebuilt(GPU)) - self.assertEqual((self.eng / setup.POLY_EXE).read_text(), "new engine") - - def test_cuda_12_for_a_pascal_card_is_the_experimental_build(self): - made = self.compile_here({"arch": 61, "driver": "550.54"}, 12) - self.assertIn("-DSTRATA_EXPERIMENTAL_SM60=ON", made["strata-poly"]) - self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=61", made["strata-poly"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_qimage.py b/tools/test_qimage.py deleted file mode 100644 index fdc81d6..0000000 --- a/tools/test_qimage.py +++ /dev/null @@ -1,202 +0,0 @@ -"""Tests for image generation's setup side (tools/image/qimage.py, setup.py --images): the pins, the quant and backend -choices, the CMake definitions, the source unpacking and the run config's "images" section. No GPU, no network. - - python -m unittest tools.test_qimage -""" -from __future__ import annotations - -import argparse -import contextlib -import io -import json -import re -import sys -import tempfile -import unittest -import zipfile -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -sys.path.insert(0, str(ROOT / "tools" / "image")) -import qimage as QI # noqa: E402 -import setup # noqa: E402 - - -def quiet(fn, *args, **kw): - with contextlib.redirect_stdout(io.StringIO()): - return fn(*args, **kw) - - -class Pins(unittest.TestCase): - def test_shapes(self): - for c in (QI.SD_CPP_COMMIT, QI.SD_GGML_COMMIT, *QI.REVISIONS.values()): - self.assertRegex(c, r"^[0-9a-f]{40}$") - for name, (repo, path, size, sha) in QI.FILES.items(): - self.assertIn(repo, QI.REVISIONS, name) - self.assertRegex(sha, r"^[0-9a-f]{64}$") - self.assertGreater(size, 100 << 20) - self.assertEqual(QI.file_url("Q8_0"), "https://huggingface.co/unsloth/Qwen-Image-2.1-Turbo-GGUF/resolve/" - "5d1f9f759ea877ae556cda88dbec958b62ad3809/qwen-image-2.1-turbo-Q8_0.gguf") - self.assertEqual(QI.local_path(Path("m"), "vae"), - Path("m") / "qwen-image-2.1-turbo" / "qwen_image_2.1_vae_bf16.safetensors") - - def test_sigmas_are_the_models(self): - """serve/images.py's schedule is model_index.json's sample_sigmas plus the terminal 0.""" - from serve import images - sample = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568] - self.assertEqual([float(x) for x in images.TURBO_SIGMAS.split(",")], sample + [0.0]) - - -class Choices(unittest.TestCase): - def test_quant_by_memory(self): - self.assertEqual([QI.pick_quant(g) for g in (4, 8, 8.5, 12, 12.1, 16, 32)], - ["Q4_K_M", "Q4_K_M", "Q6_K", "Q6_K", "Q8_0", "Q8_0", "Q8_0"]) - - def test_backend(self): - self.assertEqual(QI.pick_backend(None, False), "cpu") - self.assertEqual(QI.pick_backend({"vendor": "nvidia"}, True), "cuda") - self.assertEqual(QI.pick_backend({"vendor": "amd"}, False), "hip") - self.assertEqual(QI.pick_backend({"vendor": "amd", "uma": True}, False), "vulkan") # the 780M, Strix Halo - self.assertEqual(QI.pick_backend({"vendor": "amd"}, True), "vulkan") # AMD on Windows - self.assertEqual(QI.pick_backend({"vendor": "intel"}, False), "vulkan") - self.assertEqual(QI.pick_backend({"vendor": "amd", "arch": "gfx1103"}, False), "vulkan") # no uma mark - self.assertEqual(QI.pick_backend({"vendor": "amd", "arch": "gfx1100"}, False), "hip") - self.assertTrue(QI.is_apu({"arch": "gfx1151:xnack-"})) - - def test_default_args(self): - self.assertEqual(QI.default_args("cuda"), ["--diffusion-fa"]) - self.assertEqual(QI.default_args("vulkan"), ["--diffusion-fa", "--vae-tiling", "--vae-tile-overlap", "0.25"]) - - def test_setup_recommends_never_forces(self): - ns = argparse.Namespace(image_backend=None, image_quant=None) - self.assertEqual(quiet(setup.image_backend_choice, ns, {"vram_gb": 12.0, "arch": 86}, False)[:2], - ("cuda", "Q6_K")) - self.assertEqual(quiet(setup.image_backend_choice, ns, {"vram_gb": 32.3, "uma": True, "arch": "gfx1103"}, - True)[:2], ("vulkan", "Q8_0")) - ns.image_quant = "Q8_0" # more than recommended: kept, with a warning - out = io.StringIO() - with contextlib.redirect_stdout(out): - r = setup.image_backend_choice(ns, {"vram_gb": 8.0, "arch": 86}, False) - self.assertEqual(r[:2], ("cuda", "Q8_0")) - self.assertIn("recommends Q4_K_M", out.getvalue()) - ns.image_quant, ns.image_backend = None, "cpu" - self.assertEqual(quiet(setup.image_backend_choice, ns, {"vram_gb": 24.0}, False)[:2], ("cpu", "Q4_K_M")) - - -class Build(unittest.TestCase): - def test_cmake_defs(self): - d = QI.cmake_defs("cuda", arch=86, cuda_root=Path("/usr/local/cuda")) - self.assertIn("-DSD_CUDA=ON", d) - self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=86", d) - self.assertIn("-DSD_WEBP=OFF", d) - self.assertIn("-DSD_VULKAN=ON", QI.cmake_defs("vulkan")) - with tempfile.TemporaryDirectory() as r: - rocm = Path(r) - (rocm / "lib" / "llvm" / "bin").mkdir(parents=True) - d = QI.cmake_defs("hip", arch="gfx1103:sramecc-:xnack-", rocm=rocm) - self.assertIn("-DGPU_TARGETS=gfx1103", d) - self.assertIn(f"-DCMAKE_HIP_COMPILER={rocm / 'lib' / 'llvm' / 'bin' / 'clang++'}", d) - with self.assertRaises(ValueError): - QI.cmake_defs("hip", arch="gfx1103") - with self.assertRaises(ValueError): - QI.cmake_defs("metal") - - def test_unpack_puts_ggml_in_place(self): - with tempfile.TemporaryDirectory() as d: - d = Path(d) - z1, z2 = d / "sd.zip", d / "ggml.zip" - with zipfile.ZipFile(z1, "w") as z: - z.writestr(f"stable-diffusion.cpp-{QI.SD_CPP_COMMIT}/CMakeLists.txt", "project(sd)") - z.writestr(f"stable-diffusion.cpp-{QI.SD_CPP_COMMIT}/ggml/", "") - with zipfile.ZipFile(z2, "w") as z: - z.writestr(f"ggml-{QI.SD_GGML_COMMIT}/CMakeLists.txt", "project(ggml)") - src = QI.unpack_source(d, z1, z2) - self.assertEqual((src / "ggml" / "CMakeLists.txt").read_text(), "project(ggml)") - self.assertTrue(QI.source_ok(src)) - (src / ".strata-pin").write_text("0" * 40 + "\n" + QI.SD_GGML_COMMIT + "\n") - self.assertFalse(QI.source_ok(src)) # another pin: unpacked again - - def test_build_is_skipped_when_the_stamp_matches(self): - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "IMAGE_ENGINE", Path(d)): - (Path(d) / QI.SD_EXE).write_bytes(b"x") - (Path(d) / "BUILD.json").write_text(json.dumps({**QI.build_stamp("cuda", 86), "lib_dirs": [d]})) - with mock.patch.object(setup, "cmake_build") as cb: - exe, libs = quiet(setup.build_image_engine, "cuda", {"arch": 86}) - cb.assert_not_called() - self.assertEqual((exe, libs), (Path(d) / QI.SD_EXE, [d])) - with mock.patch.object(setup, "cmake_build") as cb, mock.patch.object(setup, "get_sd_cpp"), \ - mock.patch.object(setup, "apply_native_runner"), \ - mock.patch.object(setup, "find_nvcc", return_value=(None, None)): - with self.assertRaises(SystemExit): # another arch: compiled again (here: no nvcc, so it stops) - quiet(setup.build_image_engine, "cuda", {"arch": 89}) - - -class Config(unittest.TestCase): - def test_section(self): - c = QI.image_config("vulkan", "Q8_0", Path("/e/sd-cli"), Path("/m"), uma=True, lib_dirs=["/l"]) - self.assertEqual(c["diffusion_model"], str(Path("/m/qwen-image-2.1-turbo/qwen-image-2.1-turbo-Q8_0.gguf"))) - self.assertEqual(c["args"], ["--diffusion-fa", "--vae-tiling", "--vae-tile-overlap", "0.25"]) - self.assertTrue(c["uma"]) - self.assertEqual(c["gpu_policy"], "auto") - from serve.images import ImageGen - with tempfile.TemporaryDirectory() as d: - ImageGen({**c, "out_dir": d}) # serve accepts what setup writes - - def test_images_no_drops_the_section(self): - with tempfile.TemporaryDirectory() as d: - p = Path(d) / "strata-q2_0.json" - p.write_text(json.dumps({"exe": "x", "images": {"exe": "sd-cli"}, "mine": 1})) - quiet(setup.write_setup_config, p, {"exe": "y", "images": None}) - cfg = json.loads(p.read_text()) - self.assertNotIn("images", cfg) - self.assertEqual(cfg["mine"], 1) - p.write_text(json.dumps({"exe": "x", "images": {"exe": "sd-cli"}})) - quiet(setup.write_setup_config, p, {"exe": "y"}) # not asked: carried over - self.assertEqual(json.loads(p.read_text())["images"], {"exe": "sd-cli"}) - - def test_flags(self): - src = (ROOT / "setup.py").read_text(encoding="utf-8") - for flag in ("--images", "--image-quant", "--image-backend", "--image-gpu-policy"): - self.assertRegex(src, re.escape(f'ap.add_argument("{flag}"')) - - -class Native(unittest.TestCase): - """I2: the native DiT runner's patch for the pinned stable-diffusion.cpp, and its config switch.""" - - def test_stamp_and_config(self): - self.assertIn("native", QI.build_stamp("cuda", 86)) - self.assertIn("native", QI.build_stamp("hip", "gfx1103")) - self.assertNotIn("native", QI.build_stamp("vulkan", None)) - c = QI.image_config("hip", "Q8_0", Path("/e/sd-cli"), Path("/m"), native=True) - self.assertIs(c["native"], True) - self.assertNotIn("native", QI.image_config("vulkan", "Q8_0", Path("/e/sd-cli"), Path("/m"))) - - def test_apply_is_idempotent(self): - sys.path.insert(0, str(QI.NATIVE_DIR)) - import apply as A - with tempfile.TemporaryDirectory() as d: - sd = Path(d) - (sd / "ggml" / "src" / "ggml-cuda").mkdir(parents=True) - (sd / "src" / "model" / "diffusion").mkdir(parents=True) - (sd / "src" / "pipeline").mkdir(parents=True) - (sd / "src" / "pipeline" / "model_builders.cpp").write_text( - "#include \n" + A.INCLUDE_OLD + "int a;\n" + A.BUILDER_OLD + " }\n", encoding="utf-8") - (sd / "CMakeLists.txt").write_text("x\n" + A.CMAKE_OLD + "y\n", encoding="utf-8") - A.apply(sd) - first = [(sd / f).read_text(encoding="utf-8") for f in ("src/pipeline/model_builders.cpp", "CMakeLists.txt")] - A.apply(sd) - again = [(sd / f).read_text(encoding="utf-8") for f in ("src/pipeline/model_builders.cpp", "CMakeLists.txt")] - self.assertEqual(first, again) - self.assertIn("QwenImage21NativeRunner", first[0]) - self.assertEqual(first[1].count("SD_QI_NATIVE"), 1) - self.assertTrue((sd / "ggml/src/ggml-cuda/qi21-native.cu").is_file()) - (sd / "CMakeLists.txt").write_text("something else\n", encoding="utf-8") - with self.assertRaises(SystemExit): # another sd.cpp: refused, not half-patched - A.apply(sd) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py deleted file mode 100644 index c9000fd..0000000 --- a/tools/test_setup_amd.py +++ /dev/null @@ -1,578 +0,0 @@ -"""Tests for setup.py's AMD card detection on a mocked KFD topology (/sys/class/kfd + /sys/class/drm): the arch -names from gfx_target_version, the CPU node skipped, HIP numbering, product names, which cards are supported and -which TheRock index each family installs from. No GPU, no ROCm, no downloads. - - python -m unittest tools.test_setup_amd -""" -from __future__ import annotations - -import sys -import tempfile -import unittest -from unittest import mock -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -def fake_sysfs(root: Path, nodes: list) -> None: - """nodes: (gfx_target_version, simd_count, render_minor, product_name or None, vram_bytes)""" - for i, (ver, simd, minor, name, vram) in enumerate(nodes): - n = root / "class/kfd/kfd/topology/nodes" / str(i) - n.mkdir(parents=True) - (n / "properties").write_text(f"cpu_cores_count {0 if simd else 12}\nsimd_count {simd}\n" - f"gfx_target_version {ver}\ndrm_render_minor {minor}\n") - if simd: - d = root / f"class/drm/renderD{minor}/device" - d.mkdir(parents=True) - (d / "mem_info_vram_total").write_text(str(vram)) - if name is not None: - (d / "product_name").write_text(name + "\n") - - -class KfdDetection(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = Path(self.tmp.name) - self.win = setup.WIN - setup.WIN = False - - def tearDown(self): - setup.WIN = self.win - self.tmp.cleanup() - - def test_every_family(self): - fake_sysfs(self.root, [ - (0, 0, 0, None, 0), # the CPU node: skipped - (110001, 120, 128, "", 16 << 30), # gfx1101 without a product name - (120000, 64, 129, None, 16 << 30), # gfx1200, no product_name file - (120001, 128, 130, "AMD Radeon AI PRO R9700", 32 << 30), - (110002, 64, 131, None, 8 << 30), # gfx1102: supported, unvalidated (#938) - (100306, 4, 132, None, 512 << 20), # an integrated gfx1036: listed, not supported - (110000, 192, 133, "Radeon RX 7900 XTX", 24 << 30), - ]) - g = setup.amd_gpus(str(self.root)) - self.assertEqual([x["arch"] for x in g], ["gfx1101", "gfx1200", "gfx1201", "gfx1102", "gfx1036", "gfx1100"]) - self.assertEqual([x["index"] for x in g], [0, 1, 2, 3, 4, 5]) # HIP numbers: GPU nodes only - self.assertEqual(g[0]["name"], setup.AMD_NAMES["gfx1101"]) - self.assertEqual(g[1]["name"], setup.AMD_NAMES["gfx1200"]) - self.assertEqual(g[2]["name"], "AMD Radeon AI PRO R9700") - self.assertEqual(g[3]["name"], setup.AMD_NAMES["gfx1102"]) - self.assertAlmostEqual(g[2]["vram_gb"], 32.0) - ok = [x["arch"] for x in g if setup.amd_problem(x) is None] - self.assertEqual(ok, ["gfx1101", "gfx1200", "gfx1201", "gfx1102", "gfx1100"]) - self.assertIn("gfx1036", setup.amd_problem(g[4])) - - def test_no_kfd(self): - self.assertEqual(setup.amd_gpus(str(self.root)), []) - - def test_rocm_index_per_family(self): - for arch in setup.AMD_ARCHS: - self.assertIn(arch, setup.ROCM_INDEXES) - self.assertTrue(setup.ROCM_INDEXES["gfx1101"].endswith("/gfx110X-dgpu/")) - self.assertTrue(setup.ROCM_INDEXES["gfx1200"].endswith("/gfx120X-all/")) - self.assertEqual(setup.ROCM_INDEXES["gfx1101"], setup.ROCM_INDEXES["gfx1100"]) - self.assertEqual(setup.ROCM_INDEXES["gfx1200"], setup.ROCM_INDEXES["gfx1201"]) - # #524: the RX 6700 XT (gfx1031) takes the RDNA2 wheels, as the RX 6800 / 6900 (gfx1030) - self.assertEqual(setup.ROCM_INDEXES["gfx1031"], setup.ROCM_INDEXES["gfx1030"]) - self.assertIsNone(setup.amd_problem({"arch": "gfx1031"})) - - -class GpuLists(unittest.TestCase): - """--gpus with AMD cards: every chosen card must be supported; the first is the main one.""" - AMD = [{"index": 0, "name": "AMD Radeon RX 9070 XT", "vram_gb": 16.0, "arch": "gfx1201"}, - {"index": 1, "name": "AMD Radeon AI PRO R9700", "vram_gb": 32.0, "arch": "gfx1201"}, - {"index": 2, "name": "AMD Radeon (gfx1036)", "vram_gb": 0.5, "arch": "gfx1036"}, - {"index": 3, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 24.0, "arch": "gfx1100"}] - - def setUp(self): - self.say = setup.say - setup.say = lambda *a, **k: None - - def tearDown(self): - setup.say = self.say - - def test_list_in_order(self): - self.assertEqual([g["index"] for g in setup.amd_parse_gpus("1,0", self.AMD)], [1, 0]) - self.assertEqual([g["index"] for g in setup.amd_parse_gpus(" 0, 3 ", self.AMD)], [0, 3]) - - def test_all_is_every_supported_card_most_vram_first(self): - self.assertEqual([g["index"] for g in setup.amd_parse_gpus("all", self.AMD)], [1, 3, 0]) - - def test_refusals(self): - for text in ("1,2", "1,7", "1", "1,1", "x,y"): - with self.assertRaises(SystemExit, msg=text): - setup.amd_parse_gpus(text, self.AMD) - - def test_wheels_hold_one_family(self): - with tempfile.TemporaryDirectory() as d: # no system ROCm there: the wheels would be needed - old = setup.os.environ.get("ROCM_PATH") - setup.os.environ["ROCM_PATH"] = d - try: - with self.assertRaises(SystemExit): - setup.rocm_root(["gfx1100", "gfx1201"]) - finally: - if old is None: - del setup.os.environ["ROCM_PATH"] - else: - setup.os.environ["ROCM_PATH"] = old - - def test_runtime_only_system_rocm_falls_back_to_the_wheels(self): - """#446: a system ROCm 7 with hipcc and libhipblas but no HIP development files (no hip-lang CMake package, no - hip_runtime.h) is not used for the build: a warning says what is missing and the wheels path follows (here - it stops at the two-family check, which only the wheels path makes); with the files it is used as before.""" - said = [] - setup.say = lambda msg="": said.append(msg) # tearDown puts the real one back - with tempfile.TemporaryDirectory() as d: - sysroot = Path(d) - for rel, text in (("bin/hipcc", ""), ("lib/libhipblas.so.3", ""), - ("include/rocm-core/rocm_version.h", - "#define ROCM_VERSION_MAJOR 7\n#define ROCM_VERSION_MINOR 14\n")): - (sysroot / rel).parent.mkdir(parents=True, exist_ok=True) - (sysroot / rel).write_text(text) - with mock.patch.dict(setup.os.environ, {"ROCM_PATH": d}): - with self.assertRaises(SystemExit): - setup.rocm_root(["gfx1100", "gfx1201"]) - self.assertIn(f"the ROCm in {sysroot} has no HIP development files (lib/cmake/hip-lang/hip-lang-" - "config.cmake, include/hip/hip_runtime.h): using AMD's wheels", "\n".join(said)) - self.assertIn("two GPU families", "\n".join(said)) - for lib in ("lib64", "lib"): # either place CMake looks - with self.subTest(lib=lib): - cfg = sysroot / lib / "cmake/hip-lang/hip-lang-config.cmake" - cfg.parent.mkdir(parents=True, exist_ok=True) - cfg.write_text("") - said.clear() - with self.assertRaises(SystemExit): - setup.rocm_root(["gfx1100", "gfx1201"]) - self.assertIn("(include/hip/hip_runtime.h)", "\n".join(said)) - (sysroot / "include/hip").mkdir(parents=True, exist_ok=True) - (sysroot / "include/hip/hip_runtime.h").write_text("") - self.assertEqual(setup.rocm_root(["gfx1100", "gfx1201"]), (sysroot, [str(sysroot / "lib")])) - cfg.unlink() - (sysroot / "include/hip/hip_runtime.h").unlink() - - def test_build_for_every_arch(self): - """build_engine_hip compiles for the set of the chosen cards' archs and records it in BUILD.json.""" - calls = {} - saved = {k: getattr(setup, k) for k in ("ROOT", "rocm_root", "cmake_build", "source_hash", "source_version", - "ok", "shutil")} - with tempfile.TemporaryDirectory() as d: - root = Path(d) - - def fake_build(src, bdir, target, defs, vcvars, bat): - calls["defs"] = defs - (bdir).mkdir(parents=True, exist_ok=True) - (bdir / setup.EXE).write_text("engine") - - class Sh: - which = staticmethod(lambda name: "/usr/bin/" + name) - copy2 = staticmethod(lambda a, b: Path(b).write_text(Path(a).read_text())) - setup.ROOT, setup.cmake_build, setup.ok, setup.shutil = root, fake_build, lambda *a: None, Sh - setup.source_hash, setup.source_version = (lambda *a: "h"), (lambda: "0.1.31") - setup.rocm_root = lambda archs: (calls.setdefault("archs", archs) and root, [str(root / "lib")]) - try: - setup.build_engine_hip({"arch": "gfx1201", "archs": ["gfx1201", "gfx1100", "gfx1201"]}, root) - self.assertEqual(calls["archs"], ["gfx1100", "gfx1201"]) - self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1100;gfx1201", calls["defs"]) - import json - self.assertEqual(json.loads((root / "engine" / "BUILD.json").read_text())["archs"], - ["gfx1100", "gfx1201"]) - calls.clear() # one of those cards alone: already built, no compile - setup.build_engine_hip({"arch": "gfx1100"}, root) - self.assertNotIn("defs", calls) - setup.build_engine_hip({"arch": "gfx1101"}, root) # another arch: compiled again - self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1101", calls["defs"]) - finally: - for k, v in saved.items(): - setattr(setup, k, v) - - -class WindowsDetection(unittest.TestCase): - """Windows: the AMD cards from the display adapters (mocked Win32_VideoController rows and display-class registry - values), the HIP runtime's numbering from `strata-device --list-devices`, and the card setup chose matched to its - HIP ordinal (#325: an integrated Radeon is HIP's device 0).""" - ADAPTERS = [ # Win32_VideoController: name, PNPDeviceID, AdapterRAM (32-bit: at most 4 GB) - {"name": "NVIDIA GeForce RTX 5070", "pnp": r"PCI\VEN_10DE&DEV_2F04&SUBSYS_1234&REV_A1\4&1", "ram": 4293918720}, - {"name": "AMD Radeon RX 9070 XT", "pnp": r"PCI\VEN_1002&DEV_7550&SUBSYS_0E3B1002&REV_C0\6&2", "ram": 4293918720}, - {"name": "AMD Radeon(TM) Graphics", "pnp": r"PCI\VEN_1002&DEV_164E&SUBSYS_88771043&REV_C1\4&3", "ram": 536870912}, - {"name": "AMD Radeon RX 7800 XT", "pnp": r"PCI\VEN_1002&DEV_7499&SUBSYS_0000&REV_C8\6&4", "ram": 4293918720}, - ] - REGISTRY = [ # the display class's driver instances: 64-bit VRAM size (as int, or as bytes) - {"DriverDesc": "NVIDIA GeForce RTX 5070", "MatchingDeviceId": r"PCI\VEN_10DE&DEV_2F04", - "HardwareInformation.qwMemorySize": 12 << 30}, - {"DriverDesc": "AMD Radeon RX 6600", "MatchingDeviceId": r"PCI\VEN_1002&DEV_73FF", # a removed card - "HardwareInformation.qwMemorySize": 8 << 30}, - {"DriverDesc": "AMD Radeon RX 9070 XT", "MatchingDeviceId": r"PCI\VEN_1002&DEV_7550&REV_C0", - "HardwareInformation.qwMemorySize": (16 << 30).to_bytes(8, "little"), "DriverVersion": "32.0.21013.1000"}, - {"DriverDesc": "AMD Radeon(TM) Graphics", "MatchingDeviceId": r"PCI\VEN_1002&DEV_164E&REV_C1", - "HardwareInformation.qwMemorySize": 512 << 20}, - {"DriverDesc": "AMD Radeon RX 7800 XT", "MatchingDeviceId": r"PCI\VEN_1002&DEV_7499", - "HardwareInformation.qwMemorySize": 16 << 30}, - ] - LIST = ("device 0: AMD Radeon(TM) Graphics\n arch gfx1036, 28.1 GiB, wave32\n" - " cannot run: GPU 0 (AMD Radeon(TM) Graphics, gfx1036) is not an architecture this PolyStrata engine was " - "compiled for (gfx1100,gfx1101,gfx1102,gfx1200,gfx1201,gfx1030); ...\n" - "device 1: AMD Radeon RX 9070 XT\n arch gfx1201, 15.9 GiB, wave32\n" - "device 2: AMD Radeon RX 7800 XT\n arch gfx1101, 16.0 GiB, wave32\n") - - def test_adapters(self): - g = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) - self.assertEqual([x["name"] for x in g], ["AMD Radeon RX 9070 XT", "AMD Radeon(TM) Graphics", - "AMD Radeon RX 7800 XT"]) # AMD only, present only, in order - self.assertEqual([x["index"] for x in g], [0, 1, 2]) - self.assertEqual(g[0]["arch"], "gfx1201") # by PCI device id - self.assertEqual(g[2]["arch"], "gfx1101") # an unlisted id: by its name - self.assertTrue(g[1]["arch"].startswith("unknown")) # the iGPU: listed, not supported - self.assertAlmostEqual(g[0]["vram_gb"], 16.0) # the registry's 64-bit size - self.assertEqual(g[0]["driver"], "32.0.21013.1000") - self.assertEqual([setup.amd_problem(x) is None for x in g], [True, False, True]) - - def test_rx_6800m_is_gfx1031(self): - """#881: PCI 73DF (RX 6700 XT / 6750 XT / 6800M) is gfx1031, not an unknown id.""" - self.assertEqual(setup.win_amd_arch(0x73DF, "AMD Radeon RX 6800M"), "gfx1031") - self.assertIsNone(setup.amd_problem({"arch": "gfx1031"})) - - def test_cpu_vision_build_uses_the_visual_studio_environment(self): - """#881: build_vision_cpu on Windows hands cmake_build the vcvars file and a real .bat name (it passed None and - an empty name before).""" - calls = [] - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "WIN", True), mock.patch.object(setup, "find_vcvars", return_value=Path("C:/vs/vcvars64.bat")), mock.patch.object(setup, "cmake_build", lambda *a: calls.append(a)), mock.patch.object(setup, "ROOT", Path(d)), mock.patch.object(setup.shutil, "copy2"): - eng = Path(d) / "engine" - eng.mkdir() - setup.build_vision_cpu(eng, eng / "BUILD.json", {}, Path("llama"), "src1") - self.assertEqual(calls[0][4], Path("C:/vs/vcvars64.bat")) - self.assertTrue(calls[0][5].endswith(".bat")) - - def test_registry_alone(self): - """No WMI answer: the registry's own list (which can hold a removed card).""" - g = setup.amd_gpus_windows([], self.REGISTRY) - self.assertEqual([x["arch"] for x in g if not x["arch"].startswith("unknown")], ["gfx1201", "gfx1101"]) - - def test_arch_names(self): - for name, arch in (("AMD Radeon RX 9070 GRE", "gfx1201"), ("AMD Radeon AI PRO R9700", "gfx1201"), - ("AMD Radeon RX 9060 XT", "gfx1200"), ("AMD Radeon RX 7900 GRE", "gfx1100"), - ("AMD Radeon PRO W7800", "gfx1100"), ("AMD Radeon RX 7700 XT", "gfx1101"), - ("AMD Radeon RX 7600", "gfx1102"), ("AMD Radeon RX 6950 XT", "gfx1030"), - ("AMD Radeon RX 6800M", ""), ("AMD Radeon 780M Graphics", "gfx1103"), ("AMD Radeon RX 7700S", "")): - self.assertEqual(setup.win_amd_arch(None, name), arch, name) - self.assertEqual(setup.win_amd_arch(0x744C, "whatever"), "gfx1100") - - def test_list_devices(self): - h = setup.hip_devices(text=self.LIST) - self.assertEqual([(x["index"], x["arch"]) for x in h], [(0, "gfx1036"), (1, "gfx1201"), (2, "gfx1101")]) - self.assertAlmostEqual(h[1]["vram_gb"], 15.9) - self.assertIn("not an architecture", h[0]["cannot_run"]) - self.assertIsNotNone(setup.amd_problem(h[0])) - self.assertIsNone(setup.amd_problem(h[1])) - cannot = setup.hip_devices(text="device 0: AMD Radeon RX 9070 XT\n arch gfx1201, 15.9 GiB, wave32\n" - " cannot run: GPU 0 runs wave64\n") - self.assertEqual(setup.amd_problem(cannot[0]), "GPU 0 runs wave64") # the engine's own check counts - self.assertEqual(setup.hip_devices(text="(no GPU device)\n"), []) - - def test_the_card_by_its_hip_ordinal(self): - """#325: setup's GPU 0 (the 9070 XT, display order) is HIP's device 1 behind the iGPU.""" - listed = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) - hip = setup.hip_devices(text=self.LIST) - self.assertEqual(setup.hip_match(listed[0], listed, hip)["index"], 1) - self.assertEqual(setup.hip_match(listed[2], listed, hip)["index"], 2) - two = [{"index": 0, "arch": "gfx1201"}, {"index": 1, "arch": "gfx1201"}] # two of a kind: by rank - self.assertEqual(setup.hip_match(two[1], two, [{"index": 0, "arch": "gfx1036"}, {"index": 1, "arch": "gfx1201"}, - {"index": 2, "arch": "gfx1201"}])["index"], 2) - self.assertIsNone(setup.hip_match({"index": 0, "arch": "gfx1100"}, [{"index": 0, "arch": "gfx1100"}], hip)) - - def test_hip_card(self): - listed = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) - with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: setup_hip(self.LIST)), \ - mock.patch.object(setup, "ok", lambda *a: None): - g = setup.hip_card(Path("engine"), listed[0], listed) - self.assertEqual((g["index"], g["count"], g["arch"], g["vram_gb"]), (1, 3, "gfx1201", 15.9)) - with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: []), \ - mock.patch.object(setup, "say", lambda *a, **k: None), self.assertRaises(SystemExit): - setup.hip_card(Path("engine"), listed[0], listed) # no AMD driver: stops before the download - with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: setup_hip(self.LIST)[:1]), \ - mock.patch.object(setup, "say", lambda *a, **k: None), self.assertRaises(SystemExit): - setup.hip_card(Path("engine"), listed[0], listed) # HIP does not list the card - - def test_windows_dispatch(self): - """amd_gpus() on Windows: HIP's numbering once the HIP engine answers, the display adapters before.""" - with mock.patch.object(setup, "WIN", True), \ - mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: None), \ - mock.patch.object(setup, "amd_gpus_windows", lambda adapters=None, registry=None: ["display"]): - self.assertEqual(setup.amd_gpus(), ["display"]) - with mock.patch.object(setup, "WIN", True), \ - mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: ["hip"]), \ - mock.patch.object(setup, "amd_gpus_windows", lambda adapters=None, registry=None: ["display"]): - self.assertEqual(setup.amd_gpus(), ["hip"]) - - def test_no_hip_engine_no_probe(self): - with tempfile.TemporaryDirectory() as d: - eng = Path(d) - (eng / "strata-device.exe").write_text("x") - (eng / "BUILD.json").write_text('{"backend": "cuda"}') # an NVIDIA engine is never asked - self.assertIsNone(setup.hip_devices(eng / "strata-device.exe")) - - def test_prebuilt_hip_zip(self): - """get_prebuilt_hip: a published zip (here a local folder) is unpacked into engine/; one without code for the - card, or older than the first Windows HIP release, is refused.""" - import json - import zipfile - with tempfile.TemporaryDirectory() as d: - root = Path(d) - pub = root / "pub" - pub.mkdir() - - def publish(meta): - with zipfile.ZipFile(pub / setup.WIN_HIP_ASSET, "w") as z: - z.writestr(setup.EXE, "engine") # #975: "strata" on Linux - z.writestr("strata-device.exe", "probe") - z.writestr("rocm/bin/amdhip64_7.dll", "dll") - z.writestr("BUILD.json", json.dumps(meta)) - ver = ".".join(map(str, setup.WIN_HIP_MIN_ENGINE)) - good = {"source": "prebuilt", "backend": "hip", "version": ver, "archs": ["gfx1100", "gfx1201"], - "lib_dirs": ["rocm/bin"]} - with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "say", lambda *a, **k: None), \ - mock.patch.object(setup, "ok", lambda *a: None), mock.patch.object(setup, "warn", lambda *a: None): - publish({**good, "archs": ["gfx1100"]}) - self.assertIsNone(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"})) - publish({**good, "version": "0.1.30"}) - self.assertIsNone(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"})) - publish(good) - eng = setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}) - self.assertEqual(eng, root / "engine") - self.assertTrue((eng / "rocm" / "bin" / "amdhip64_7.dll").exists()) - self.assertEqual(setup.hip_lib_dirs(eng), [eng / "rocm" / "bin"]) - (pub / setup.WIN_HIP_ASSET).unlink() # installed: kept, nothing downloaded again - self.assertEqual(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}), eng) - - -_HIP_DEVICES = setup.hip_devices # the real parser, for the tests that mock setup.hip_devices - - -def setup_hip(text): - return _HIP_DEVICES(text=text) - - -class CalibrationKey(unittest.TestCase): - """#566: a calibration is saved and found again per PC and model (hardware_key). A HIP config's cards are AMD's, - in HIP's numbering - nvidia-smi named them "?" (or another card with that number) before - and setup reuses a - saved calibration on Linux HIP. The NVIDIA key and the settings file's format are unchanged.""" - AMD = [{"index": 0, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 23.98, "arch": "gfx1100"}, - {"index": 1, "name": "AMD Radeon RX 7900 XT", "vram_gb": 19.98, "arch": "gfx1100"}, - {"index": 2, "name": "AMD Radeon (gfx1201)", "vram_gb": 15.92, "arch": "gfx1201"}, - {"index": 3, "name": "AMD Radeon (gfx1036)", "vram_gb": 0.5, "arch": "gfx1036"}] - - def setUp(self): - self.patches = [mock.patch.object(setup, "amd_gpus", lambda *a, **k: [dict(g) for g in self.AMD]), - mock.patch.object(setup, "cpu_info", lambda: ("AMD Ryzen 9 7950X", 16)), - mock.patch.object(setup, "ram_gb", lambda: 63.6)] - for p in self.patches: - p.start() - - def tearDown(self): - for p in self.patches: - p.stop() - - @staticmethod - def cfg(gpu, backend="hip", ctx="32768"): - c = {"model_name": "qwen3.8-flash-next-iq3_xxs", "args": ["--max-context", ctx, "--kv", "int8"], "gpu": gpu} - if backend: - c["backend"] = backend - return c - - def test_hip_key_names_the_amd_card_and_its_arch(self): - def no_nvidia(*a, **k): # a HIP config never asks nvidia-smi (a PC with both kinds) - raise AssertionError("gpu_info called for a HIP config") - with mock.patch.object(setup, "gpu_info", no_nvidia): - self.assertEqual(setup.hardware_key(self.cfg(0)), - "AMD Radeon RX 7900 XTX (gfx1100)|24GB|AMD Ryzen 9 7950X|64GB|qwen3.8-flash-next-iq3_xxs|" - "32768|text") - # the arch is not repeated when the name already holds it (no product name in sysfs) - self.assertTrue(setup.hardware_key(self.cfg(2)).startswith("AMD Radeon (gfx1201)|16GB|")) - - def test_two_cards_of_one_arch_are_two_keys(self): - keys = {setup.hardware_key(self.cfg(i)) for i in (0, 1, 2)} - self.assertEqual(len(keys), 3) - - def test_a_split_names_every_card(self): - self.assertTrue(setup.hardware_key(self.cfg([1, 0])).startswith( - "AMD Radeon RX 7900 XT (gfx1100) + AMD Radeon RX 7900 XTX (gfx1100)|44GB|")) - - def test_no_gpu_in_the_config_is_the_supported_card_with_the_most_vram(self): - self.assertTrue(setup.hardware_key(self.cfg(None)).startswith("AMD Radeon RX 7900 XTX (gfx1100)|24GB|")) - - def test_a_card_that_is_gone_is_unknown(self): - self.assertTrue(setup.hardware_key(self.cfg(7)).startswith("?|0GB|")) - - def test_nvidia_key_unchanged(self): - def amd(*a, **k): - raise AssertionError("amd_gpus called for an NVIDIA config") - with mock.patch.object(setup, "amd_gpus", amd), \ - mock.patch.object(setup, "gpu_info", lambda i=None: {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}): - self.assertEqual(setup.hardware_key(self.cfg(0, backend=None)), - "NVIDIA GeForce RTX 5070|12GB|AMD Ryzen 9 7950X|64GB|qwen3.8-flash-next-iq3_xxs|32768|text") - self.assertEqual(setup.hardware_key(self.cfg([0, 1], backend="cuda")), - "NVIDIA GeForce RTX 5070 + NVIDIA GeForce RTX 5070|24GB|AMD Ryzen 9 7950X|64GB|" - "qwen3.8-flash-next-iq3_xxs|32768|text") - - def test_setup_reuses_a_saved_calibration_on_linux_hip(self): - cfg = self.cfg(1) - saved = {"settings": {"pcie_frac": 0.0}, "tok_s": 40.1, "date": "2026-10-03"} - other = {"settings": {"pcie_frac": 0.5}, "tok_s": 50.0, "date": "2026-10-02"} - store = {"calibration": {setup.hardware_key(cfg): saved, setup.hardware_key(self.cfg(0)): other}} - with mock.patch.object(setup, "load_settings", lambda: store): - with mock.patch.object(setup, "WIN", False): - self.assertEqual(setup.setup_calibration(cfg, hip=True), saved) # its own card's, not the XTX's - self.assertIsNone(setup.setup_calibration(self.cfg(2), hip=True)) # never tuned on that card - with mock.patch.object(setup, "WIN", True): - self.assertIsNone(setup.setup_calibration(cfg, hip=True)) # Windows HIP: defaults for now - - -class WindowsHipVision(unittest.TestCase): - def test_no_cpu_encoder_on_windows(self): - with mock.patch.object(setup, "WIN", True), mock.patch.object(setup, "warn", lambda *a: None): - self.assertEqual(setup.hip_vision("cpu"), "none") - self.assertEqual(setup.hip_vision("yes"), "none") - with mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "warn", lambda *a: None): - self.assertEqual(setup.hip_vision("cpu"), "cpu") - - -class HipRuntimeBesideExe(unittest.TestCase): - """#468 #461: the bundled HIP runtime (and amd_comgr) goes next to strata.exe, so an AMD driver's System32 copy is - not found first; rocBLAS and the rest stay in rocm/bin.""" - - def test_copies_only_the_runtime(self): - import json - with tempfile.TemporaryDirectory() as d: - eng = Path(d) - rb = eng / "rocm" / "bin" - rb.mkdir(parents=True) - (eng / "BUILD.json").write_text(json.dumps({"backend": "hip", "lib_dirs": ["rocm/bin"]})) - for n, data in (("amdhip64_7.dll", b"hip-3686"), ("amd_comgr.dll", b"comgr"), ("rocblas.dll", b"blas")): - (rb / n).write_bytes(data) - setup.hip_runtime_beside_exe(eng) - self.assertEqual((eng / "amdhip64_7.dll").read_bytes(), b"hip-3686") - self.assertEqual((eng / "amd_comgr.dll").read_bytes(), b"comgr") - self.assertFalse((eng / "rocblas.dll").exists()) # finds its kernels relative to rocm/bin - (rb / "amdhip64_7.dll").write_bytes(b"hip-3690-newer") # a newer zip: replaced on the next start - setup.hip_runtime_beside_exe(eng) - self.assertEqual((eng / "amdhip64_7.dll").read_bytes(), b"hip-3690-newer") - - def test_no_rocm_bin_is_a_no_op(self): - with tempfile.TemporaryDirectory() as d: - setup.hip_runtime_beside_exe(Path(d)) # no BUILD.json (a CUDA or Linux engine) - self.assertEqual(list(Path(d).iterdir()), []) - - -class DeviceAccess(unittest.TestCase): - """Linux AMD: /dev/kfd and the render nodes must be openable by the user; setup warns, never refuses.""" - - def dev(self, d, kfd=True, nodes=("renderD128",)): - root = Path(d) - (root / "dri").mkdir() - if kfd: - (root / "kfd").write_text("") - for n in nodes: - (root / "dri" / n).write_text("") - return str(root) - - def test_accessible_is_silent(self): - with tempfile.TemporaryDirectory() as d: - self.assertIsNone(setup.amd_device_access_problem(self.dev(d), access=lambda p, m: True)) - - def test_no_kfd_is_not_this_problem(self): - with tempfile.TemporaryDirectory() as d: - self.assertIsNone(setup.amd_device_access_problem(self.dev(d, kfd=False), access=lambda p, m: False)) - - def test_kfd_denied_names_the_fix(self): - with tempfile.TemporaryDirectory() as d: - msg = setup.amd_device_access_problem(self.dev(d), access=lambda p, m: not p.endswith("kfd")) - self.assertIn("kfd", msg) - self.assertNotIn("renderD128", msg) - self.assertIn("sudo usermod -aG render,video $USER", msg) - self.assertIn("log out and in", msg) - - def test_render_node_denied(self): - with tempfile.TemporaryDirectory() as d: - msg = setup.amd_device_access_problem(self.dev(d), access=lambda p, m: "renderD" not in p) - self.assertIn("renderD128", msg) - self.assertNotIn("/kfd", msg) - - def test_engine_names_the_permission_not_another_program(self): - src = (Path(setup.__file__).resolve().parent / "src/program/generate.cpp").read_text(encoding="utf-8") - i = src.index("cannot open /dev/kfd") - guard = src[src.rindex("#if", 0, i):i] - self.assertIn("cudaGetDeviceCount", guard) - self.assertIn('access("/dev/kfd", R_OK | W_OK)', guard) - self.assertIn("STRATA_USE_HIP", guard) # CUDA builds keep the "another program" text - self.assertIn("another program (or an engine that is still exiting)", src) - - -class EngineLaunchEnv(unittest.TestCase): - """#2372: every engine program setup runs gets the ready-made HIP engine's rocm/bin on PATH, or Windows shows a - "hipblas.dll not found" dialog per DLL and `strata --families` prints nothing (setup then said the engine does - not run Qwen3.6).""" - - def engine(self, tmp: Path) -> Path: - eng = tmp / "engine" - (eng / "rocm" / "bin").mkdir(parents=True) - (eng / "BUILD.json").write_text('{"backend": "hip", "lib_dirs": ["rocm/bin"]}', encoding="utf-8") - return eng - - def test_engine_env_puts_rocm_bin_first(self): - with tempfile.TemporaryDirectory() as t: - eng = self.engine(Path(t)) - with mock.patch.dict("os.environ", {"PATH": "C:\\Windows"}): - env = setup.engine_env(eng) - self.assertEqual(env["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) - self.assertTrue(env["PATH"].endswith("C:\\Windows")) - - def test_engine_without_lib_dirs_keeps_the_environment(self): - with tempfile.TemporaryDirectory() as t: - with mock.patch.dict("os.environ", {"PATH": "/usr/bin"}): - self.assertEqual(setup.engine_env(Path(t))["PATH"], "/usr/bin") - - def test_families_probe_runs_with_that_env(self): - seen = {} - - def fake_run(cmd, **kw): - seen["cmd"], seen["env"] = cmd, kw.get("env") - return mock.Mock(stdout="qwen4exp qwen35moe\n") - with tempfile.TemporaryDirectory() as t: - eng = self.engine(Path(t)) - with mock.patch.object(setup.subprocess, "run", fake_run): - names = setup.engine_families(eng) - self.assertEqual(names, {"qwen4exp", "qwen35moe"}) - self.assertEqual(seen["cmd"][1], "--families") - self.assertEqual(seen["env"]["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) - - def test_device_probe_runs_with_that_env(self): - seen = {} - - def fake_run(cmd, **kw): - seen["env"] = kw.get("env") - return mock.Mock(returncode=0, stdout="device 0: AMD Radeon RX 7900 XT\n arch gfx1100, 20.0 GiB, wave32\n") - with tempfile.TemporaryDirectory() as t: - eng = self.engine(Path(t)) - probe = eng / ("strata-device.exe" if setup.WIN else "strata-device") - probe.write_text("x") - with mock.patch.object(setup.subprocess, "run", fake_run), mock.patch.object(setup, "hip_runtime_beside_exe", lambda d: None): - found = setup.hip_devices(probe) - self.assertEqual(found[0]["arch"], "gfx1100") - self.assertEqual(seen["env"]["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) - - -class TdrPointer(unittest.TestCase): - def test_setup_points_windows_gfx12_to_the_entry(self): - src = Path(setup.__file__).read_text(encoding="utf-8") - self.assertIn('WIN and str(gpu.get("arch") or "").startswith("gfx12")', src) - doc = (Path(setup.__file__).resolve().parent / "docs/TROUBLESHOOTING.md").read_text(encoding="utf-8") - self.assertIn("Windows AMD: the driver resets", doc) - for env in ("STRATA_PF_STEP_SYNC", "STRATA_KV_HOST_DMA"): - self.assertIn(env, doc) - self.assertIn(env, (Path(setup.__file__).resolve().parent / "src/prefill/prefill.cpp").read_text(encoding="utf-8")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_bench_tips.py b/tools/test_setup_bench_tips.py deleted file mode 100644 index 141f377..0000000 --- a/tools/test_setup_bench_tips.py +++ /dev/null @@ -1,99 +0,0 @@ -"""Setup's recommendations from the community bench data (0.1.40): text only, never a changed default. - - python -m unittest tools.test_setup_bench_tips -""" -from __future__ import annotations - -import sys -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 -from test_setup_hybrid import fake_sys # noqa: E402 - -BASE = ["--expert-cache", "auto", "--prefill", "auto", "--max-context", "65536"] - - -def tips(args=BASE, env=None, ram=32.0, model=20.0, vram=12.0, vision="none", win=False): - return setup.bench_tips(list(args), env, ram, model, vram, vision, win) - - -class BenchTips(unittest.TestCase): - def test_nothing_to_say_on_a_plain_pc(self): - self.assertEqual(tips(), []) - - def test_explicit_cache_warns_on_windows_only(self): - a = ["--expert-cache", "2400", "--prefill", "auto"] - self.assertTrue(any("--expert-cache 2400" in t and "7x" in t for t in tips(a, win=True))) - self.assertEqual(tips(a, win=False), []) - self.assertEqual(tips(BASE, win=True), []) # auto: nothing to warn about - - def test_prefill_auto_32768_follows_the_ram(self): - self.assertTrue(any("auto:32768" in t and t.startswith("tip") for t in tips(ram=128))) - self.assertEqual([t for t in tips(ram=64) if "auto:32768" in t], []) - big = ["--prefill", "auto:32768"] - self.assertTrue(any(t.startswith("warning") and "auto:32768" in t for t in tips(big, ram=32))) - self.assertEqual([t for t in tips(big, ram=96) if "auto:32768" in t], []) - - def test_resident_headroom_on_small_ram(self): - res = [*BASE, "--resident-experts"] - self.assertTrue(any("STRATA_RESIDENT_HEADROOM_GIB" in t for t in tips(res, ram=32))) - self.assertTrue(any("STRATA_RESIDENT_HEADROOM_GIB" in t for t in tips([*BASE, "--resident-budget-gib", "40"], ram=48))) - self.assertEqual([t for t in tips(res, ram=64) if "HEADROOM" in t], []) - self.assertEqual([t for t in tips(res, {"STRATA_RESIDENT_HEADROOM_GIB": "8"}, ram=32) if "HEADROOM" in t], []) - self.assertEqual([t for t in tips(BASE, ram=32) if "HEADROOM" in t], []) # not a resident config - - def test_conversation_cache_for_agents(self): - self.assertTrue(any("--conversation-cache-mib 8192" in t for t in tips(ram=64, model=40))) - self.assertEqual([t for t in tips(ram=64, model=41) if "conversation" in t], []) # < 24 GB left - self.assertEqual([t for t in tips([*BASE, "--conversation-cache-mib", "4096"], ram=128) if "conversation" in t], []) - - def test_vision_cpu_on_small_cards(self): - self.assertTrue(any("--vision cpu" in t for t in tips(vision="gpu", vram=12))) - self.assertEqual([t for t in tips(vision="gpu", vram=24) if "vision" in t], []) - self.assertEqual([t for t in tips(vision="cpu", vram=12) if "vision" in t], []) - - def test_tips_never_touch_the_arguments(self): - a = ["--expert-cache", "2400", "--prefill", "auto", "--resident-experts"] - before = list(a) - env = {} - tips(a, env, ram=128, vision="gpu", win=True) - self.assertEqual(a, before) - self.assertEqual(env, {}) - - -class Sockets(unittest.TestCase): - def fake(self, d, sockets, cores): - n = 0 - for s in range(sockets): - for c in range(cores): - t = Path(d) / "devices" / "system" / "cpu" / f"cpu{n}" / "topology" - t.mkdir(parents=True) - (t / "physical_package_id").write_text(str(s)) - (t / "core_id").write_text(str(c)) - n += 1 - - def test_linux_sockets(self): - with tempfile.TemporaryDirectory() as d: - self.fake(d, 2, 18) - self.assertEqual(setup.linux_sockets(d), (2, 18)) - with tempfile.TemporaryDirectory() as d: - self.fake(d, 1, 8) - self.assertEqual(setup.linux_sockets(d), (1, 8)) - with tempfile.TemporaryDirectory() as d: - self.assertIsNone(setup.linux_sockets(d)) - - def test_two_socket_tip(self): - t = setup.two_socket_note((2, 18)) - self.assertEqual(len(t), 1) - self.assertIn("--pool-workers 17", t[0]) - self.assertEqual(setup.two_socket_note((1, 18)), []) - self.assertEqual(setup.two_socket_note(None), []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_choices.py b/tools/test_setup_choices.py deleted file mode 100644 index b4d20ee..0000000 --- a/tools/test_setup_choices.py +++ /dev/null @@ -1,663 +0,0 @@ -"""Tests for setup.py's choices that depend on the PC (no GPU, no network, nothing installed): the image encoder of a -ready-made engine that has no code for the card (#331), --gguf-dir's shard count (#305), the experimental -Pascal/Volta build (#295), the CPU image encoder with the AMD backend (#304). - - python -m unittest tools.test_setup_choices -""" -from __future__ import annotations - -import contextlib -import io -import json -import os -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - - -def quiet(fn, *args, **kw): - out = io.StringIO() - with contextlib.redirect_stdout(out): - return fn(*args, **kw), out.getvalue() - - -class PrebuiltVision(unittest.TestCase): - """#331: the 0.1.30/0.1.31 zip's encoder has no sm_75 code: an RTX 20 card gets the CPU encoder, not a compile.""" - META = {"version": "0.1.31", "archs": [75, 86, 89, 120], "ptx": True, "vision_archs": [86, 89, 120]} - - def test_a_card_the_encoder_has_no_code_for_gets_the_cpu_encoder(self): - got, out = quiet(setup.prebuilt_vision, self.META, {"arch": 75}, "gpu") - self.assertEqual(got, "cpu") - self.assertIn("runs on the CPU instead", out) - - def test_covered_cards_keep_the_gpu_encoder(self): - for arch in (86, 89, 120): - self.assertEqual(quiet(setup.prebuilt_vision, self.META, {"arch": arch}, "gpu")[0], "gpu") - # a newer card than the newest encoder code: only with PTX in the zip - self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [86, 89]}, {"arch": 120}, "gpu")[0], - "gpu") - self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [86, 89], "ptx": False}, - {"arch": 120}, "gpu")[0], "cpu") - # 0.1.32's zip: the encoder built with 75-real too - self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [75, 86, 89, 120]}, - {"arch": 75}, "gpu")[0], "gpu") - - def test_other_choices_are_left_alone(self): - for v in ("cpu", "none"): - self.assertEqual(quiet(setup.prebuilt_vision, self.META, {"arch": 75}, v), (v, "")) - # an older BUILD.json without vision_archs: the engine's archs - self.assertEqual(quiet(setup.prebuilt_vision, {"archs": [75, 86]}, {"arch": 75}, "gpu")[0], "gpu") - - -class GgufDirShards(unittest.TestCase): - """#305: --gguf-dir reads the shard count from the -of-N part of the name instead of assuming two.""" - - def shards(self, names, family="qwen", model="IQ3_XXS"): - with tempfile.TemporaryDirectory() as d: - for n in names: - (Path(d) / n).write_bytes(b"") - return [p.name for p in setup.gguf_dir_shards(Path(d), setup.FAMILIES[family], model)] - - def test_the_published_two_shards(self): - names = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", - "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf"] - self.assertEqual(self.shards(names), names) - self.assertEqual(self.shards(names[:1]), names) # shard 2 missing: check_shards says so later - swift = ["Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", - "Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"] - self.assertEqual(self.shards(swift + ["mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf"], "swift", "Q2_0"), swift) - - def test_four_unsloth_shards(self): - names = ["Qwen3.8-Flash-Next-UD-Q4_K_XL-%05d-of-00004.gguf" % i for i in range(1, 5)] - self.assertEqual(self.shards(names + ["mmproj-F16.gguf"], model="Q4_K_XL"), names) - self.assertEqual(self.shards(names[:1], model="Q4_K_XL"), names) # the others named from the first - - def test_another_split_of_a_setup_size(self): - names = ["my-IQ3_XXS-%05d-of-00003.gguf" % i for i in range(1, 4)] - other = ["my-Q2_0-%05d-of-00002.gguf" % i for i in range(1, 3)] - self.assertEqual(self.shards(names + other), names) # the one with the size in its name - self.assertEqual(self.shards(other, model="Q2_0"), other) - - def test_nothing_recognisable_keeps_the_published_names(self): - want = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", - "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf"] - self.assertEqual(self.shards([]), want) - self.assertEqual(self.shards(["a-00001-of-00002.gguf", "b-00001-of-00002.gguf"]), want) # ambiguous - - -class GgufDirUnsupported(unittest.TestCase): - """#444: --gguf-dir with GGUFs PolyStrata cannot run (Unsloth's UD-IQ3_XXS, UD-Q2_K_XL) says so, names the files it - runs (ISTA-DASLab's GSQ-RCO, the Coder's, Unsloth's UD-Q4_K_XL) and the --family/--model of the usable ones.""" - UD = ["Qwen3.8-Flash-Next-UD-IQ3_XXS-%05d-of-00003.gguf" % i for i in range(1, 4)] + \ - ["Qwen3.8-Flash-Next-UD-Q2_K_XL-%05d-of-00003.gguf" % i for i in range(1, 4)] - - def problem(self, names, family="qwen", model="IQ3_XXS"): - with tempfile.TemporaryDirectory() as d: - for n in names: - (Path(d) / n).write_bytes(b"") - fam = setup.FAMILIES[family] - first = setup.gguf_dir_shards(Path(d), fam, model)[0] - p = setup.gguf_dir_problem(Path(d), first, fam, model) - return p and (p[0].replace(d, ""), p[1]) - - def test_quant_names(self): - for name, want in (("Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf", "UD-IQ3_XXS"), - ("Qwen3.8-Flash-Next-UD-Q2_K_XL-00001-of-00003.gguf", "UD-Q2_K_XL"), - ("model-Q4_K_M.gguf", "Q4_K_M"), - ("Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", None), - ("Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", None), - ("my-IQ3_XXS-00001-of-00003.gguf", None), ("mmproj-F16.gguf", None), - ("a-00001-of-00002.gguf", None)): - self.assertEqual(setup.gguf_unsupported(name), want, name) - - def test_an_unsloth_ud_file_is_not_taken_for_a_gsq_rco_size(self): - msg, hint = self.problem(self.UD) # IQ3_XXS: UD-IQ3_XXS has the size in its name - self.assertEqual(msg, "Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf is UD-IQ3_XXS, a GGUF PolyStrata " - "cannot run") - self.assertIn("ISTA-DASLab's GSQ-RCO files", hint) - self.assertIn("Unsloth's UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 only", hint) - - def test_a_folder_without_the_choice_names_what_is_there(self): - gsq = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-%05d-of-00002.gguf" % i for i in (1, 2)] - msg, hint = self.problem(self.UD + gsq, "unsloth", "UD-Q4_K_XL") - self.assertEqual(msg, " has no Qwen3.8-Flash-Next (Unsloth) UD-Q4_K_XL file") - self.assertIn("Not usable here: Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf, " - "Qwen3.8-Flash-Next-UD-Q2_K_XL-00001-of-00003.gguf", hint) - self.assertIn("Usable here: --family coder --model IQ1_M", hint) - - def test_usable_folders_are_left_alone(self): - good = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-%05d-of-00002.gguf" % i for i in (1, 2)] - self.assertIsNone(self.problem(good + self.UD)) - self.assertIsNone(self.problem(["my-IQ3_XXS-%05d-of-00003.gguf" % i for i in (1, 2, 3)])) - self.assertIsNone(self.problem([])) # nothing there: check_shards' "missing", as before - - def test_the_size_of_another_family(self): - from test_setup_golden import PROFILES, install - ram, found = PROFILES["64GB-1x32GB"] - with tempfile.TemporaryDirectory() as d: - code, out, _, _ = install(ram, found, ["--gguf-dir", d, "--family", "unsloth", "--model", "IQ3_XXS"]) - self.assertEqual(code, 1) - self.assertIn("has no IQ3_XXS model file", out) - self.assertIn("choose one of: UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL, Q8_0 (or IQ3_XXS: --family qwen --model IQ3_XXS, --family swift --model " - "IQ3_XXS)", out) - self.assertIn("PolyStrata runs ISTA-DASLab's GSQ-RCO files", out) - - -class ReadOnlyGgufDir(unittest.TestCase): - """--gguf-dir on a read-only folder (a share): whole shards without a finish mark still install, with a warning.""" - - def test_a_finish_mark_that_cannot_be_written_is_a_warning(self): - from test_setup_golden import PROFILES, install - ram, found = PROFILES["64GB-1x32GB"] - real_mark = setup.mark - - def read_only_mark(path, text=""): - if "gguf_share" in str(path): - raise PermissionError(13, "Read-only file system") - real_mark(path, text) - - with tempfile.TemporaryDirectory() as tmp: - d = Path(tmp) / "gguf_share" - d.mkdir() - for i in (1, 2): - (d / f"Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-{i:05d}-of-00002.gguf").write_bytes(b"") - code, out, cfg, _ = install(ram, found, ["--gguf-dir", str(d), "--family", "qwen", "--model", "Q2_0", - "--no-start"], - extra=[mock.patch.object(setup, "whole_shard", lambda s: True), - mock.patch.object(setup, "mark", read_only_mark)]) - self.assertEqual(code, 0, out) - self.assertIn("is whole but its finish mark cannot be written", out) - - - def test_mark_itself_never_stops_on_a_read_only_folder(self): - """#570: every finish mark (the SHA-256 result of a verified shard too), not only the one for a whole shard.""" - with tempfile.TemporaryDirectory() as tmp, mock.patch.object(Path, "write_text", - side_effect=PermissionError(13, "read-only")): - setup.mark(Path(tmp) / "x.gguf", "sha256 abc") # no exception - self.assertFalse(setup.done(Path(tmp) / "x.gguf")) - - -class VsRange(unittest.TestCase): - """#985: Visual Studio 2026 (version 18) is looked for only with CUDA 13.3 or newer.""" - - def asked(self, cuda_v): - seen = [] - with mock.patch.object(setup.Path, "exists", lambda self: True), mock.patch.object(setup, "out", lambda cmd, *a, **k: seen.append(cmd) or "C:/VS"): - setup.find_vcvars(cuda_v) - return seen[0][seen[0].index("-version") + 1] if "-version" in seen[0] else None - - def test_the_range_follows_the_toolkit(self): - self.assertIsNone(self.asked(None)) # #881: without CUDA vswhere gets no version range - self.assertEqual(self.asked((13, 0)), "[16.0,18.0)") - self.assertEqual(self.asked((13, 2)), "[16.0,18.0)") - self.assertEqual(self.asked((13, 3)), "[16.0,19.0)") - self.assertEqual(self.asked((14, 0)), "[16.0,19.0)") - - - def test_vcvars_by_hand(self): - """#881: STRATA_VCVARS names a vcvars64.bat directly, for an install vswhere cannot use.""" - import tempfile - with tempfile.TemporaryDirectory() as d: - bat = Path(d) / "vcvars64.bat" - bat.write_text("rem") - with mock.patch.dict(os.environ, {"STRATA_VCVARS": str(bat)}): - self.assertEqual(setup.find_vcvars(), bat) - with mock.patch.dict(os.environ, {"STRATA_VCVARS": str(Path(d) / "missing.bat")}): - self.assertIsNone(setup.find_vcvars()) - -class ExperimentalSm60(unittest.TestCase): - """#295: Pascal (6.x) and Volta (7.0) only with STRATA_EXPERIMENTAL_SM60=1, built with -DSTRATA_EXPERIMENTAL_SM60=ON - and a CUDA 12.x toolkit; nothing changes without the variable.""" - - def card(self, arch): - return {"arch": arch, "vram_gb": 11.0, "index": 0, "name": "card"} - - def test_the_gate(self): - with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": ""}): - for arch in ("60", "61", "70"): - p = setup.gpu_problem(self.card(arch)) - self.assertIn("not supported", p) - self.assertIn("choose it with --gpu 0", p) # the CUDA 12 engine (docs/OLDER_GPUS.md) - self.assertNotIn("--gpu", setup.gpu_problem(self.card("52"))) - self.assertIsNone(setup.gpu_problem(self.card("75"))) - with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}): - for arch in ("60", "61", "70", "75", "120"): - self.assertIsNone(setup.gpu_problem(self.card(arch)), arch) - for arch in ("52", "72"): - self.assertIsNotNone(setup.gpu_problem(self.card(arch)), arch) - - def test_the_build_flag(self): - self.assertEqual(setup.engine_defs([61]), ["-DSTRATA_EXPERIMENTAL_SM60=ON"]) - self.assertEqual(setup.engine_defs([70, 86]), ["-DSTRATA_EXPERIMENTAL_SM60=ON"]) - self.assertEqual(setup.engine_defs([75, 86, 120]), []) - - def test_find_nvcc_below(self): - with tempfile.TemporaryDirectory() as d: - new, old = Path(d) / "13" / "nvcc", Path(d) / "12" / "bin" / "nvcc" - for p in (new, old): - p.parent.mkdir(parents=True) - p.write_bytes(b"") - versions = {str(new): "Cuda compilation tools, release 13.0, V13.0.88", - str(old): "Cuda compilation tools, release 12.9, V12.9.86"} - with mock.patch.object(setup, "WIN", False), mock.patch.object(setup.shutil, "which", lambda n: str(new)), \ - mock.patch.dict(os.environ, {"CUDA_PATH": str(Path(d) / "12")}), \ - mock.patch.object(setup, "out", lambda cmd: versions.get(cmd[0], "")): # #414 - self.assertEqual(setup.find_nvcc(), (str(new), (13, 0))) - self.assertEqual(setup.find_nvcc(below=(13, 0)), (str(old), (12, 9))) - # #601: STRATA_NVCC is the only one considered; CUDA_HOME is a candidate like CUDA_PATH - with mock.patch.dict(os.environ, {"STRATA_NVCC": str(old)}): - self.assertEqual(setup.find_nvcc(), (str(old), (12, 9))) - with mock.patch.dict(os.environ, {"STRATA_NVCC": str(new)}): - got, text = quiet(setup.find_nvcc, below=(13, 0)) - self.assertEqual(got, (None, None)) - self.assertIn("needs one older than 13.0", text) - with mock.patch.dict(os.environ, {"STRATA_NVCC": str(Path(d) / "missing")}): - got, text = quiet(setup.find_nvcc) - self.assertEqual(got, (str(new), (13, 0))) - self.assertIn("no such file", text) - with mock.patch.object(setup, "WIN", False), mock.patch.object(setup.shutil, "which", lambda n: None), \ - mock.patch.dict(os.environ, {"CUDA_HOME": str(Path(d) / "12")}), \ - mock.patch.object(setup, "out", lambda cmd: versions.get(cmd[0], "")): - os.environ.pop("CUDA_PATH", None) - got = setup.find_nvcc(below=(13, 0)) - self.assertEqual(got, (str(old), (12, 9))) - - def tools(self, archs, nvcc): - seen = [] - - def find(below=None): - seen.append(below) - return nvcc(below) - - with mock.patch.object(setup, "find_nvcc", find), mock.patch.object(setup, "find_vcvars", lambda cuda_v=None: "vcvars"), \ - mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n): - got, _ = quiet(setup.install_build_tools, {"arch": str(archs[0]), "archs": archs}, True) - return got, seen - - def test_pascal_takes_cuda_12(self): - got, seen = self.tools([61], lambda below: ("nvcc12", (12, 9)) if below == (13, 0) else ("nvcc13", (13, 0))) - self.assertEqual(got[0], "nvcc12") - self.assertEqual(seen, [(13, 0)]) - got, seen = self.tools([86, 120], lambda below: ("nvcc13", (13, 0))) - self.assertEqual((got[0], seen), ("nvcc13", [None])) # the default: unchanged - - def test_cuda_132_on_sm120(self): - """#892 / #968: nvcc 13.2 for an RTX 50 card: an older 13.x is taken when there is one, else a warning; never an - error, and no other card or toolkit is touched.""" - def nvcc(below): - return ("nvcc130", (13, 0)) if below == (13, 2) else ("nvcc132", (13, 2)) - - got, seen = self.tools([120], nvcc) - self.assertEqual(got[0], "nvcc130") - self.assertEqual(seen, [None, (13, 2)]) - with mock.patch.dict(os.environ, {"STRATA_NVCC": "x"}): # the user's own pick is kept - got, seen = self.tools([120], nvcc) - self.assertEqual((got[0], seen), ("nvcc132", [None])) - only132 = lambda below: (None, None) if below == (13, 2) else ("nvcc132", (13, 2)) - with mock.patch.object(setup, "warn") as warn: # nothing older: the one found, with a warning - got, _ = self.tools([120], only132) - self.assertEqual(got[0], "nvcc132") - self.assertIn("#892", warn.call_args[0][0]) - for archs in ([86], [89, 86]): # not an sm_120 card: as before - got, seen = self.tools(archs, nvcc) - self.assertEqual((got[0], seen), ("nvcc132", [None])) - - def test_pascal_without_cuda_12_stops(self): - for archs in ([61], [70, 120]): - with self.subTest(archs=archs), self.assertRaises(SystemExit): - self.tools(archs, lambda below: (None, None) if below else ("nvcc13", (13, 0))) - - -class HipVision(unittest.TestCase): - """#304: --vision cpu with --backend hip builds the CPU image encoder beside the HIP engine.""" - - @mock.patch.object(setup, "WIN", False) # Linux: compiled here (Windows has no AMD image encoder yet) - def test_the_choice(self): - self.assertEqual(quiet(setup.hip_vision, "cpu"), ("cpu", "")) - for asked in (None, "no", "none"): - self.assertEqual(quiet(setup.hip_vision, asked), ("none", "")) - for asked in ("yes", "gpu"): - got, out = quiet(setup.hip_vision, asked) - self.assertEqual(got, "none") - self.assertIn("--vision cpu", out) - - def build(self, meta, vision, vexe=False): - """build_engine_hip with an engine that is already built: only the encoder can be missing.""" - with tempfile.TemporaryDirectory() as d: - root = Path(d) - eng = root / "engine" - eng.mkdir() - (eng / setup.EXE).write_bytes(b"engine") - if vexe: - (eng / setup.VEXE).write_bytes(b"vision") - src, vsrc = "S", "V" - (eng / "BUILD.json").write_text(json.dumps({"backend": "hip", "archs": ["gfx1201"], "src": src, **meta})) - built = [] - - def cmake_build(src_dir, bdir, target, defs, vcvars, bat): - built.append((target, defs)) - (bdir / "bin").mkdir(parents=True) - (bdir / "bin" / setup.VEXE).write_bytes(b"vision") - - with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "cmake_build", cmake_build), \ - mock.patch.object(setup, "source_hash", lambda paths: vsrc if paths == setup.VISION_SOURCES else src): - quiet(setup.build_engine_hip, {"arch": "gfx1201"}, "llama", vision) - return built, json.loads((eng / "BUILD.json").read_text()), (eng / setup.VEXE).exists() - - def test_the_cpu_encoder_is_built_once(self): - built, meta, have = self.build({}, "cpu") - self.assertEqual([t for t, _ in built], ["strata-vision"]) - self.assertIn("-DSTRATA_VISION_CUDA=OFF", built[0][1]) - self.assertIn("-DSTRATA_PORTABLE=OFF", built[0][1]) # built for this PC (#411: portable is the default) - self.assertEqual((meta["vision"], meta["vision_src"], have), ("cpu", "V", True)) - built, meta, _ = self.build({"vision": "cpu", "vision_src": "V"}, "cpu", vexe=True) - self.assertEqual(built, []) # built and unchanged: nothing to do - built, meta, _ = self.build({"vision": "cpu", "vision_src": "old"}, "cpu", vexe=True) - self.assertEqual([t for t, _ in built], ["strata-vision"]) # its source changed: again - - def test_without_images_nothing_changes(self): - built, meta, have = self.build({}, "none") - self.assertEqual((built, have), ([], False)) - self.assertNotIn("vision_src", meta) - - -class RotationalDisk(unittest.TestCase): - """#605: a model on a rotational disk gets --ple-io ram when the n-gram table fits the RAM, else a warning.""" - - def install(self, ram, disk): - from test_setup_golden import PROFILES, install - _, found = PROFILES["64GB-1x32GB"] - return install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], - extra=[mock.patch.object(setup, "rotational_disk", lambda p: disk)]) - - def test_fits(self): - code, out, cfg, _ = self.install(127.8, "sdb") - self.assertEqual(code, 0, out) - a = cfg["args"] - self.assertEqual(a[a.index("--ple-io") + 1], "ram") - self.assertIn("rotational disk (sdb)", out) - - def test_does_not_fit(self): - code, out, cfg, _ = self.install(63.7, "sdb") - self.assertEqual(code, 0, out) - self.assertNotIn("--ple-io", cfg["args"]) - self.assertIn("An SSD is recommended", out) - - def test_ssd(self): - code, out, cfg, _ = self.install(127.8, None) - self.assertNotIn("--ple-io", cfg["args"]) - self.assertNotIn("rotational", out) - - def test_sysfs(self): - if not sys.platform.startswith("linux"): - self.assertIsNone(setup.rotational_disk(__file__)) # Windows: never - return - self.assertIn(setup.rotational_disk(__file__), (None,) + tuple(os.listdir("/sys/block"))) - - -class VramReserve(unittest.TestCase): - """#493: --vram-reserve-mib N - VRAM the engine leaves free for other programs - goes into the config only when - given (the default config is tools/test_setup_golden.py's, unchanged), at setup and on a start.""" - - def setUp(self): - from test_setup_golden import PROFILES - self.ram, self.found = PROFILES["64GB-1x32GB"] - - def install(self, *extra): - from test_setup_golden import install - return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra]) - - def test_given_at_setup(self): - code, out, cfg, _ = self.install("--vram-reserve-mib", "2048") - self.assertEqual(code, 0, out) - a = cfg["args"] - self.assertEqual(a.count("--vram-reserve-mib"), 1) - self.assertEqual(a[a.index("--vram-reserve-mib") + 1], "2048") - self.assertIn("VRAM kept free for other programs: 2048 MiB", out) - code, out, cfg, _ = self.install() - self.assertNotIn("--vram-reserve-mib", cfg["args"]) # not given: the engine's default, as before - - def test_with_images_one_value(self): - code, out, cfg, _ = self.install("--vision", "cpu", "--vram-reserve-mib", "1500") - self.assertEqual(code, 0, out) - a = cfg["args"] - self.assertEqual(a.count("--vram-reserve-mib"), 1) - self.assertEqual(a[a.index("--vram-reserve-mib") + 1], "1500") - - def test_a_negative_value_is_refused(self): - with contextlib.redirect_stderr(io.StringIO()) as err: - code, out, cfg, _ = self.install("--vram-reserve-mib", "-1") - self.assertEqual(code, 2) - self.assertIn("--vram-reserve-mib takes a number of MiB", err.getvalue()) - - def test_kept_from_an_earlier_install(self): - with tempfile.TemporaryDirectory() as d: - p = Path(d) / "strata-q2_0.json" - p.write_text(json.dumps({"args": ["--max-context", "8192", "--vram-reserve-mib", "2048"]})) - self.assertEqual(setup.choices_from_config(p)["vram_reserve_mib"], 2048) - p.write_text(json.dumps({"args": ["--vision", "--vram-reserve-mib", "700"], "vision": {"gpu": True}})) - self.assertIsNone(setup.choices_from_config(p)["vram_reserve_mib"]) # the images' own reserve - p.write_text(json.dumps({"args": ["--max-context", "8192"]})) - self.assertIsNone(setup.choices_from_config(p)["vram_reserve_mib"]) - - def test_given_on_a_start(self): - with tempfile.TemporaryDirectory() as d: - exe = Path(d) / "strata.exe" - exe.write_bytes(b"") - p = Path(d) / "strata-q2_0.json" - p.write_text(json.dumps({"exe": str(exe), "args": ["--kv", "int8"], "gpu": 0, "gpus_asked": True})) - call = mock.Mock(return_value=0) - with mock.patch.object(setup, "gpus", lambda: self.found), \ - mock.patch.object(setup, "is_wsl", lambda: False), \ - mock.patch.object(setup, "ensure_engine_for", lambda cards, path, cfg, yes: cfg), \ - mock.patch.object(setup.subprocess, "call", call): - for n in ("2048", "1024"): - _, out = quiet(setup.start, p, None, None, False, True, None, {"vram_reserve_mib": int(n)}) - self.assertEqual(json.loads(p.read_text())["args"], ["--kv", "int8", "--vram-reserve-mib", n]) - self.assertIn("1024 MiB of VRAM kept free", out) - self.assertTrue(call.called) - - -class SmallCardTip(unittest.TestCase): - """#496: a card under 8 GB (a 6 GB laptop RTX 3060) gets a tip for when the start has no room for the expert cache; - the engine chooses its own reserve there, so the config is the one any card gets. An 8 GB card: no tip.""" - - def install(self, vram, *extra): - from test_setup_golden import card, install - return install(63.7, [card(0, "NVIDIA GeForce RTX 3060 Laptop GPU", vram, "86")], - ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra]) - - def test_a_6gb_card(self): - code, out, cfg, _ = self.install(6.0) - self.assertEqual(code, 0, out) - self.assertNotIn("--vram-reserve-mib", cfg["args"]) # the engine decides (no fixed reserve) - self.assertIn("no VRAM is left for the expert cache", out) - self.assertIn("--draft-vocab en", out) - self.assertIn("--mtp", cfg["args"]) # the draft layer stays: the server needs it - - def test_an_8gb_card_has_no_tip(self): - for vram in (8188 / 1024, 8.0): # nvidia-smi lists an 8 GB card as 8188 MiB - code, out, cfg, _ = self.install(vram) - self.assertEqual(code, 0, out) - self.assertNotIn("no VRAM is left for the expert cache", out) - self.assertNotIn("--vram-reserve-mib", cfg["args"]) - - def test_a_given_reserve_is_kept(self): - code, out, cfg, _ = self.install(6.0, "--vram-reserve-mib", "500") - self.assertEqual(code, 0, out) - a = cfg["args"] - self.assertEqual(a[a.index("--vram-reserve-mib") + 1], "500") - - def test_the_tip(self): - self.assertIn("an 8K context", " ".join(setup.small_card_note(32768, None))) - self.assertIn("--draft-vocab en", " ".join(setup.small_card_note(32768, "cjk"))) - tip = " ".join(setup.small_card_note(8192, "en")) - self.assertNotIn("--draft-vocab", tip) - self.assertIn("close other programs", tip) - - -class DesktopReserveTip(unittest.TestCase): - """#560 #516: an AMD card on a Linux desktop gets a recommended reserve (3072 MiB) - a tip, the config is not - changed.""" - - def test_desktop_detection(self): - with mock.patch.object(setup.sys, "platform", "linux"): - self.assertTrue(setup.linux_desktop({"WAYLAND_DISPLAY": "wayland-0"})) - self.assertTrue(setup.linux_desktop({"DISPLAY": ":0"})) - self.assertFalse(setup.linux_desktop({})) # a headless box / ssh - with mock.patch.object(setup.sys, "platform", "win32"): - self.assertFalse(setup.linux_desktop({"DISPLAY": ":0"})) # Windows counts the desktop itself (#497) - - def test_the_tip(self): - tip = " ".join(setup.desktop_reserve_note()) - self.assertIn("--vram-reserve-mib 3072", tip) - self.assertIn("desktop", tip) - - -class CudaVision(unittest.TestCase): - """#411: the image encoder setup compiles beside the CUDA engine is built for this PC, not portable.""" - - def test_the_encoder_is_built_native(self): - for vision in ("gpu", "cpu"): - with self.subTest(vision), tempfile.TemporaryDirectory() as d: - root = Path(d) - eng = root / "engine" - eng.mkdir() - (eng / setup.EXE).write_bytes(b"engine") # the engine is built: only the encoder - (eng / "BUILD.json").write_text(json.dumps({"source": "local", "archs": [86], "src": "S"})) - built = [] - - def cmake_build(src_dir, bdir, target, defs, vcvars, bat): - built.append((target, defs)) - (bdir / "bin").mkdir(parents=True) - (bdir / "bin" / setup.VEXE).write_bytes(b"vision") - - with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "cmake_build", cmake_build), \ - mock.patch.object(setup, "source_hash", lambda p: "V" if p == setup.VISION_SOURCES else "S"), \ - mock.patch.object(setup, "install_build_tools", lambda gpu, yes: (str(root / "nvcc"), None)), \ - mock.patch.object(setup, "source_version", lambda: "test"): - quiet(setup.build_engine, {"arch": "86"}, vision, True, "llama") - self.assertEqual([t for t, _ in built], ["strata-vision"]) - self.assertIn("-DSTRATA_PORTABLE=OFF", built[0][1]) - self.assertIn(f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}", built[0][1]) - - -class SwiftIq3s(unittest.TestCase): - """#1651: Swift 1.5 has its own IQ3_S tier since 2026-10-08 (ukisai's Swift-1.5 GGUF repo) - the model choice - must not hide it behind the qwen family. Names and sizes checked against the Hub listing when written.""" - - def test_iq3_s_is_a_swift_choice(self): - self.assertIn("swift", setup.MODELS["IQ3_S"].get("families", ("qwen", "swift"))) - - def test_the_published_file_names(self): - fam = setup.FAMILIES["swift"] - self.assertEqual(setup.model_shards(fam, "IQ3_S"), 2) - self.assertEqual([setup.model_file(fam, "IQ3_S", i) for i in (1, 2)], - ["Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf"]) - - -class HostCompilers(unittest.TestCase): - """#1645: CC / CXX / CUDAHOSTCXX name the build's compilers - handed to CMake as -D, so a build folder that is - already configured picks them up too (CXX alone reaches CMake only on the first configure: the reporter's - `CXX=g++-14` run died at the last step). CUDAHOSTCXX is nvcc's host compiler and defaults to CXX.""" - - def test_env_names_the_compilers(self): - with mock.patch.dict(os.environ, {"CC": "gcc-14", "CXX": "g++-14", "CUDAHOSTCXX": "g++-14-alt"}): - self.assertEqual(setup.host_compiler_defs(True), ["-DCMAKE_C_COMPILER=gcc-14", - "-DCMAKE_CXX_COMPILER=g++-14", - "-DCMAKE_CUDA_HOST_COMPILER=g++-14-alt"]) - - def test_cudahostcxx_defaults_to_cxx_and_needs_cuda(self): - with mock.patch.dict(os.environ, {"CC": "", "CXX": "g++-14", "CUDAHOSTCXX": ""}): - self.assertEqual(setup.host_compiler_defs(True), ["-DCMAKE_CXX_COMPILER=g++-14", - "-DCMAKE_CUDA_HOST_COMPILER=g++-14"]) - self.assertEqual(setup.host_compiler_defs(False), ["-DCMAKE_CXX_COMPILER=g++-14"]) # a C++-only project - - def test_unset_adds_nothing(self): - with mock.patch.dict(os.environ, {"CC": "", "CXX": "", "CUDAHOSTCXX": ""}): - self.assertEqual(setup.host_compiler_defs(True), []) - - def test_the_defs_reach_cmake(self): - """The engine's and the CUDA encoder's configure both take them.""" - with tempfile.TemporaryDirectory() as d: - root = Path(d) - eng = root / "engine" - eng.mkdir() - (eng / "BUILD.json").write_text(json.dumps({"source": "local", "archs": [86], "src": "old"})) - built = [] - - def cmake_build(src_dir, bdir, target, defs, vcvars, bat): - built.append((target, defs)) - (bdir / "bin").mkdir(parents=True, exist_ok=True) - (bdir / "bin" / setup.VEXE).write_bytes(b"vision") - (bdir / setup.EXE).write_bytes(b"engine") - - env = {"CC": "gcc-14", "CXX": "g++-14", "CUDAHOSTCXX": ""} - with mock.patch.dict(os.environ, env), mock.patch.object(setup, "ROOT", root), \ - mock.patch.object(setup, "cmake_build", cmake_build), \ - mock.patch.object(setup, "source_hash", lambda p: "V" if p == setup.VISION_SOURCES else "new"), \ - mock.patch.object(setup, "install_build_tools", lambda gpu, yes: (str(root / "nvcc"), None)), \ - mock.patch.object(setup, "source_version", lambda: "test"): - quiet(setup.build_engine, {"arch": "86"}, "gpu", True, "llama") - for target, defs in built: - self.assertIn("-DCMAKE_CXX_COMPILER=g++-14", defs, target) - self.assertIn("-DCMAKE_CUDA_HOST_COMPILER=g++-14", defs, target) - - -if __name__ == "__main__": - unittest.main() - - -class CalibrateWithModel(unittest.TestCase): - """#2036: --calibrate --model X tunes model X (it used to fall through to a plain re-setup); a model that is not - installed is an error that says so; --calibrate with --setup or --check says it does nothing.""" - - def run_main(self, *argv, installed=("iq3_xxs", "q2_0")): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - cfgs = [] - for tag in installed: - p = Path(tmp.name) / f"strata-{tag}.json" - p.write_text(json.dumps({"exe": "x", "args": ["--max-context", "8192"], "model_name": tag})) - cfgs.append(p) - tuned = [] - with mock.patch.object(sys, "argv", ["setup.py", *argv]), \ - mock.patch.object(setup, "installed_configs", lambda: cfgs), \ - mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None), \ - mock.patch.object(setup, "calibrate_config", lambda c: tuned.append(c.name) or True), \ - mock.patch.object(setup, "start", lambda *a, **k: 0), \ - mock.patch.object(setup, "data_folder", lambda d: (Path(tmp.name), [])), \ - mock.patch.object(setup, "step", side_effect=SystemExit("reached the plain setup")): - try: - code, out = quiet(setup.main) - except SystemExit as e: - code, out = e.code, "" - return code, tuned - - def test_model_is_the_target(self): - code, tuned = self.run_main("--calibrate", "--model", "IQ3_XXS", "--yes", "--no-start") - self.assertEqual((code, tuned), (0, ["strata-iq3_xxs.json"])) - - def test_a_model_not_installed_is_an_error(self): - code, tuned = self.run_main("--calibrate", "--model", "IQ3_S", "--yes", "--no-start") - self.assertEqual((code, tuned), (1, [])) - - def test_targets(self): - with tempfile.TemporaryDirectory() as d: - ps = [] - for tag in ("iq3_xxs", "q2_0"): - p = Path(d) / f"strata-{tag}.json" - p.write_text(json.dumps({"args": []})) - ps.append(p) - self.assertEqual(setup.calibration_targets(ps, None, None), ps) - self.assertEqual(setup.calibration_targets(ps, "Q2_0", None), [ps[1]]) - self.assertEqual(setup.calibration_targets(ps, "Q2_0", "qwen"), [ps[1]]) - self.assertEqual(setup.calibration_targets(ps, "Q4_K_M", None), []) diff --git a/tools/test_setup_compute_mode.py b/tools/test_setup_compute_mode.py deleted file mode 100644 index a649385..0000000 --- a/tools/test_setup_compute_mode.py +++ /dev/null @@ -1,36 +0,0 @@ -"""#1445: setup warns when nvidia-smi reports a compute mode other than Default (never refuses). - - python -m unittest tools.test_setup_compute_mode -""" -from __future__ import annotations - -import sys -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -class Mode(unittest.TestCase): - def test_default_is_silent(self): - for m in ("Default", "default", "", "[N/A]", "N/A"): - self.assertIsNone(setup.compute_mode_warning(0, m), m) - - def test_other_modes_warn(self): - for m in ("Exclusive_Process", "Prohibited", "Exclusive_Thread"): - w = setup.compute_mode_warning(2, m) - self.assertIn(m, w) - self.assertIn("GPU 2", w) - self.assertIn("nvidia-smi -i 2 -c DEFAULT", w) - - def test_query(self): - with mock.patch.object(setup, "out", return_value="Exclusive_Process\n") as o: - self.assertEqual(setup.gpu_compute_mode(1), "Exclusive_Process") - self.assertIn("compute_mode", " ".join(o.call_args[0][0])) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_config.py b/tools/test_setup_config.py deleted file mode 100644 index d031891..0000000 --- a/tools/test_setup_config.py +++ /dev/null @@ -1,277 +0,0 @@ -"""Tests for what setup keeps in a model's run config when it runs again (#629), the browser choice (#609) and the -image-token flag (#625). Every outside effect is mocked (tools/test_setup_golden.py's install()). - - python -m unittest tools.test_setup_config -""" -from __future__ import annotations - -import contextlib -import io -import json -import sys -import tempfile -import unittest -import unittest.mock -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 -from test_setup_golden import PROFILES, install # noqa: E402 - - -def quiet(fn, *args, **kw): - out = io.StringIO() - with contextlib.redirect_stdout(out): - return fn(*args, **kw), out.getvalue() - - -USER = {"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0}, - "mcp_servers": {"files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]}}, - "mcp": {"timeout_s": 60, "max_result_chars": 16000, "max_rounds": 8}, - "cors_origins": ["http://localhost:3000"], "reasoning_effort": "low"} - - -class CarryOver(unittest.TestCase): - """#629: setup run again (a different --context) keeps the keys it does not write and keeps the old file as .bak.""" - - def setUp(self): - self.ram, self.found = PROFILES["64GB-1x32GB"] - - def run_setup(self, *extra, configs=()): - return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], - configs=configs) - - def test_user_keys_survive_a_rerun(self): - code, out, first, _ = self.run_setup("--context", "65536") - self.assertEqual(code, 0, out) - old = {**first, **USER, "args": first["args"] + ["--hand-option", "7"]} - code, out, cfg, _ = self.run_setup("--context", "131072", configs=[("strata-q2_0.json", old)]) - self.assertEqual(code, 0, out) - for k, v in USER.items(): - self.assertEqual(cfg[k], v, k) - a = cfg["args"] - self.assertEqual(a[a.index("--max-context") + 1], "131072") # the new choice is used - self.assertNotIn("--hand-option", a) # setup chooses the engine options... - self.assertIn("kept from your earlier strata-q2_0.json: sampling, mcp_servers, mcp, cors_origins, " - "reasoning_effort", out) - self.assertIn("kept as strata-q2_0.json.bak", out) - self.assertIn("--hand-option", out) # ...and says which ones it did not keep - - def test_a_first_install_is_unchanged(self): - code, out, cfg, _ = self.run_setup() - self.assertEqual(code, 0, out) - self.assertNotIn("kept from", out) - self.assertNotIn(".bak", out) - self.assertFalse(set(cfg) - setup.SETUP_KEYS) # setup writes only its own keys - - def test_setup_keys_are_rewritten(self): - code, out, first, _ = self.run_setup() - old = {**first, "model_name": "renamed", "port": 9999, "draft_vocab": "en", "host": "0.0.0.0"} - code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", old)]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["model_name"], first["model_name"]) - self.assertEqual(cfg["port"], first["port"]) - self.assertNotIn("host", cfg) # as before: --host is given to setup - self.assertEqual(cfg["draft_vocab"], "en") # kept by its own rule (saved_draft_vocab) - self.assertNotIn("kept from", out) - - def test_write_setup_config(self): - with tempfile.TemporaryDirectory() as d: - p = Path(d) / "strata-x.json" - mm = Path(d) / "mmproj-Q8_0.gguf" - mm.write_bytes(b"") - old = {"exe": "e", "args": ["--kv", "int8", "--threads", "8"], "sampling": {"temperature": 0.7}, - "env": {"STRATA_RESIDENT_PIN": "0", "MY_VAR": "1"}, - "vision": {"exe": "v", "mmproj": str(mm), "gpu": False, "max_tokens": 300, "min_tokens": 64}} - p.write_text(json.dumps(old), encoding="utf-8") - new = {"exe": "e2", "args": ["--kv", "int8"], - "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, "max_tokens": 300}} - _, out = quiet(setup.write_setup_config, p, new) - got = json.loads(p.read_text(encoding="utf-8")) - self.assertEqual(got["sampling"], {"temperature": 0.7}) - self.assertEqual(got["env"], {"MY_VAR": "1"}) # setup's own env entry is setup's to write - self.assertEqual(got["vision"]["mmproj"], str(mm)) # a Q8_0 mmproj of the user's own (#625) - self.assertEqual(got["vision"]["min_tokens"], 64) - self.assertEqual(got["exe"], "e2") - self.assertEqual(json.loads((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8")), old) - self.assertIn("--threads", out) - # the same again: nothing changes, so no new copy is made - (Path(d) / "strata-x.json.bak").unlink() - again = {"exe": "e2", "args": ["--kv", "int8"], - "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, - "max_tokens": 300}} - quiet(setup.write_setup_config, p, again) - self.assertFalse((Path(d) / "strata-x.json.bak").exists()) - self.assertEqual(json.loads(p.read_text(encoding="utf-8")), got) - - def test_an_unreadable_earlier_config_is_replaced_with_a_copy(self): - with tempfile.TemporaryDirectory() as d: - p = Path(d) / "strata-x.json" - p.write_text("{cut off", encoding="utf-8") - quiet(setup.write_setup_config, p, {"exe": "e", "args": []}) - self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"exe": "e", "args": []}) - self.assertEqual((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8"), "{cut off") - - def test_display_tip_and_typed_ahead_flush(self): - # #779: the tip only when nvidia-smi says the card drives a display; #841: typed-ahead keys are dropped on a tty - with unittest.mock.patch.object(setup, "out", lambda cmd: "Enabled\n"): - self.assertTrue(setup.gpu_drives_display({"index": 0})) - with unittest.mock.patch.object(setup, "out", lambda cmd: "Disabled\n"), unittest.mock.patch.object(setup, "out") as o: - o.return_value = "Disabled\n" - self.assertFalse(setup.gpu_drives_display({"index": 1})) - self.assertIn("1", o.call_args[0][0]) - with unittest.mock.patch.object(setup, "out", lambda cmd: ""): - self.assertFalse(setup.gpu_drives_display({"index": 0})) - with unittest.mock.patch.object(setup.sys, "stdin") as stdin: - stdin.isatty.return_value = False - setup.flush_typed_ahead() # a pipe: nothing touched - stdin.fileno.assert_not_called() - - def test_a_learned_expert_profile_is_carried(self): - # #775: --expert-profile / --expert-profile-save added by hand survive a setup run - with tempfile.TemporaryDirectory() as d: - mine = Path(d) / "learned.bin" - mine.write_bytes(b"x") - old = {"args": ["--kv", "int8", "--expert-profile", str(mine), "--expert-profile-save", str(mine)]} - new = {"args": ["--kv", "int8", "--expert-profile", "/data/expert-profile.bin", "--expert-cache", "auto"]} - self.assertEqual(setup.carry_over(old, new), ["args --expert-profile", "args --expert-profile-save"]) - self.assertEqual(setup.flag_value(new["args"], "--expert-profile"), str(mine)) - self.assertEqual(setup.flag_value(new["args"], "--expert-profile-save"), str(mine)) - # the shipped profile named again, or a file that is gone: setup's own stays - gone = {"args": ["--expert-profile", str(Path(d) / "gone.bin")]} - new = {"args": ["--expert-profile", "/data/expert-profile.bin"]} - self.assertEqual(setup.carry_over(gone, new), []) - self.assertEqual(new["args"], ["--expert-profile", "/data/expert-profile.bin"]) - same = {"args": ["--expert-profile", "/old/expert-profile.bin"]} - self.assertEqual(setup.carry_over(same, new), []) - - def test_a_missing_mmproj_is_not_carried(self): - old = {"vision": {"mmproj": "/nowhere/mmproj-Q8_0.gguf", "gpu": True}} - new = {"vision": {"mmproj": "/data/mmproj-BF16.gguf", "gpu": True}} - self.assertEqual(setup.carry_over(old, new), []) - self.assertEqual(new["vision"]["mmproj"], "/data/mmproj-BF16.gguf") - - def test_a_copy_set_up_like_the_last_one_keeps_them_too(self): - with tempfile.TemporaryDirectory() as d: - src = Path(d) / "other" / "strata-x.json" - src.parent.mkdir() - src.write_text(json.dumps({"exe": "old", "mcp_servers": {"a": {"command": "x"}}}), encoding="utf-8") - p = Path(d) / "strata-x.json" - quiet(setup.write_setup_config, p, {"exe": "new"}, src) - self.assertEqual(json.loads(p.read_text(encoding="utf-8")), - {"exe": "new", "mcp_servers": {"a": {"command": "x"}}}) - self.assertFalse((Path(d) / "strata-x.json.bak").exists()) # nothing here was replaced - - -class NoBrowser(unittest.TestCase): - """#609 (#631): --no-browser keeps the chat page from opening: "open_browser": false in the run config, no --open - on the start's server command or in run-.bat/.sh. Without the flag nothing changes.""" - - def setUp(self): - self.ram, self.found = PROFILES["64GB-1x32GB"] - - def run_setup(self, *extra, configs=()): - return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], - configs=configs) - - def test_at_setup(self): - code, out, cfg, _ = self.run_setup("--no-browser") - self.assertEqual(code, 0, out) - self.assertIs(cfg["open_browser"], False) - code, out, cfg, _ = self.run_setup() - self.assertNotIn("open_browser", cfg) # not given: the config as before - # setup run again without the flag keeps the choice (#629); --browser undoes it - code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", {"open_browser": False})]) - self.assertIs(cfg["open_browser"], False) - code, out, cfg, _ = self.run_setup("--browser", configs=[("strata-q2_0.json", {"open_browser": False})]) - self.assertIs(cfg["open_browser"], True) - - def test_run_script(self): - with tempfile.TemporaryDirectory() as d, unittest.mock.patch.object(setup, "ROOT", Path(d)): - text = lambda p: p.read_text(encoding="utf-8") # noqa: E731 - self.assertIn('"--open"', text(setup.write_run_script("Q2_0", Path(d) / "strata-q2_0.json", 8080))) - script = setup.write_run_script("Q2_0", Path(d) / "strata-q2_0.json", 8080, False) - self.assertNotIn("--open", text(script)) - self.assertIn('"--port" "8080"', text(script)) - - def start_cmd(self, cfg, keep=None): - with tempfile.TemporaryDirectory() as d: - exe = Path(d) / "strata.exe" - exe.write_bytes(b"") - p = Path(d) / "strata-q2_0.json" - p.write_text(json.dumps({"exe": str(exe), "args": ["--kv", "int8"], "gpu": 0, "gpus_asked": True, **cfg})) - call = unittest.mock.Mock(return_value=0) - with unittest.mock.patch.object(setup, "gpus", lambda: self.found), \ - unittest.mock.patch.object(setup, "is_wsl", lambda: False), \ - unittest.mock.patch.object(setup, "ensure_engine_for", lambda cards, path, c, yes: c), \ - unittest.mock.patch.object(setup.subprocess, "call", call): - _, out = quiet(setup.start, p, None, None, True, True, None, keep) - return call.call_args[0][0], out, json.loads(p.read_text()) - - def test_on_a_start(self): - cmd, out, _ = self.start_cmd({}) - self.assertIn("--open", cmd) # the default, as before - self.assertIn("the browser opens when it is ready", out) - cmd, out, _ = self.start_cmd({"open_browser": False}) - self.assertNotIn("--open", cmd) - self.assertNotIn("the browser opens", out) - self.assertIn("no browser", out) # the Settings line says so - cmd, out, saved = self.start_cmd({}, {"open_browser": False}) # START-HERE --no-browser: kept from now on - self.assertNotIn("--open", cmd) - self.assertIs(saved["open_browser"], False) - self.assertIn("saved for this model: no browser", out) - cmd, out, saved = self.start_cmd({"open_browser": False}, {"open_browser": True}) - self.assertIn("--open", cmd) - self.assertIs(saved["open_browser"], True) - - -class VisionTokens(unittest.TestCase): - """#625: --vision-tokens N sets the config's vision.max_tokens (the most image tokens a picture becomes); a setup - run again keeps it for the same encoder device; without it the device's default, as before.""" - - def setUp(self): - self.ram, self.found = PROFILES["64GB-1x32GB"] - - def run_setup(self, *extra, configs=()): - return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], - configs=configs) - - def test_the_flag(self): - code, out, cfg, _ = self.run_setup("--vision", "cpu") - self.assertEqual(code, 0, out) - self.assertEqual(cfg["vision"]["max_tokens"], 300) # the default, as before - self.assertNotIn("--vision-tokens", out) - code, out, cfg, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "768") - self.assertEqual(code, 0, out) - self.assertEqual(cfg["vision"]["max_tokens"], 768) - self.assertIn("up to 768 image tokens", out) - self.assertIn("longer to encode", out) # a note, not a cap - code, out, cfg, _ = self.run_setup("--vision", "gpu", "--vision-tokens", "2048") - self.assertEqual(cfg["vision"]["max_tokens"], 2048) - self.assertIn("more VRAM", out) - - def test_kept_when_setup_runs_again(self): - code, out, first, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "768") - old = [("strata-q2_0.json", first)] - code, out, cfg, _ = self.run_setup("--vision", "cpu", "--context", "65536", configs=old) - self.assertEqual(cfg["vision"]["max_tokens"], 768) - code, out, cfg, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "300", configs=old) - self.assertEqual(cfg["vision"]["max_tokens"], 300) # given again: the new value - code, out, cfg, _ = self.run_setup("--vision", "gpu", configs=old) - self.assertEqual(cfg["vision"]["max_tokens"], 1024) # another device: its own default - - def test_refused_and_unused(self): - with contextlib.redirect_stderr(io.StringIO()) as err: - code, out, cfg, _ = self.run_setup("--vision-tokens", "0") - self.assertEqual(code, 2) - self.assertIn("--vision-tokens takes a number", err.getvalue()) - code, out, cfg, _ = self.run_setup("--vision", "no", "--vision-tokens", "768") - self.assertEqual(code, 0, out) - self.assertNotIn("vision", cfg) - self.assertIn("images are off", out) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_configs.py b/tools/test_setup_configs.py deleted file mode 100644 index afb1bfa..0000000 --- a/tools/test_setup_configs.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Tests for the model configs setup.py lists: the server keeps a config's Chat settings next to it as -`strata-.shared-settings.json`, which matches the configs' own `strata-*.json` but is not one (no exe, no -args), so the start menu and the "set up like the last one" lookup must leave it out. - - python -m unittest tools.test_setup_configs -""" -from __future__ import annotations - -import json -import os -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - -CONFIG = {"exe": "engine/strata.exe", "args": ["--max-context", "131072"]} -SHARED = {"reasoning_effort": "high", "temperature": 0.6} - - -def write(folder: Path, name: str, data: dict) -> Path: - path = folder / name - path.write_text(json.dumps(data), encoding="utf-8") - return path - - -class ModelConfigs(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.dir = Path(tmp.name) - self.config = write(self.dir, "strata-iq3_s.json", CONFIG) - self.shared = write(self.dir, "strata-iq3_s.shared-settings.json", SHARED) - # previous_config also looks into the PolyStrata folders next to this checkout: keep the real ones out - patch = mock.patch.object(setup, "other_installs", return_value=[]) - patch.start() - self.addCleanup(patch.stop) - - def test_the_start_menu_lists_the_config_but_not_its_shared_settings(self): - with mock.patch.object(setup, "ROOT", self.dir): - self.assertEqual(setup.installed_configs(), [self.config]) - - def test_the_last_config_of_another_install_is_never_its_shared_settings(self): - # the shared settings are written after the config (the first time Chat settings are saved), so they are - # the newest strata-*.json there - later = self.config.stat().st_mtime + 60 - os.utime(self.shared, (later, later)) - self.assertEqual(setup.previous_config([self.dir], {}), self.config) - - def test_a_folder_with_only_shared_settings_has_no_config(self): - self.config.unlink() - with mock.patch.object(setup, "ROOT", self.dir): - self.assertEqual(setup.installed_configs(), []) - self.assertIsNone(setup.previous_config([self.dir], {})) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_cuda_repo.py b/tools/test_setup_cuda_repo.py deleted file mode 100644 index 1c59cf7..0000000 --- a/tools/test_setup_cuda_repo.py +++ /dev/null @@ -1,115 +0,0 @@ -"""The CUDA Toolkit apt install: which distros it covers and which 13.x package it picks -(Debian 13's repo has no cuda-toolkit-13-0). No GPU, downloads or installs are used. - - python -m unittest tools.test_setup_cuda_repo -""" -from __future__ import annotations - -import contextlib -import io -import sys -import types -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -class AptRepo(unittest.TestCase): - def test_known_and_unknown_distros(self): - for osr, want in ({"ID": "ubuntu", "VERSION_ID": '"22.04"'}, "ubuntu2204"), \ - ({"ID": "ubuntu", "VERSION_ID": '"24.04"'}, "ubuntu2404"), \ - ({"ID": "debian", "VERSION_ID": '"12"'}, "debian12"), \ - ({"ID": "debian", "VERSION_ID": '"13"'}, "debian13"), \ - ({"ID": "debian", "VERSION_ID": '"11"'}, None), \ - ({"ID": "fedora", "VERSION_ID": '"42"'}, None), \ - ({}, None): - with self.subTest(osr=osr): - self.assertEqual(setup.cuda_apt_repo(osr), want) - - def test_debian_13_falls_back_to_the_oldest_13_x_it_has(self): - # the repo has no 13-0: apt fails on it, setup must try 13-1 and stop there (not install 13-2+) - installed = [] - - def fake_run(cmd, **kw): - installed.append(cmd[-1]) - return types.SimpleNamespace(returncode=100 if cmd[-1] == "cuda-toolkit-13-0" else 0) - - with mock.patch.object(setup, "WIN", False), \ - mock.patch.object(setup, "find_nvcc", side_effect=[(None, (0, 0)), ("/usr/local/cuda-13.1/bin/nvcc", (13, 1))]), \ - mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ - mock.patch("builtins.open", mock.mock_open(read_data='ID=debian\nVERSION_ID="13"\n')), \ - mock.patch.object(setup, "download") as download, \ - mock.patch.object(setup, "run", side_effect=fake_run), \ - contextlib.redirect_stdout(io.StringIO()): - nvcc, _ = setup.install_build_tools({"arch": "86", "archs": [86]}, True) - self.assertEqual(nvcc, "/usr/local/cuda-13.1/bin/nvcc") - self.assertIn("repos/debian13/x86_64/cuda-keyring_1.1-1_all.deb", download.call_args[0][0]) - self.assertEqual(installed[-2:], ["cuda-toolkit-13-0", "cuda-toolkit-13-1"]) - - def test_ubuntu_still_installs_exactly_13_0(self): - installed = [] - - def fake_run(cmd, **kw): - if cmd[0:2] == ["sudo", "apt-get"] and cmd[2] == "install": - installed.append(cmd[-1]) - return types.SimpleNamespace(returncode=0) - - with mock.patch.object(setup, "WIN", False), \ - mock.patch.object(setup, "find_nvcc", side_effect=[(None, (0, 0)), ("/usr/local/cuda-13.0/bin/nvcc", (13, 0))]), \ - mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ - mock.patch("builtins.open", mock.mock_open(read_data='ID=ubuntu\nVERSION_ID="24.04"\n')), \ - mock.patch.object(setup, "download"), \ - mock.patch.object(setup, "run", side_effect=fake_run), \ - contextlib.redirect_stdout(io.StringIO()): - setup.install_build_tools({"arch": "86", "archs": [86]}, True) - self.assertEqual(installed, ["cuda-toolkit-13-0"]) - - def test_debian_without_any_13_x_stops_with_guidance(self): - out = io.StringIO() - with mock.patch.object(setup, "WIN", False), \ - mock.patch.object(setup, "find_nvcc", return_value=(None, (0, 0))), \ - mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ - mock.patch("builtins.open", mock.mock_open(read_data='ID=debian\nVERSION_ID="12"\n')), \ - mock.patch.object(setup, "download"), \ - mock.patch.object(setup, "run", return_value=types.SimpleNamespace(returncode=100)), \ - contextlib.redirect_stdout(out): - with self.assertRaises(SystemExit): - setup.install_build_tools({"arch": "86", "archs": [86]}, True) - self.assertIn("no cuda-toolkit-13-x package", out.getvalue()) - - def test_ubuntu_install_failure_still_stops_setup(self): - def fake_run(cmd, check=True, **kw): - failed = cmd[-1] == "cuda-toolkit-13-0" - if failed and check: - raise SystemExit(1) # setup.run's own fail() on a checked command - return types.SimpleNamespace(returncode=100 if failed else 0) - - with mock.patch.object(setup, "WIN", False), \ - mock.patch.object(setup, "find_nvcc", return_value=(None, (0, 0))), \ - mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ - mock.patch("builtins.open", mock.mock_open(read_data='ID=ubuntu\nVERSION_ID="22.04"\n')), \ - mock.patch.object(setup, "download"), \ - mock.patch.object(setup, "run", side_effect=fake_run), \ - contextlib.redirect_stdout(io.StringIO()): - with self.assertRaises(SystemExit): - setup.install_build_tools({"arch": "86", "archs": [86]}, True) - - def test_unknown_distro_stops_with_guidance(self): - out = io.StringIO() - with mock.patch.object(setup, "WIN", False), \ - mock.patch.object(setup, "find_nvcc", return_value=(None, (0, 0))), \ - mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ - mock.patch("builtins.open", mock.mock_open(read_data='ID=fedora\nVERSION_ID="42"\n')), \ - mock.patch.object(setup, "download", side_effect=AssertionError("download started")), \ - contextlib.redirect_stdout(out): - with self.assertRaises(SystemExit): - setup.install_build_tools({"arch": "86", "archs": [86]}, True) - self.assertIn("Debian 12 / 13", out.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_draft_vocab.py b/tools/test_setup_draft_vocab.py deleted file mode 100644 index 33a7638..0000000 --- a/tools/test_setup_draft_vocab.py +++ /dev/null @@ -1,153 +0,0 @@ -"""Tests for setup.py's draft-vocabulary choice (#287): a setup run again without --draft-vocab keeps the subset the -model's config chose before (cyrillic, fr, en), and refresh_draft_vocab copies the chosen shipped subset. Pure file work -in a temporary folder - no GPU, no downloads, no prompts. - - python -m unittest tools.test_setup_draft_vocab -""" -from __future__ import annotations - -import hashlib -import json -import sys -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -class SavedChoice(unittest.TestCase): - def test_a_config_keeps_its_choice(self): - with tempfile.TemporaryDirectory() as d: - for choice in setup.DRAFT_VOCABS: - p = Path(d) / "strata-x.json" - p.write_text(json.dumps({"args": [], "draft_vocab": choice}), encoding="utf-8") - self.assertEqual(setup.saved_draft_vocab(p), choice) - - def test_no_choice_without_a_valid_config(self): - with tempfile.TemporaryDirectory() as d: - self.assertIsNone(setup.saved_draft_vocab(Path(d) / "missing.json")) - for text in ("{}", "[1]", "not json", json.dumps({"draft_vocab": "klingon"})): - p = Path(d) / "strata-y.json" - p.write_text(text, encoding="utf-8") - self.assertIsNone(setup.saved_draft_vocab(p), text) - - -class Refresh(unittest.TestCase): - def test_cyrillic_replaces_a_shipped_subset_and_stays(self): - if not (ROOT / "data" / setup.DRAFT_VOCABS["cyrillic"]).exists(): - self.skipTest("data/draft_vocab_cyrillic.bin is not in this checkout") - want = hashlib.sha256((ROOT / "data" / setup.DRAFT_VOCABS["cyrillic"]).read_bytes()).hexdigest() - with tempfile.TemporaryDirectory() as d: - rt = Path(d) - (rt / "draft_vocab.bin").write_bytes((ROOT / "data" / setup.DRAFT_VOCABS["cjk"]).read_bytes()) - setup.refresh_draft_vocab(rt, "cyrillic") - self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want) - setup.refresh_draft_vocab(rt, "cyrillic") # again: nothing changes - self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want) - - - def test_fr_replaces_a_shipped_subset_and_back(self): - # #597: the French subset is a shipped one too - a later --draft-vocab cjk (or en) replaces it again, while a - # subset made by hand stays - data = ROOT / "data" - if not (data / setup.DRAFT_VOCABS["fr"]).exists(): - self.skipTest("data/draft_vocab_fr.bin is not in this checkout") - sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest() # noqa: E731 - with tempfile.TemporaryDirectory() as d: - rt = Path(d) - (rt / "draft_vocab.bin").write_bytes((data / setup.DRAFT_VOCABS["en"]).read_bytes()) - setup.refresh_draft_vocab(rt, "fr") - self.assertEqual(sha(rt / "draft_vocab.bin"), sha(data / setup.DRAFT_VOCABS["fr"])) - setup.refresh_draft_vocab(rt, "cjk") - self.assertEqual(sha(rt / "draft_vocab.bin"), sha(data / setup.DRAFT_VOCABS["cjk"])) - (rt / "draft_vocab.bin").write_bytes(bytes([1, 0, 0, 0])) # made by hand: kept - setup.refresh_draft_vocab(rt, "fr") - self.assertEqual((rt / "draft_vocab.bin").read_bytes(), bytes([1, 0, 0, 0])) - - def test_fr_holds_the_en_subset_in_its_order(self): - # built with tools/draft_vocab.py --base data/draft_vocab_en.bin --corpus ...: the base first, unchanged - from array import array - data = ROOT / "data" - if not (data / setup.DRAFT_VOCABS["fr"]).exists(): - self.skipTest("data/draft_vocab_fr.bin is not in this checkout") - en = list(array("i", (data / setup.DRAFT_VOCABS["en"]).read_bytes())) - fr = list(array("i", (data / setup.DRAFT_VOCABS["fr"]).read_bytes())) - self.assertEqual(fr[:len(en)], en) - self.assertEqual(len(set(fr)), len(fr)) - self.assertEqual(fr[len(en):], sorted(fr[len(en):])) - - -class SharedFolder(unittest.TestCase): - """setup.py --update refreshes the draft subset of every installed config, most recently used first. Two configs - that name one MTP folder: the folder keeps the subset of the one used last, not of the one used longest ago.""" - - def setUp(self): - self.data = ROOT / "data" - if not all((self.data / setup.DRAFT_VOCABS[c]).exists() for c in ("cjk", "cyrillic", "en")): - self.skipTest("the shipped draft subsets are not in this checkout") - self.sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest() # noqa: E731 - - def run_update(self, rt, cfgs): - done: set = set() - for cfg in cfgs: # update_install's loop, newest first - setup.refresh_shared_draft_vocab(cfg, done) - return self.sha(rt / "draft_vocab.bin") - - def test_the_most_recently_used_config_decides(self): - with tempfile.TemporaryDirectory() as d: - rt = Path(d) - (rt / "draft_vocab.bin").write_bytes((self.data / setup.DRAFT_VOCABS["cyrillic"]).read_bytes()) - in_use = {"args": ["--mtp", str(rt), "--spec", "4"], "draft_vocab": "cyrillic"} - older = {"args": ["--mtp", str(rt), "--spec", "4"]} # no key: the default subset (cjk) - self.assertEqual(self.run_update(rt, [in_use, older]), self.sha(self.data / setup.DRAFT_VOCABS["cyrillic"])) - self.assertEqual(self.run_update(rt, [older, in_use]), self.sha(self.data / setup.DRAFT_VOCABS["cjk"])) - - def test_separate_folders_each_keep_their_own(self): - with tempfile.TemporaryDirectory() as d: - a, b = Path(d) / "a", Path(d) / "b" - for rt in (a, b): - rt.mkdir() - (rt / "draft_vocab.bin").write_bytes((self.data / setup.DRAFT_VOCABS["cjk"]).read_bytes()) - done: set = set() - setup.refresh_shared_draft_vocab({"args": ["--mtp", str(a), "--spec", "4"], "draft_vocab": "cyrillic"}, done) - setup.refresh_shared_draft_vocab({"args": ["--mtp", str(b), "--spec", "4"], "draft_vocab": "en"}, done) - self.assertEqual(self.sha(a / "draft_vocab.bin"), self.sha(self.data / setup.DRAFT_VOCABS["cyrillic"])) - self.assertEqual(self.sha(b / "draft_vocab.bin"), self.sha(self.data / setup.DRAFT_VOCABS["en"])) - - def test_a_config_without_a_draft_layer_is_skipped(self): - done: set = set() - setup.refresh_shared_draft_vocab({"args": ["--spec", "0"]}, done) - setup.refresh_shared_draft_vocab({}, done) - self.assertEqual(done, set()) - - -class SmallCardNote(unittest.TestCase): - """#474: a card under 14 GB is told about a smaller draft subset - a note only, and not when one was chosen.""" - - def test_note_on_a_small_card_only(self): - note = setup.draft_vocab_note(12.0, None) - self.assertTrue(note) - self.assertIn("--draft-vocab en", " ".join(note)) - self.assertIn("the draft head does not fit", " ".join(note)) - for vram, chosen in ((16.0, None), (24.0, None), (12.0, "en"), (12.0, "cyrillic"), (12.0, "fr"), (12.0, "cjk"), - (0.0, None)): - self.assertEqual(setup.draft_vocab_note(vram, chosen), [], (vram, chosen)) - - def test_sizes_follow_the_shipped_subsets(self): - # the MiB the note gives scale with the subsets' token counts (4 bytes per token id in data/) - sizes = {} - for choice, name in setup.DRAFT_VOCABS.items(): - p = ROOT / "data" / name - if not p.exists(): - self.skipTest(f"data/{name} is not in this checkout") - sizes[choice] = p.stat().st_size // 4 - for choice in ("en", "cyrillic", "fr"): - want = setup.DRAFT_VOCAB_MIB["cjk"] * sizes[choice] / sizes["cjk"] - self.assertAlmostEqual(setup.DRAFT_VOCAB_MIB[choice], want, delta=3) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_engine_hash.py b/tools/test_setup_engine_hash.py deleted file mode 100644 index 7a99ce8..0000000 --- a/tools/test_setup_engine_hash.py +++ /dev/null @@ -1,390 +0,0 @@ -"""Tests for setup.py's verification of the ready-made engine archive against its published SHA-256. - -`get_prebuilt()` used to install the engine on nothing more than the byte count matching the server's -Content-Length, so a substituted file of the same length passed. These cover the check that closes that, the -refusal and what a refusal does to the caller, the cases where there is nothing published to check against, -and the order it happens in - it must run before the archive is opened, or a wrong engine still reaches the -disk. Mocked network - nothing is downloaded. - - python -m unittest tools.test_setup_engine_hash -""" - -from __future__ import annotations - -import hashlib -import io -import json -import os -import sys -import tempfile -import unittest -import zipfile -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) - -import setup # noqa: E402 - -ASSET = "strata-windows-x64.zip" -HIP_ASSET = "strata-windows-x64-hip.zip" -TAG_BASE = "https://github.com/Niko1221/Strata/releases/download/v0.1.40/" -LATEST_BASE = "https://github.com/Niko1221/Strata/releases/latest/download/" -FORK_BASE = "https://github.com/someone/PolyStrata/releases/download/v1.0/" -LOCAL_BASE = r"C:\my\mirror" - - -def zip_bytes() -> bytes: - """A stand-in engine archive. Small; its hash is what matters, not its size.""" - buf = io.BytesIO() - with zipfile.ZipFile(buf, "w") as zf: - zf.writestr("strata.exe", b"not a real engine") - zf.writestr("BUILD.json", b'{"version": "0.1.40"}') - return buf.getvalue() - - -def sha_of(b: bytes) -> str: - return hashlib.sha256(b).hexdigest() - - -class WhereTheHashComesFrom(unittest.TestCase): - """`release_of` and `is_local`: which base names a published release, and which is the user's own disk.""" - - def test_a_tag_url_names_its_tag(self): - self.assertEqual(setup.release_of(TAG_BASE), - ("https://api.github.com/repos/Niko1221/Strata/releases", "0.1.40")) - - def test_the_latest_url_names_no_tag(self): - self.assertEqual(setup.release_of(LATEST_BASE), - ("https://api.github.com/repos/Niko1221/Strata/releases", None)) - - def test_a_fork_names_the_fork_not_this_repository(self): - # The repository used to be hardcoded, so a fork's own tag was looked up under Niko1221/Strata, - # where it does not exist - every fork install would be refused. - self.assertEqual(setup.release_of(FORK_BASE), - ("https://api.github.com/repos/someone/PolyStrata/releases", "1.0")) - - def test_something_that_is_not_a_github_release_url_names_nothing(self): - # This is the case that mattered: a local folder or a plain mirror used to match no tag, fall - # through to releases/latest, and be checked against a release the user did not ask for. - for base in (LOCAL_BASE, "https://mirror.invalid/dl/", "/mnt/mirror", "\\\\share\\engine"): - self.assertIsNone(setup.release_of(base), base) - - def test_a_local_folder_is_local_and_a_remote_mirror_is_not(self): - # The distinction the policy turns on: nothing is between a local file and setup; a remote mirror - # has a network in the middle and still no release to check against. - for base in (LOCAL_BASE, r"C:\\mirror", "/mnt/mirror", "file:///srv/engine", - r"\\\\share\\engine"): - self.assertTrue(setup.is_local(base), base) - for base in (setup.PREBUILT_URL, TAG_BASE, FORK_BASE, "https://mirror.invalid/dl/", - "http://example.invalid/engine/"): - self.assertFalse(setup.is_local(base), base) - - def test_a_local_folder_asks_the_api_nothing_at_all(self): - # Air-gapped and shared-IP installs must not depend on GitHub answering. - with mock.patch.object(setup.urllib.request, "urlopen", - side_effect=AssertionError("the API was called")): - self.assertIsNone(setup.engine_digest(ASSET, LOCAL_BASE)) - - -class DigestLookup(unittest.TestCase): - """`engine_digest`: the size and hash for one asset, from the releases API.""" - - def release_json(self, tag, assets): - return json.dumps({"tag_name": tag, "assets": assets}).encode("utf-8") - - def asked(self, payload): - """Patch urlopen with a fake that serves `payload`; returns the list the URL goes into. - - A list rather than a mock, because patching urlopen with a plain function hands back the function, - and the URL asked for is part of what is under test. - """ - seen = [] - - class R: - def __init__(self, data): - self._b = io.BytesIO(data) - - def read(self, *a): - return self._b.read(*a) - - def __enter__(self): - return self - - def __exit__(self, *a): - return False - - def open_it(req, timeout=None): - seen.append(req.full_url) - return R(payload) - - patcher = mock.patch.object(setup.urllib.request, "urlopen", open_it) - patcher.start() - self.addCleanup(patcher.stop) - return seen - - def test_reads_the_tag_out_of_the_download_url(self): - # The URL already names the release, so the API call must ask for THAT release and not "latest": - # the tag URL is tried first (#214) so a checkout normally gets its own version's engine. - seen = self.asked(self.release_json( - "v0.1.40", [{"name": ASSET, "size": 42, "digest": "sha256:" + "a" * 64}])) - self.assertEqual(setup.engine_digest(ASSET, TAG_BASE), (42, "a" * 64)) - self.assertEqual(seen, ["https://api.github.com/repos/Niko1221/Strata/releases/tags/v0.1.40"]) - - def test_latest_when_the_url_says_latest(self): - seen = self.asked(self.release_json( - "v0.1.40.1", [{"name": ASSET, "size": 7, "digest": "sha256:" + "b" * 64}])) - setup.engine_digest(ASSET, LATEST_BASE) - self.assertEqual(seen, ["https://api.github.com/repos/Niko1221/Strata/releases/latest"]) - - def test_asks_the_fork_for_a_fork_url(self): - seen = self.asked(self.release_json( - "v1.0", [{"name": ASSET, "size": 9, "digest": "sha256:" + "c" * 64}])) - self.assertEqual(setup.engine_digest(ASSET, FORK_BASE), (9, "c" * 64)) - self.assertIn("/repos/someone/PolyStrata/releases/tags/v1.0", seen[0]) - - def test_none_when_no_digest_is_published(self): - # No digest is not a pass. The caller refuses. - self.asked(self.release_json("v0.1.40", [{"name": ASSET, "size": 42}])) - self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE)) - - def test_none_when_the_digest_is_not_a_sha256(self): - for other in ("md5:" + "d" * 32, "sha512:" + "e" * 128, "", None): - self.asked(self.release_json("v0.1.40", - [{"name": ASSET, "size": 42, "digest": other}])) - self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE), other) - - def test_none_when_the_asset_is_not_in_that_release(self): - # A CUDA 12 asset asked for on a release that has none, or a renamed asset. Refuse, do not verify - # against some other file's hash. - self.asked(self.release_json("v0.1.40", - [{"name": "other.zip", "size": 1, "digest": "sha256:" + "f" * 64}])) - self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE)) - - def test_none_when_github_cannot_be_reached(self): - for exc in (OSError("no network"), TimeoutError("slow")): - with mock.patch.object(setup.urllib.request, "urlopen", side_effect=exc): - self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE), exc) - - def test_picks_the_asset_the_url_actually_wants(self): - # v0.1.40.1 ships several engine builds with different hashes; the one asked for must be the one - # used, not whichever the API lists first. - self.asked(self.release_json("v0.1.40.1", [ - {"name": "strata-windows-x64.zip", "size": 1, "digest": "sha256:" + "1" * 64}, - {"name": "strata-windows-x64-cuda12.zip", "size": 2, "digest": "sha256:" + "2" * 64}, - {"name": HIP_ASSET, "size": 3, "digest": "sha256:" + "3" * 64}, - ])) - self.assertEqual(setup.engine_digest("strata-windows-x64-cuda12.zip", LATEST_BASE), (2, "2" * 64)) - self.assertEqual(setup.engine_digest(HIP_ASSET, LATEST_BASE), (3, "3" * 64)) - - -class ArchiveVerification(unittest.TestCase): - """`verify_engine_archive`: the downloaded file against the published size and hash.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.z = Path(self.tmp.name) / ASSET - self.data = zip_bytes() - self.z.write_bytes(self.data) - patch = mock.patch.dict(os.environ, {}, clear=False) - env = patch.start() - self.addCleanup(patch.stop) - env.pop("STRATA_SKIP_SHA256", None) - - def digest(self, value): - return mock.patch.object(setup, "engine_digest", return_value=value) - - def test_passes_when_the_hash_matches(self): - with self.digest((len(self.data), sha_of(self.data))): - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) # must not raise - self.assertTrue(self.z.exists()) - - def test_refuses_a_wrong_hash_and_deletes_the_file(self): - # A wrong engine left on disk is the thing this exists to prevent, so it goes. - with self.digest((len(self.data), "0" * 64)): - with self.assertRaises(setup.UnverifiedEngine) as caught: - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - self.assertIn("wrong SHA-256", str(caught.exception)) - self.assertFalse(self.z.exists()) - self.assertFalse(self.z.with_name(self.z.name + ".done").exists()) - - def test_refuses_a_wrong_size_before_hashing(self): - with self.digest((len(self.data) + 1, sha_of(self.data))): - with self.assertRaises(setup.UnverifiedEngine) as caught: - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - self.assertIn("not the published", str(caught.exception)) - self.assertFalse(self.z.exists()) - - def test_a_same_size_impostor_is_caught_by_the_hash_alone(self): - # The case Content-Length cannot see, and the reason the hash is there at all. - impostor = b"x" * len(self.data) - self.z.write_bytes(impostor) - with self.digest((len(impostor), sha_of(self.data))): - with self.assertRaises(setup.UnverifiedEngine): - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - self.assertFalse(self.z.exists()) - - def test_no_digest_warns_and_installs_anyway(self): - # "recommend, never force": no digest (offline, rate limit, mirror, folder) is a warning, not a refusal. - for base in (TAG_BASE, LOCAL_BASE, "https://mirror.invalid/dl/"): - said = io.StringIO() - with self.digest(None), mock.patch.object(setup, "warn", said.write): - setup.verify_engine_archive(self.z, ASSET, base) # must not raise - self.assertIn("NOT verified", said.getvalue(), base) - self.assertTrue(self.z.exists()) - - def test_skip_env_skips_the_check_loudly(self): - os.environ["STRATA_SKIP_SHA256"] = "1" - said = io.StringIO() - with mock.patch.object(setup, "engine_digest", return_value=(1, "0" * 64)) as m, mock.patch.object(setup, "warn", said.write): - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) # a wrong digest, but skipped - self.assertEqual(m.call_count, 0) - self.assertIn("STRATA_SKIP_SHA256", said.getvalue()) - self.assertIn("NOT checking", said.getvalue()) - self.assertTrue(self.z.exists()) - - def test_skip_env_needs_exactly_1(self): - os.environ["STRATA_SKIP_SHA256"] = "0" - with self.digest((1, "0" * 64)): - with self.assertRaises(setup.UnverifiedEngine): - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - - def test_a_truncated_archive_is_refused(self): - # There is no finish mark any more, so nothing can vouch for a file that changed after it was - # checked. Measured cost of that decision: 190 MB hashes in 0.79 s at 242 MB/s on this machine, - # against 3.0 s to download the same file, so re-checking is not worth saving. - with self.digest((len(self.data), sha_of(self.data))): - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - with open(self.z, "r+b") as f: - f.truncate(len(self.data) // 2) - with self.assertRaises(setup.UnverifiedEngine) as caught: - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - self.assertIn("not the published", str(caught.exception)) - - def test_a_same_length_change_after_verification_is_refused(self): - # The hole the mark left: same length, so the size check passes, and the mark would have vouched - # for it. With no mark, the hash is recomputed and it is caught. - with self.digest((len(self.data), sha_of(self.data))): - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - with open(self.z, "r+b") as f: - f.seek(0) - f.write(b"X") - with self.assertRaises(setup.UnverifiedEngine) as caught: - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - self.assertIn("wrong SHA-256", str(caught.exception)) - - def test_the_api_is_asked_once_not_twice(self): - # It is a rate-limited API and an install is not the place to spend two calls on one lookup. - with mock.patch.object(setup, "engine_digest", - return_value=(len(self.data), sha_of(self.data))) as m: - setup.verify_engine_archive(self.z, ASSET, TAG_BASE) - self.assertEqual(m.call_count, 1, f"engine_digest was called {m.call_count} times") - - -class WhatARefusalDoesToTheCaller(unittest.TestCase): - """`engine_refused`, and the paths that call it. - - This is where the adversarial pass found the worst bug: a refusal used to end in `fail()`, i.e. - `sys.exit(1)`, which is a BaseException, so the engine-UPDATE paths' `except Exception` could not catch - it and setup died instead of starting with the engine it already had. - """ - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - (Path(self.tmp.name) / "engine").mkdir(parents=True, exist_ok=True) - # engine/ is the temporary one, and the HEAD request that finds the asset published always succeeds - eng = Path(self.tmp.name) / "engine" - for p in (mock.patch.object(setup, "engine_dir", lambda toolkit=13: eng), - mock.patch.object(setup.urllib.request, "urlopen", return_value=mock.MagicMock())): - p.start() - self.addCleanup(p.stop) - - def fake_download(self, url, dst, what=None): - with zipfile.ZipFile(dst, "w") as z: - z.writestr("BUILD.json", json.dumps({"version": "0.1.40", "archs": [89]})) - z.writestr(setup.EXE, b"engine") - - def get_prebuilt(self, updating, digest): - out = io.StringIO() - with contextlib_redirect(out), mock.patch.object(setup, "download", self.fake_download), mock.patch.object(setup, "engine_digest", return_value=digest): - return setup.get_prebuilt(setup.PREBUILT_URL, {"arch": 89}, "gpu", updating=updating), out - - def test_updating_keeps_the_installed_engine_instead_of_stopping(self): - # The call site's own words: "a failed download must not stop the model from starting". - for digest in ((999, "f" * 64), (1, "0" * 64)): - eng, out = self.get_prebuilt(updating=True, digest=digest) - self.assertIsNone(eng, f"digest={digest!r} did not return None") - self.assertNotIn("Setup stopped", out.getvalue(), - "a refusal while updating must not claim setup stopped") - self.assertIn("keeping the engine that is installed", out.getvalue()) - - def test_a_refusal_is_an_exception_the_update_path_can_catch(self): - # The regression guard for the actual bug: SystemExit escaped this guard before. - self.assertTrue(issubclass(setup.UnverifiedEngine, Exception)) - self.assertFalse(issubclass(SystemExit, Exception)) - eng, _ = self.get_prebuilt(updating=True, digest=(999, "f" * 64)) - self.assertIsNone(eng, "a refusal must not escape get_prebuilt as SystemExit") - - def test_a_first_install_stops_because_there_is_nothing_to_fall_back_to(self): - with mock.patch.object(setup, "download", self.fake_download), mock.patch.object(setup, "engine_digest", return_value=(999, "f" * 64)): - with self.assertRaises(SystemExit): - setup.get_prebuilt(setup.PREBUILT_URL, {"arch": 89}, "gpu") - - def test_the_cuda_and_amd_paths_both_verify(self): - # get_prebuilt_hip downloads the AMD engine from a SECOND `download(base + ...)` call site, which - # the first version of this change missed entirely - so AMD users got nothing from it. - src = (ROOT / "setup.py").read_text(encoding="utf-8") - for call in ('download(base + asset, z, "PolyStrata engine")', - 'download(base + WIN_HIP_ASSET, z, "PolyStrata AMD engine")'): - i = src.index(call) - self.assertIn("verify_engine_archive", src[i:i + 400], f"{call} is not verified") - - -class Wiring(unittest.TestCase): - """The check is reached, and reached before the archive is opened.""" - - def test_get_prebuilt_verifies_before_it_unpacks(self): - src = (ROOT / "setup.py").read_text(encoding="utf-8") - body = src[src.index("def get_prebuilt("):] - body = body[:body.index("\ndef ")] - i_verify = body.index("verify_engine_archive(") - for opener in ("ZipFile(", "_unpack", "install_unpacked"): - self.assertGreater(body.index(opener), i_verify, - f"{opener} happens before the SHA-256 is checked") - - def test_the_digest_is_read_from_the_api_not_the_download_host(self): - src = (ROOT / "setup.py").read_text(encoding="utf-8") - # release_of() builds the API URL, from the OWNER/REPO in the download URL - so a mirror of this - # repository is checked against this repository's published hash, not against whatever the mirror - # happens to be serving. - body = src[src.index("def release_of("):] - body = body[:body.index("\ndef ")] - self.assertIn("api.github.com/repos/", body) - self.assertIn("m.group(1)", body, "the repository comes out of the URL, not a constant") - # and engine_digest asks release_of rather than the download URL - body = src[src.index("def engine_digest("):] - body = body[:body.index("\ndef ")] - self.assertIn("release_of(base)", body) - - -class contextlib_redirect: - """stdout into a StringIO, without importing contextlib under a name setup.py also uses.""" - - def __init__(self, buf): - self.buf = buf - - def __enter__(self): - self.old = sys.stdout - sys.stdout = self.buf - return self - - def __exit__(self, *a): - sys.stdout = self.old - return False - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_engine_keep.py b/tools/test_setup_engine_keep.py deleted file mode 100644 index 8b5c634..0000000 --- a/tools/test_setup_engine_keep.py +++ /dev/null @@ -1,105 +0,0 @@ -"""#670: an engine update keeps the engine it replaces in engine/.previous (one generation), the swap is all or -nothing, and `setup.py --rollback-engine` puts the kept one back. - - python -m unittest tools.test_setup_engine_keep -""" -from __future__ import annotations - -import json -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - - -def engine(folder: Path, version: str, exe: bytes) -> None: - folder.mkdir(parents=True, exist_ok=True) - (folder / "BUILD.json").write_text(json.dumps({"version": version}), encoding="utf-8") - (folder / "strata.exe").write_bytes(exe) - (folder / "lib").mkdir(exist_ok=True) - (folder / "lib" / "x.dll").write_bytes(exe) - - -class KeepPrevious(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - self.eng = self.root / "engine" - self.new = self.eng / "_unpack" - - def test_the_replaced_engine_is_kept_and_rolled_back(self): - engine(self.eng, "0.1.39", b"old") - engine(self.new, "0.1.40", b"new") - setup.install_unpacked(self.new, self.eng) - self.assertEqual((self.eng / "strata.exe").read_bytes(), b"new") - self.assertEqual(setup.engine_version_of(self.eng), "0.1.40") - prev = self.eng / ".previous" - self.assertEqual((prev / "strata.exe").read_bytes(), b"old") - self.assertEqual((prev / "lib" / "x.dll").read_bytes(), b"old") - self.assertEqual(setup.engine_version_of(prev), "0.1.39") - with mock.patch.object(setup, "ROOT", self.root): - self.assertEqual(setup.rollback_engine(), 0) - self.assertEqual((self.eng / "strata.exe").read_bytes(), b"old") - self.assertEqual(setup.engine_version_of(self.eng), "0.1.39") - self.assertEqual(setup.engine_version_of(prev), "0.1.40") # forward again - self.assertEqual(setup.rollback_engine(), 0) - self.assertEqual((self.eng / "strata.exe").read_bytes(), b"new") - - def test_previous_keeps_its_build_json_after_get_prebuilt_moved_it_aside(self): - """get_prebuilt takes the old BUILD.json out of the way (BUILD.json.prev) before the unpack, so the - engine kept in .previous still says its version instead of '?'.""" - engine(self.eng, "0.1.39", b"old") - (self.eng / "BUILD.json").replace(self.eng / "BUILD.json.prev") - engine(self.new, "0.1.40", b"new") - setup.install_unpacked(self.new, self.eng) - self.assertEqual(setup.engine_version_of(self.eng / ".previous"), "0.1.39") - self.assertFalse((self.eng / "BUILD.json.prev").exists()) - self.assertEqual(setup.engine_version_of(self.eng), "0.1.40") - - def test_one_generation_only(self): - engine(self.eng, "0.1.38", b"a") - for version, exe in (("0.1.39", b"b"), ("0.1.40", b"c")): - engine(self.new, version, exe) - setup.install_unpacked(self.new, self.eng) - for p in self.new.iterdir(): # (get_prebuilt removes what is left of the unpack) - p.unlink() if p.is_file() else None - self.assertEqual(setup.engine_version_of(self.eng / ".previous"), "0.1.39") - - def test_a_first_install_keeps_nothing(self): - self.eng.mkdir() - engine(self.new, "0.1.40", b"new") - setup.install_unpacked(self.new, self.eng) - self.assertEqual((self.eng / "strata.exe").read_bytes(), b"new") - self.assertFalse((self.eng / ".previous").exists()) - with mock.patch.object(setup, "ROOT", self.root): - self.assertEqual(setup.rollback_engine(), 1) - - def test_a_failure_part_way_leaves_the_old_engine_whole(self): - engine(self.eng, "0.1.39", b"old") - engine(self.new, "0.1.40", b"new") - real = Path.replace - calls = [] - - def flaky(self_, target): - calls.append(self_.name) - if len(calls) == 2: - raise PermissionError("held open") - return real(self_, target) - - with mock.patch.object(Path, "replace", flaky), self.assertRaises(OSError): - setup.install_unpacked(self.new, self.eng) - self.assertEqual((self.eng / "strata.exe").read_bytes(), b"old") - self.assertEqual((self.eng / "lib" / "x.dll").read_bytes(), b"old") - self.assertEqual(setup.engine_version_of(self.eng), "0.1.39") - self.assertFalse((self.eng / ".previous").exists()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_gguf_models.py b/tools/test_setup_gguf_models.py deleted file mode 100644 index 3dbfb28..0000000 --- a/tools/test_setup_gguf_models.py +++ /dev/null @@ -1,290 +0,0 @@ -"""Tests for setup.py's Qwen3.6-35B-A3B, Ornith 1.5, Gemma 4 26B-A4B and Tiel Coder (docs/BACKENDS.md): the pinned -files, the estimates for a small card, and that each is installed by GLM's steps with nothing of GLM's own (no shipped -expert profile, no draft block to fetch). Mocked like tools/test_setup_glm.py, whose harness this uses. - - python -m unittest tools.test_setup_gguf_models -""" -from __future__ import annotations - -import json -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 -from tools import test_setup_glm as glm_tests # noqa: E402 (the module: its test classes are not this file's) - -# family: (size, file, repository, bytes) of the size setup takes when the PC has the RAM for it -NEW = { - "qwen36": ("UD-Q3_K_M", "Qwen3.6-35B-A3B-UD-Q3_K_M.gguf", "unsloth/Qwen3.6-35B-A3B-MTP-GGUF", 17104402720), - "ornith": ("APEX-I-COMPACT", "Ornith-1.5-35B-A3B-APEX-MTP-I-Compact.gguf", - "mudler/Ornith-1.5-35B-A3B-APEX-MTP-GGUF", 17437861408), - "gemma4": ("UD-Q3_K_M", "gemma-4-26B-A4B-it-UD-Q3_K_M.gguf", "unsloth/gemma-4-26B-A4B-it-GGUF", 12728497888), - "tiel": ("UD-Q3_K_XL", "Tiel-Coder-35B-A3B-MTP-UD-Q3_K_XL.gguf", "peculiar-ragdoll/Tiel-Coder-35B-A3B-GGUF-MTP", - 17234935648), -} -# family: its other sizes in setup's order, the smaller and then the larger: (size, file, bytes) -MORE = { - "qwen36": [("UD-Q2_K_XL", "Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf", 12574128416), - ("UD-Q4_K_M", "Qwen3.6-35B-A3B-UD-Q4_K_M.gguf", 22663387424)], - "ornith": [("APEX-I-MINI", "Ornith-1.5-35B-A3B-APEX-MTP-I-Mini.gguf", 14366220832), - ("APEX-I-QUALITY", "Ornith-1.5-35B-A3B-APEX-MTP-I-Quality.gguf", 23718411808)], - "gemma4": [("UD-Q2_K_XL", "gemma-4-26B-A4B-it-UD-Q2_K_XL.gguf", 10546934240), - ("UD-Q4_K_M", "gemma-4-26B-A4B-it-UD-Q4_K_M.gguf", 16947541728)], - "tiel": [("UD-IQ3_XXS", "Tiel-Coder-35B-A3B-MTP-UD-IQ3_XXS.gguf", 13600579424), - ("UD-Q4_K_XL", "Tiel-Coder-35B-A3B-MTP-UD-Q4_K_XL.gguf", 22749880160)], -} - - -class Pins(unittest.TestCase): - def test_the_files(self): - for family, (size0, file0, repo, n0) in NEW.items(): - sizes = [(size0, file0, n0), *MORE[family]] - fam = setup.FAMILIES[family] - self.assertEqual(fam["engine"], "poly", family) - self.assertRegex(fam["hf"], rf"^https://huggingface.co/{repo}/resolve/[0-9a-f]{{40}}/$") - self.assertEqual(list(setup.family_models(family)), [size for size, _, _ in sizes]) - more = [] # a draft model the sizes share - for size, file, n in sizes: - self.assertEqual((setup.model_file(fam, size, 1), setup.model_shards(fam, size)), (file, 1)) - d = fam["models"][size] - more = [Path(d["draft_model"]).name] if d.get("draft_model") else [] - self.assertEqual(fam["sha256"][file][0], n) - self.assertAlmostEqual(sum(fam["sha256"][f][0] for f in [file, *more]) / 1e9, d["download_gb"], - delta=0.05) - self.assertLess(d["arena_gb"], d["download_gb"]) # the experts are part of the file - self.assertEqual(d["ram_gb"], round(setup.poly_ram_need(d, 8.0)), size) - # the image encoder is pinned too; it is downloaded when images are wanted, so it has its own size - self.assertEqual(list(fam["sha256"]), [*(file for _, file, _ in sizes), *more, fam["mmproj"]]) - for pinned in fam["sha256"].values(): - self.assertRegex(pinned[1], r"^[0-9a-f]{64}$") - self.assertAlmostEqual(fam["sha256"][fam["mmproj"]][0] / 1e9, fam["vision_gb"], delta=0.05) - - def test_two_families_have_a_size_of_one_name(self): - q, g = setup.FAMILIES["qwen36"]["models"]["UD-Q3_K_M"], setup.FAMILIES["gemma4"]["models"]["UD-Q3_K_M"] - self.assertNotEqual(q["download_gb"], g["download_gb"]) - self.assertNotIn("UD-Q3_K_M", setup.MODELS) # the other families' sizes are not theirs - for f in ("qwen", "swift", "coder", "unsloth", "glm"): - self.assertNotIn("UD-Q3_K_M", setup.family_models(f), f) - - def test_tags_tell_the_families_apart(self): - tags = [d["tag"] for d in setup.FAMILIES.values() if d["tag"]] - for a in tags: - self.assertEqual([b for b in tags if b.startswith(a)], [a]) - - -class Estimates(unittest.TestCase): - def test_a_32_gb_card_holds_every_expert(self): - for family in NEW: - for d in setup.family_models(family).values(): - self.assertEqual(setup.poly_held_gb(d, 31.84), d["arena_gb"], family) - self.assertEqual(setup.poly_ram_need(d, 31.84), setup.POLY_RAM_BESIDE_GB) - - def test_an_8_gb_card(self): - # what the families' menu lines say of an 8 GB card - need = {f: setup.poly_ram_need(next(iter(setup.family_models(f).values())), 8.0) for f in NEW} - self.assertAlmostEqual(need["qwen36"], 21, delta=0.5) - self.assertAlmostEqual(need["ornith"], 22, delta=0.5) - self.assertAlmostEqual(need["gemma4"], 18, delta=0.5) - self.assertAlmostEqual(need["tiel"], 21, delta=0.5) - for f, n in need.items(): - self.assertIn(f"~{n:.0f} GB of RAM beside an 8 GB card", setup.FAMILIES[f]["about"]) - self.assertEqual(next(iter(setup.family_models(f).values()))["ram_gb"], round(n)) - - def test_check_lines(self): - d = setup.FAMILIES["qwen36"]["models"]["UD-Q3_K_M"] - self.assertIn("fits by setup's estimate (~21 GB of RAM", setup.poly_verdict(d, 32, 8.0, False)) - self.assertIn("read from the SSD", setup.poly_verdict(d, 12, 8.0, False)) - self.assertIn("does not fit", setup.poly_verdict(d, 64, 6.0, False)) - with mock.patch.object(setup, "WIN", False): # #11: AMD on Linux runs it - self.assertNotIn("does not run", setup.poly_verdict(d, 64, 24.0, True)) - with mock.patch.object(setup, "WIN", True): # a family that has run on Windows is not said to be untried - self.assertIn("AMD", setup.poly_verdict(d, 64, 24.0, True)) # only AMD on Windows is left out - self.assertIn("not tried on Windows", setup.poly_verdict(d, 32, 8.0, False)) - self.assertNotIn("not tried on Windows", setup.poly_verdict(d, 32, 8.0, False, True)) - - -class Config(unittest.TestCase): - def test_choices_from_config(self): - with tempfile.TemporaryDirectory() as t: - for family, (size, *_rest) in NEW.items(): - p = Path(t) / f"strata-{setup.FAMILIES[family]['tag']}{size.lower()}.json" - p.write_text(json.dumps({"exe": "/x/engine-poly/" + setup.POLY_EXE, "args": ["--max-context", "8192"]})) - ch = setup.choices_from_config(p) - self.assertEqual((ch["family"], ch["model"], ch["context"]), (family, size, 8192)) - - -class Main(unittest.TestCase): - """setup.main() for the four families, every outside effect mocked.""" - setUp, tearDown, main = glm_tests.Main.setUp, glm_tests.Main.tearDown, glm_tests.Main.main - - def test_install(self): - for family, (size, file, _repo, _n) in NEW.items(): - with self.subTest(family): - self.downloads, self.runs, self.verified = [], [], [] - code, out, cfg = self.main(family=family, ram=32.0, vram=8188 / 1024) # what an 8 GB card reports - self.assertEqual(code, 0, out) - fam = setup.FAMILIES[family] - guesser = fam["models"][size].get("draft_model") # Gemma 4's: a second file, beside the model's - more = [Path(guesser).name] if guesser else [] - self.assertEqual(self.downloads, [fam["hf"] + file] + ([fam["hf"] + guesser] if guesser else [])) - self.assertEqual(self.verified, [(f, *fam["sha256"][f]) for f in [file, *more]]) - tag = fam["tag"] + size - pack = self.t / "data" / "packs" / tag.lower() - # the tokenizer alone: no draft block is fetched for these - self.assertEqual([Path(r[1]).name for r in self.runs], ["strata_tokenizer.py"]) - self.assertEqual(self.runs[0][self.runs[0].index("--out") + 1], str(pack)) - args = cfg["args"] - self.assertEqual(Path(args[args.index("--model") + 1]), self.t / "models" / tag / file) - self.assertEqual(Path(args[args.index("--expert-profile") + 1]), pack / "expert-profile.txt") - self.assertFalse((pack / "expert-profile.txt").exists()) # none is shipped: the engine starts it - if guesser: - self.assertEqual(Path(args[args.index("--draft-model") + 1]), - self.t / "models" / tag / more[0]) - else: - self.assertNotIn("--draft-model", args) # theirs is in the model's file - if family == "qwen36": # the others' answers move more (docs/BACKENDS.md) - self.assertEqual(args[args.index("--tail-skip") + 1], "6") - else: - self.assertNotIn("--tail-skip", args) - self.assertEqual(cfg["model_name"], f"{fam['name']}-{size.lower()}") - self.assertEqual(cfg["display_name"], f"{fam['title']} {size}") - self.assertEqual(Path(cfg["exe"]), self.t / setup.ENGINE_POLY_DIR / setup.POLY_EXE) - self.assertIn("experts fit in VRAM (100% on a 32 GB card)", out) - self.assertNotIn("has run on no card", out) # each has run on one of 8 GB - self.assertEqual((self.encoder, cfg.get("vision")), ("none", None)) # --yes: no images - - def test_a_hybrid_cpu_gets_a_thread_count(self): - """The engine's own count is every logical CPU, which is the slowest on a hybrid one.""" - code, out, cfg = self.main(family="gemma4", ram=32.0, vram=8.0, cores=(8, 12)) - self.assertEqual(code, 0, out) - args = cfg["args"] - self.assertEqual(args[args.index("--threads") + 1], "13") - self.assertIn("hybrid CPU (8 performance + 12 efficiency cores): 13 CPU threads", out) - for cores in (None, (8, 8)): - code, out, cfg = self.main(family="gemma4", ram=32.0, vram=8.0, cores=cores) - self.assertEqual(code, 0, out) - self.assertNotIn("--threads", cfg["args"]) - - def test_images(self): - for family, (size, file, _repo, _n) in NEW.items(): - fam = setup.FAMILIES[family] - folder = self.t / "models" / (fam["tag"] + size) - # (the card's VRAM, --vision) -> where the encoder runs: a small card keeps its VRAM for the model - for vram, asked, where in ((31.84, "yes", "gpu"), (8.0, "yes", "cpu"), (12.0, "gpu", "gpu")): - with self.subTest(family=family, vram=vram, asked=asked): - self.downloads, self.verified = [], [] - code, out, cfg = self.main(["--vision", asked], family=family, ram=64.0, vram=vram) - self.assertEqual(code, 0, out) - self.assertEqual(self.encoder, where) - if vram > 30: # the first run: the encoder is the last file fetched - self.assertEqual(self.downloads[-1], fam["mmproj_hf"] + fam["mmproj"]) - self.assertEqual(self.verified[-1], (fam["mmproj"], *fam["sha256"][fam["mmproj"]])) - v = cfg["vision"] - self.assertEqual((Path(v["exe"]), Path(v["mmproj"]), Path(v["model"]), v["gpu"]), - (self.t / setup.ENGINE_POLY_DIR / setup.VEXE, folder / fam["mmproj"], - folder / file, where == "gpu")) - self.assertEqual(v["max_tokens"], setup.VISION[where]["max_tokens"]) - self.assertEqual("threads" in v, where == "cpu") - self.assertIn("images: on" + (" (encoder on the CPU)" if where == "cpu" else ""), out) - # the encoder was downloaded once, beside the model's file, and found there afterwards - self.assertTrue((folder / fam["mmproj"]).exists()) - self.assertEqual(self.downloads, []) - # the encoder on the GPU leaves less VRAM to the experts, and the estimate says so - need = {} - for asked in ("no", "gpu"): - code, out, cfg = self.main(["--vision", asked], family="gemma4", ram=64.0, vram=16.0, - answers={}) - need[asked] = out - self.assertIn("about 10 of", need["no"]) - self.assertIn("about 8 of", need["gpu"]) - # and on a card it leaves too little of, setup stops and says how to keep it off the card - code, out, cfg = self.main(["--vision", "gpu"], family="gemma4", ram=64.0, vram=8.0) - self.assertNotEqual(code, 0) - self.assertIn("and its image encoder 2.4 GB", out) - self.assertIn("--vision cpu keeps the image encoder off the card", out) - - def test_images_are_asked_about(self): - code, out, cfg = self.main(family="qwen36", ram=64.0, vram=24.0, answers={"Do you want images": "y"}) - self.assertEqual(code, 0, out) - self.assertIn("a 0.9 GB", out) - self.assertEqual((self.encoder, cfg["vision"]["gpu"]), ("gpu", True)) - # GLM 5.3 Flash reads no pictures: it is not asked, and --vision is said to be unused - code, out, cfg = self.main(["--vision", "yes"], family="glm") - self.assertEqual(code, 0, out) - self.assertIn("not used with GLM 5.3 Flash", out) - self.assertNotIn("vision", cfg) - - def test_the_draft_model_beside_files_of_ones_own(self): - size, file, _repo, _n = NEW["gemma4"] - fam = setup.FAMILIES["gemma4"] - guesser = fam["models"][size]["draft_model"] - mine = self.t / "mine" - mine.mkdir() - (mine / file).write_bytes(b"") - # --gguf-dir has the model alone: its draft model is downloaded, to where setup keeps its own files - code, out, cfg = self.main(["--gguf-dir", str(mine)], family="gemma4", ram=32.0, vram=8.0) - self.assertEqual(code, 0, out) - self.assertEqual(self.downloads, [fam["hf"] + guesser]) - args = cfg["args"] - self.assertEqual(Path(args[args.index("--model") + 1]), mine / file) - self.assertEqual(Path(args[args.index("--draft-model") + 1]), - self.t / "models" / (fam["tag"] + size) / Path(guesser).name) - # with both files there, nothing is downloaded and both are used where they are - (mine / Path(guesser).name).write_bytes(b"") - self.downloads, self.verified = [], [] - code, out, cfg = self.main(["--gguf-dir", str(mine)], family="gemma4", ram=32.0, vram=8.0) - self.assertEqual((code, self.downloads), (0, []), out) - self.assertEqual([v[0] for v in self.verified], [file, Path(guesser).name]) - self.assertEqual(Path(cfg["args"][cfg["args"].index("--draft-model") + 1]), mine / Path(guesser).name) - - def test_a_pc_below_the_qwen_models_ram_is_not_stopped(self): - # 24 GB is under what the smallest Qwen3.8 size needs, and enough for these by their own estimate - code, out, cfg = self.main(family="gemma4", ram=24.0, vram=8.0) - self.assertEqual(code, 0, out) - self.assertNotIn("the Coder", out) - self.assertIn("RAM: 24 GB", out) - self.assertIsNotNone(cfg) - - def test_too_little_ram_for_the_model_stops(self): - code, out, cfg = self.main(family="qwen36", ram=12.0, vram=8.0) # too little for its smallest size too - self.assertNotEqual(code, 0) - self.assertIn("wants about 17 GB", out) - self.assertIsNone(cfg) - code, out, cfg = self.main(family="qwen36", ram=12.0, vram=8.0, model="UD-Q3_K_M") # named: a risk taken - self.assertEqual(code, 0, out) - self.assertIn("as you chose", out) - - def test_the_size_taken_without_a_name(self): - """The first size where the PC has the RAM for it, the smaller one where not; the larger one only by name.""" - for ram, size in ((64.0, "UD-Q3_K_M"), (20.0, "UD-Q3_K_M"), (16.0, "UD-Q2_K_XL")): - code, out, cfg = self.main(family="qwen36", ram=ram, vram=8.0) - self.assertEqual(code, 0, out) - self.assertIn(f"size: {size}", out, ram) - code, out, cfg = self.main(family="qwen36", ram=64.0, vram=8.0, model="UD-Q4_K_M") - self.assertEqual(code, 0, out) - self.assertIn("size: UD-Q4_K_M", out) - - def test_a_size_of_another_family_is_refused_by_name(self): - code, out, cfg = self.main(family="gemma4", model="APEX-I-COMPACT") - self.assertNotEqual(code, 0) - self.assertIn("Gemma 4 26B-A4B has no APEX-I-COMPACT model file", out) - self.assertIn("UD-Q3_K_M", out) - code, out, cfg = self.main(family="qwen", model="UD-Q3_K_M") # and the other way: who has it - self.assertNotEqual(code, 0) - self.assertIn("Qwen3.8-Flash-Next has no UD-Q3_K_M model file", out) - self.assertIn("--family qwen36 --model UD-Q3_K_M, --family gemma4 --model UD-Q3_K_M", out) - - def test_the_context_note_is_the_familys(self): - code, out, cfg = self.main(family="gemma4", ram=32.0, vram=8.0, answers={"Context?": "3"}) - self.assertEqual(code, 0, out) - self.assertIn("0.9 GB more VRAM", out) # 65536: 32768 tokens of 28672 bytes more - self.assertEqual(cfg["args"][cfg["args"].index("--max-context") + 1], "65536") - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_glm.py b/tools/test_setup_glm.py deleted file mode 100644 index d832eca..0000000 --- a/tools/test_setup_glm.py +++ /dev/null @@ -1,452 +0,0 @@ -"""Tests for setup.py's GLM 5.3 Flash choice (docs/GLM.md): the pinned file with its size and SHA-256, the steps of -its own setup (no pack, no draft layer, no image encoder), the run config, the conversation cache kept on a second -run, and what setup says about RAM, VRAM and the options of the Qwen engine. Mocked - no GPU, no compile, no -downloads, nothing written outside a temp folder. - - python -m unittest tools.test_setup_glm -""" -from __future__ import annotations - -import contextlib -import io -import json -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - -M = "3.0BIT" -FILE = "GLM-5.3-Flash-GSQ-RCO-3.0bit-q4kattn.gguf" -REV = "7feedfeb5ee924bfbe0064c63b124728b443ddc0" -HALF = "REAP50-Q3_K_M" # half the routed experts, from another repository -HALF_FILE = "GLM-5.3-Flash-REAP50-Q3_K_M.gguf" -SPLIT = "UD-IQ2_XXS" # the numbered files of a split GGUF, in a folder of a third -SPLIT_FILES = [f"GLM-5.3-Flash-UD-IQ2_XXS-0000{i}-of-00004.gguf" for i in range(1, 5)] - - -def quiet(fn, *args): - """-> (exit code or None, printed text).""" - out = io.StringIO() - code = None - with contextlib.redirect_stdout(out): - try: - code = fn(*args) - except SystemExit as e: - code = e.code - return code, out.getvalue() - - -class Pins(unittest.TestCase): - def test_the_file(self): - fam = setup.FAMILIES["glm"] - self.assertEqual(fam["hf"], f"https://huggingface.co/neuralll/GLM-5.3-Flash-GSQ-RCO-3.0bit-Q4Kattn-GGUF/" - f"resolve/{REV}/") - self.assertEqual(list(fam["sha256"]), [FILE, HALF_FILE, *SPLIT_FILES]) - size, sha = fam["sha256"][FILE] - self.assertEqual(size, 113585695168) - self.assertRegex(sha, r"^[0-9a-f]{64}$") - self.assertEqual(setup.model_file(fam, M, 1), FILE) - self.assertEqual(setup.model_shards(fam, M), 1) - - def test_a_size_from_another_repository(self): - fam, d = setup.FAMILIES["glm"], setup.MODELS[HALF] - self.assertRegex(d["hf"], r"^https://huggingface.co/patrickbdevaney/GLM-5.3-Flash-REAP50-GGUF/resolve/" - r"[0-9a-f]{40}/$") - self.assertEqual(setup.model_file(fam, HALF, 1), HALF_FILE) - size, sha = fam["sha256"][HALF_FILE] - self.assertEqual(size, 78776759712) - self.assertRegex(sha, r"^[0-9a-f]{64}$") - rows = [line.split() for line in (ROOT / "data" / d["profile"]).read_text().splitlines()] - self.assertEqual(sorted({int(r[0]) for r in rows}), list(range(3, 46))) # 45: its draft block - self.assertEqual(max(int(r[1]) for r in rows), 143) # 144 experts a layer - - def test_not_in_the_other_families(self): - for f in setup.FAMILIES: - names = [m for m in setup.MODELS if f in setup.MODELS[m].get("families", ("qwen", "swift"))] - self.assertEqual(M in names, f == "glm", f) - - def test_the_shipped_profile_names_every_routed_layer(self): - rows = [line.split() for line in (ROOT / "data" / setup.FAMILIES["glm"]["profile"]).read_text().splitlines()] - self.assertTrue(all(len(r) == 3 and int(r[2]) > 0 for r in rows)) - self.assertEqual(sorted({int(r[0]) for r in rows}), list(range(3, 46))) # 45: the draft block - self.assertEqual(max(int(r[1]) for r in rows), 287) - - -class Estimates(unittest.TestCase): - def test_the_measured_card(self): - # an RTX 5090 lists 31.8 GiB; its cache held 19.9 GiB of experts at 32K - self.assertAlmostEqual(setup.poly_held_gb(setup.MODELS[M], 31.84) / 1.073741824, 19.9, delta=0.2) - self.assertAlmostEqual(setup.poly_ram_need(setup.MODELS[M], 31.84), 96, delta=1) - - def test_the_half_expert_size(self): - # the same card held 20.8 GiB of its experts - self.assertAlmostEqual(setup.poly_held_gb(setup.MODELS[HALF], 31.84) / 1.073741824, 20.8, delta=0.2) - self.assertAlmostEqual(setup.poly_ram_need(setup.MODELS[HALF], 31.84), 60, delta=1) - - def test_the_size_taken_when_none_is_named(self): - sizes = setup.family_models("glm") - self.assertEqual(list(sizes), [M, SPLIT, HALF]) # the whole model before the half of it - self.assertEqual(setup.poly_default(sizes, 128, 31.84), M) - self.assertEqual(setup.poly_default(sizes, 88, 31.84), SPLIT) # 3.0BIT wants 96 GB there - self.assertEqual(setup.poly_default(sizes, 64, 31.84), HALF) - self.assertEqual(setup.poly_default(sizes, 32, 31.84), HALF) # none fits: the one that wants least - - def test_the_split_size(self): - fam, d = setup.FAMILIES["glm"], setup.MODELS[SPLIT] - self.assertEqual([setup.model_file(fam, SPLIT, i) for i in range(1, 5)], SPLIT_FILES) - self.assertEqual(setup.model_shards(fam, SPLIT), 4) - self.assertRegex(d["hf"], r"^https://huggingface.co/unsloth/GLM-5.3-Flash-GGUF/resolve/[0-9a-f]{40}/UD-IQ2_XXS/$") - self.assertAlmostEqual(sum(fam["sha256"][f][0] for f in SPLIT_FILES) / 1e9, d["download_gb"], delta=0.1) - # the same card held 19.3 GiB of its experts - self.assertAlmostEqual(setup.poly_held_gb(setup.MODELS[SPLIT], 31.84) / 1.073741824, 19.3, delta=0.1) - self.assertAlmostEqual(setup.poly_ram_need(setup.MODELS[SPLIT], 31.84), d["ram_gb"], delta=1) - - def test_a_card_that_holds_none(self): - self.assertEqual(setup.poly_held_gb(setup.MODELS[M], 8.0), 0.0) - self.assertAlmostEqual(setup.poly_ram_need(setup.MODELS[M], 8.0), 117.2, delta=0.1) - - def test_check_lines(self): - with mock.patch.object(setup, "WIN", False): # #11: AMD on Linux runs it - self.assertNotIn("does not run", setup.poly_verdict(setup.MODELS[M], 256, 24.0, True)) - with mock.patch.object(setup, "WIN", True): - self.assertIn("AMD", setup.poly_verdict(setup.MODELS[M], 256, 24.0, True)) # only AMD on Windows is left out - self.assertIn("does not fit", setup.poly_verdict(setup.MODELS[M], 256, 12.0, False)) - self.assertIn("fits by setup's estimate", setup.poly_verdict(setup.MODELS[M], 128, 31.84, False)) - self.assertIn("read from the SSD", setup.poly_verdict(setup.MODELS[M], 64, 31.84, False)) - - -class Config(unittest.TestCase): - def test_choices_from_config(self): - with tempfile.TemporaryDirectory() as t: - p = Path(t) / "strata-glm-3.0bit.json" - p.write_text(json.dumps({"exe": "/x/engine-poly/" + setup.POLY_EXE, "args": ["--max-context", "65536"]})) - ch = setup.choices_from_config(p) - self.assertEqual((ch["family"], ch["model"], ch["context"], ch["vision"]), ("glm", M, 65536, "none")) - self.assertTrue(setup.poly_config(json.loads(p.read_text()))) - - def test_an_install_from_before_the_engine_was_renamed(self): - # its config has strata-glm in engine-glm/: it is this engine's, and an update moves it to the new one - with tempfile.TemporaryDirectory() as t: - root = Path(t) - p = root / "strata-glm-3.0bit.json" - cfg = {"exe": str(root / setup.OLD_ENGINE_POLY_DIR / setup.OLD_POLY_EXE), "args": ["--max-context", "32768"]} - p.write_text(json.dumps(cfg)) - self.assertTrue(setup.poly_config(cfg)) - self.assertEqual(setup.choices_from_config(p)["family"], "glm") - - def build(gpu, yes, llama, vision="none", works=True): - if not works: - raise RuntimeError("no compiler") - (root / setup.ENGINE_POLY_DIR).mkdir(exist_ok=True) - (root / setup.ENGINE_POLY_DIR / setup.POLY_EXE).write_text("") - (root / setup.ENGINE_POLY_DIR / "BUILD.json").write_text(json.dumps({"cuda_dirs": ["/cuda/bin"]})) - return root / setup.ENGINE_POLY_DIR - - with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "get_llama_cpp", lambda: root), \ - mock.patch.object(setup, "gpu_info", lambda i=None: {"arch": "89"}): - # a compile that fails leaves the install as it was: the old engine still starts - with mock.patch.object(setup, "build_engine_poly", lambda *a: build(*a, works=False)): - _code, out = quiet(setup.update_poly_engine, dict(cfg), False, p) - self.assertIn("could not update strata-poly", out) - self.assertEqual(json.loads(p.read_text())["exe"], cfg["exe"]) - with mock.patch.object(setup, "build_engine_poly", build): - _code, out = quiet(setup.update_poly_engine, cfg, False, p) - new = root / setup.ENGINE_POLY_DIR / setup.POLY_EXE - self.assertEqual((Path(cfg["exe"]), Path(json.loads(p.read_text())["exe"])), (new, new)) - self.assertEqual(json.loads(p.read_text())["lib_dirs"], ["/cuda/bin"]) - self.assertIn(setup.OLD_ENGINE_POLY_DIR + "/ can be deleted", out) - self.assertFalse(setup.poly_config({"exe": "/x/engine/" + setup.EXE})) - - def test_the_compile_takes_the_cmake_pip_installed(self): - # a cmake on PATH can be older than CMakeLists.txt takes (Ubuntu 22.04's); the one beside Python is setup's - with tempfile.TemporaryDirectory() as t: - mine, name = Path(t) / "bin", "cmake" + (".exe" if setup.WIN else "") - mine.mkdir() - with mock.patch.object(sys, "executable", str(mine / "python")), \ - mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n), \ - mock.patch.object(setup.Path, "home", lambda: Path(t) / "home"): - self.assertEqual(setup.find_tool("cmake"), "/usr/bin/cmake") # none of its own: PATH's - (mine / name).write_text("") - self.assertEqual(setup.find_tool("cmake"), str(mine / name)) - with mock.patch.object(setup.shutil, "which", lambda n: None): - self.assertIsNone(setup.find_tool("ninja")) - - def test_saved_conversation_cache(self): - with tempfile.TemporaryDirectory() as t: - p = Path(t) / "c.json" - self.assertIsNone(setup.poly_saved_conv([p, None])) - p.write_text(json.dumps({"args": ["--model", "m.gguf"]})) - self.assertEqual(setup.poly_saved_conv([None, p]), 0) - p.write_text(json.dumps({"args": ["--conversation-cache-mib", "4096", "--model", "m.gguf"]})) - self.assertEqual(setup.poly_saved_conv([p]), 4096) - - -class Main(unittest.TestCase): - """setup.main() for --family glm, every outside effect mocked.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.t = Path(self.tmp.name) - (self.t / "data").mkdir() - (self.t / "data" / "expert-profile-glm.txt").write_text("3 0 7\n") - (self.t / "data" / "expert-profile-glm-reap50.txt").write_text("3 1 5\n") - self.downloads, self.runs, self.verified, self.built = [], [], [], [] - - def tearDown(self): - self.tmp.cleanup() - - def main(self, argv=(), ram=128.0, vram=31.84, model=False, answers=None, win=False, n_gpus=1, family="glm", - cores=None): - """answers: None = --yes; else {words of a question: its answer} (Enter for the others); the questions asked - are kept in self.asked. model: False, True (this file's M) or a size's name. cores: (performance, - efficiency) of a hybrid CPU.""" - self.asked = [] - - def fake_input(prompt=""): - if answers is None: - raise AssertionError(f"asked {prompt!r}") - self.asked.append(prompt) - return next((v for k, v in answers.items() if k in prompt), "") - - found = [{"index": i, "name": "NVIDIA GeForce RTX 5090", "vram_gb": vram, "arch": "120", "driver": "580.97"} - for i in range(n_gpus)] - - def fake_download(url, dst, what=None): - self.downloads.append(url) - dst.parent.mkdir(parents=True, exist_ok=True) - dst.write_bytes(b"") - setup.mark(dst) - - def fake_build(gpu, yes, llama, vision="none", toolkit=13): - self.built.append(gpu["archs"]) - self.encoder, self.toolkit = vision, toolkit - eng = self.t / setup.ENGINE_POLY_DIR - eng.mkdir(exist_ok=True) - (eng / "BUILD.json").write_text(json.dumps({"source": "local", "cuda_dirs": ["/cuda/lib64"]})) - return eng - - patches = [ - mock.patch.object(setup, "ROOT", self.t), - mock.patch.object(setup, "WIN", win), - mock.patch.object(setup, "GPU_PICK", None), - mock.patch.object(setup, "data_folder", lambda d: (self.t / "data", [])), - mock.patch.object(setup, "installed_configs", lambda: []), - mock.patch.object(setup, "gpus", lambda: found), - mock.patch.object(setup, "amd_gpus", lambda *a: []), - mock.patch.object(setup, "ram_gb", lambda: ram), - mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, True)), - mock.patch.object(setup, "cpu_cores", lambda: cores), - mock.patch.object(setup, "page_file_gb", lambda: 16.0), - mock.patch.object(setup, "free_gb", lambda p: 500.0), - mock.patch.object(setup, "pip_install", lambda *a, **k: None), - mock.patch.object(setup, "get_llama_cpp", lambda: self.t / "llama.cpp"), - mock.patch.object(setup, "get_prebuilt", mock.Mock(side_effect=AssertionError("the Qwen engine"))), - mock.patch.object(setup, "build_engine_poly", fake_build), - mock.patch.object(setup, "download", fake_download), - mock.patch.object(setup, "whole_shard", lambda s: False), - mock.patch.object(setup, "check_shards", lambda shards: None), - mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), - mock.patch.object(setup, "run", lambda cmd, *a, **k: self.runs.append([str(x) for x in cmd])), - mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: self.t / f"start-{tag}.sh"), - mock.patch.object(setup, "start", mock.Mock(side_effect=AssertionError("started"))), - mock.patch.object(sys, "argv", ["setup.py", "--family", family, - *(["--model", M if model is True else model] if model else []), - *(["--yes"] if answers is None else []), "--no-start", - "--models-dir", str(self.t / "models"), *argv]), - mock.patch("builtins.input", fake_input), - ] - with contextlib.ExitStack() as st: - for p in patches: - st.enter_context(p) - code, out = quiet(setup.main) - cfg = next(iter(sorted(self.t.glob(f"strata-{setup.FAMILIES[family]['tag']}*.json"))), None) - return code, out, (json.loads(cfg.read_text()) if cfg else None) - - def test_install(self): - code, out, cfg = self.main() - self.assertEqual(code, 0, out) - self.assertEqual(self.downloads, [setup.FAMILIES["glm"]["hf"] + FILE]) - self.assertEqual(self.verified, [(FILE, *setup.FAMILIES["glm"]["sha256"][FILE])]) - self.assertEqual(self.built, [["120"]]) - self.assertEqual(len(self.runs), 2, self.runs) # the tokenizer and the draft block: no pack - self.assertTrue(self.runs[0][1].endswith("strata_tokenizer.py")) - pack = self.t / "data" / "packs" / "glm-3.0bit" - self.assertEqual(self.runs[0][self.runs[0].index("--out") + 1], str(pack)) - # this size's file has no draft block: the model's is fetched, and the engine is given it - block = self.t / "data" / "mtp" / "glm-5.3-flash" / "draft-block.gguf" - self.assertTrue(self.runs[1][1].endswith("glm_draft_fetch.py")) - self.assertEqual(self.runs[1][2:], ["fetch", "--out", str(block)]) - self.assertEqual((pack / "expert-profile.txt").read_text(), "3 0 7\n") - args = cfg["args"] - self.assertEqual(Path(cfg["exe"]), self.t / setup.ENGINE_POLY_DIR / setup.POLY_EXE) - self.assertEqual(Path(args[args.index("--model") + 1]), self.t / "models" / "glm-3.0BIT" / FILE) - self.assertEqual(args[args.index("--max-context") + 1], "32768") - self.assertEqual(Path(args[args.index("--expert-profile") + 1]), pack / "expert-profile.txt") - self.assertEqual(Path(args[args.index("--draft-model") + 1]), block) - self.assertEqual(args[args.index("--conversation-cache-mib") + 1], "8192") - for flag in ("--pack", "--native", "--mtp", "--kv", "--vision", "--pool-workers", "--prefill"): - self.assertNotIn(flag, args) - self.assertEqual(cfg["model_name"], "glm-5.3-flash-3.0bit") - self.assertEqual(Path(cfg["tokenizer"]), pack / "tokenizer") - self.assertEqual(cfg["lib_dirs"], ["/cuda/lib64"]) - self.assertNotIn("vision", cfg) - self.assertEqual(cfg["gpu"], 0) # as main() does for every model - - def test_a_draft_block_that_is_there_is_not_fetched_again(self): - block = self.t / "data" / "mtp" / "glm-5.3-flash" / "draft-block.gguf" - block.parent.mkdir(parents=True) - block.write_bytes(b"GGUF") - code, out, cfg = self.main() - self.assertEqual(code, 0, out) - self.assertEqual([Path(r[1]).name for r in self.runs], ["strata_tokenizer.py"]) - self.assertEqual(Path(cfg["args"][cfg["args"].index("--draft-model") + 1]), block) - - def test_the_engine_keeps_its_own_profile(self): - pack = self.t / "data" / "packs" / "glm-3.0bit" - pack.mkdir(parents=True) - (pack / "expert-profile.txt").write_text("4 1 9\n") - code, out, cfg = self.main() - self.assertEqual(code, 0, out) - self.assertEqual((pack / "expert-profile.txt").read_text(), "4 1 9\n") - - def test_the_questions(self): - code, out, cfg = self.main(answers={"Context": "3", "Keep several": "n"}) - self.assertEqual(code, 0, out) - self.assertEqual([q.split("?")[0] for q in self.asked], - ["Size", "Context", "Keep several conversations in RAM"]) - self.assertEqual(cfg["model_name"], "glm-5.3-flash-3.0bit") # Enter: the whole model, with 128 GB - self.assertEqual(cfg["args"][cfg["args"].index("--max-context") + 1], "65536") - self.assertNotIn("--conversation-cache-mib", cfg["args"]) - # a second run does not ask for the cache again and keeps it off - code, out, cfg = self.main(answers={}) - self.assertEqual(code, 0, out) - self.assertEqual([q.split("?")[0] for q in self.asked], ["Size", "Context"]) - self.assertNotIn("--conversation-cache-mib", cfg["args"]) - - def test_the_cache_is_not_recommended_without_room(self): - code, out, cfg = self.main(ram=100.0) # 96 GB wanted: no 8 GB beside it - self.assertEqual(code, 0, out) - self.assertNotIn("--conversation-cache-mib", cfg["args"]) - - def test_less_ram_gets_the_half_expert_size(self): - code, out, cfg = self.main(ram=63.7) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["model_name"], "glm-5.3-flash-reap50-q3_k_m") - self.assertEqual(self.downloads, [setup.MODELS[HALF]["hf"] + HALF_FILE]) - self.assertEqual(self.verified, [(HALF_FILE, *setup.FAMILIES["glm"]["sha256"][HALF_FILE])]) - pack = self.t / "data" / "packs" / "glm-reap50-q3_k_m" - self.assertEqual((pack / "expert-profile.txt").read_text(), "3 1 5\n") # its own profile - args = cfg["args"] - self.assertEqual(Path(args[args.index("--model") + 1]), self.t / "models" / "glm-REAP50-Q3_K_M" / HALF_FILE) - self.assertNotIn("--draft-model", args) # its file has its own, pruned with it - self.assertEqual([Path(r[1]).name for r in self.runs], ["strata_tokenizer.py"]) - - def test_a_size_in_several_files(self): - code, out, cfg = self.main(ram=88.0) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["model_name"], "glm-5.3-flash-ud-iq2_xxs") - self.assertEqual(self.downloads, [setup.MODELS[SPLIT]["hf"] + f for f in SPLIT_FILES]) - self.assertEqual(self.verified, [(f, *setup.FAMILIES["glm"]["sha256"][f]) for f in SPLIT_FILES]) - args = cfg["args"] # the engine is given the first file - self.assertEqual(Path(args[args.index("--model") + 1]), self.t / "models" / "glm-UD-IQ2_XXS" / SPLIT_FILES[0]) - pack = self.t / "data" / "packs" / "glm-ud-iq2_xxs" - self.assertEqual((pack / "expert-profile.txt").read_text(), "3 0 7\n") # the whole model's profile - self.assertNotIn("--draft-model", args) # the draft block is in its last file - self.assertEqual([Path(r[1]).name for r in self.runs], ["strata_tokenizer.py"]) - - def test_deepseek(self): - """DeepSeek V4 Flash: GLM's steps for Unsloth's three files, no draft block and no shipped profile.""" - fam = setup.FAMILIES["deepseek"] - d = fam["models"]["UD-IQ2_XXS"] - files = [f"DeepSeek-V4-Flash-0731-UD-IQ2_XXS-0000{i}-of-00003.gguf" for i in (1, 2, 3)] - self.assertRegex(d["hf"], r"^https://huggingface.co/unsloth/DeepSeek-V4-Flash-0731-GGUF/resolve/[0-9a-f]{40}/" - r"UD-IQ2_XXS/$") - self.assertAlmostEqual(sum(fam["sha256"][f][0] for f in files) / 1e9, d["download_gb"], delta=0.05) - self.assertAlmostEqual(setup.poly_ram_need(d, 31.84), d["ram_gb"], delta=0.5) - code, out, cfg = self.main(family="deepseek") - self.assertEqual(code, 0, out) - self.assertEqual(self.downloads, [d["hf"] + f for f in files]) - self.assertEqual(self.verified, [(f, *fam["sha256"][f]) for f in files]) - self.assertEqual([Path(r[1]).name for r in self.runs], ["strata_tokenizer.py"]) - args = cfg["args"] - self.assertEqual(Path(args[args.index("--model") + 1]), self.t / "models" / "dsv4-UD-IQ2_XXS" / files[0]) - self.assertNotIn("--draft-model", args) - self.assertFalse((self.t / "data" / "packs" / "dsv4-ud-iq2_xxs" / "expert-profile.txt").exists()) - self.assertEqual(cfg["model_name"], "deepseek-v4-flash-ud-iq2_xxs") - - def test_too_little_ram(self): - code, out, cfg = self.main(ram=40.0) - self.assertNotEqual(code, 0) - self.assertIn("wants about 60 GB of RAM; this PC has 40", out) - self.assertIsNone(cfg) - self.assertEqual(self.built, []) - code, out, cfg = self.main(ram=63.7, model=True) # --model with --yes is the consent - self.assertEqual(code, 0, out) - self.assertIn("going on with 64 GB of RAM, as you chose", out) - - def test_a_smaller_card(self): - code, out, cfg = self.main(ram=256.0, vram=23.9) - self.assertEqual(code, 0, out) - self.assertIn("has run on no card under 32 GB", out) - code, out, cfg = self.main(ram=256.0, vram=11.9) - self.assertNotEqual(code, 0) - self.assertIn("needs more VRAM than 12 GB", out) - - def test_qwen_options_are_named(self): - code, out, cfg = self.main(["--kv", "q4_0", "--vision", "yes", "--parallel", "2"]) - self.assertEqual(code, 0, out) - line = next(ln for ln in out.splitlines() if "not used with GLM 5.3 Flash" in ln) - for flag in ("--kv", "--vision"): - self.assertIn(flag, line) - self.assertNotIn("--parallel", line) # strata-poly answers several requests at once too - self.assertEqual(cfg["parallel"], 2) - - def test_two_cards(self): - code, out, cfg = self.main(["--gpu", "1"], n_gpus=2) - self.assertEqual(code, 0, out) - self.assertEqual((cfg["gpu"], cfg["gpus_asked"]), (1, True)) - - def test_layer_split(self): - code, out, cfg = self.main(["--gpus", "0,1"], n_gpus=2) - self.assertEqual(code, 0, out) - self.assertEqual((cfg["gpu"], cfg["gpus_asked"], cfg["layer_split"]), ([0, 1], True, "auto")) - self.assertNotIn("runs on one GPU", out) - code, out, cfg = self.main(["--gpus", "0,1", "--layer-split", "30"], n_gpus=2) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["layer_split"], "30") - self.assertNotIn("--layer-split", next((ln for ln in out.splitlines() if "not used with" in ln), "")) - - def test_windows_is_asked(self): - code, out, cfg = self.main(win=True, answers={}) - self.assertNotEqual(code, 0) - self.assertIn("has not been tried on Windows", out) - self.assertEqual(self.built, []) - - def test_windows_is_not_asked_for_a_family_that_ran_there(self): - for family in ("qwen36", "ornith", "gemma4", "tiel"): - with self.subTest(family): - self.built = [] - code, out, cfg = self.main(win=True, family=family, ram=32.0, vram=8.0) - self.assertEqual(code, 0, out) - self.assertNotIn("Windows", out) - self.assertEqual(len(self.built), 1) - - def test_cuda_12_compiles_the_engine_with_it(self): - code, out, cfg = self.main(["--cuda", "12"]) - self.assertEqual(code, 0, out) - self.assertEqual((self.built, self.toolkit), ([["120"]], 12)) - self.assertIn("with CUDA 12 is compiled here", out) - self.assertEqual(cfg["cuda"], 12) - # a copy set up from this install keeps it; the same one set up again chooses again - self.assertEqual(setup.choices_from_config(next(self.t.glob("strata-glm*.json")))["cuda"], 12) - code, out, cfg = self.main() - self.assertEqual((cfg.get("cuda"), self.toolkit), (None, 13)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_golden.json b/tools/test_setup_golden.json deleted file mode 100644 index ad762c1..0000000 --- a/tools/test_setup_golden.json +++ /dev/null @@ -1,1129 +0,0 @@ -{ - "128GB-1x24GB qwen IQ3_S": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_s", - "--native", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_s.log", - "model_name": "qwen3.8-flash-next-iq3_s", - "port": 8080, - "tokenizer": "/data/packs/iq3_s/tokenizer" - } - }, - "128GB-1x24GB qwen IQ3_XXS": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_xxs", - "--native", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_xxs.log", - "model_name": "qwen3.8-flash-next-iq3_xxs", - "port": 8080, - "tokenizer": "/data/packs/iq3_xxs/tokenizer" - } - }, - "128GB-1x24GB qwen Q2_0": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/q2_0", - "--native", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", - "--ple-gguf", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-q2_0.log", - "model_name": "qwen3.8-flash-next-q2_0", - "port": 8080, - "tokenizer": "/data/packs/q2_0/tokenizer" - } - }, - "128GB-1x24GB qwen recommended": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_s", - "--native", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_s.log", - "model_name": "qwen3.8-flash-next-iq3_s", - "port": 8080, - "tokenizer": "/data/packs/iq3_s/tokenizer" - } - }, - "128GB-1x24GB unsloth UD-Q4_K_XL": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/unsloth-ud-q4_k_xl", - "--native", - "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--kv-resident", - "32768", - "--vision", - "--vram-reserve-mib", - "700" - ], - "cwd": "", - "env": { - "STRATA_HC_Q8": "1", - "STRATA_ROUTE_TAIL_SKIP": "0" - }, - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-unsloth-ud-q4_k_xl.log", - "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", - "port": 8080, - "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", - "vision": { - "exe": "/engine/strata-vision.exe", - "gpu": true, - "max_tokens": 1024, - "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", - "model": "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" - } - } - }, - "32GB-2x24GB qwen IQ3_S": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_s", - "--native", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--resident-experts" - ], - "cwd": "", - "exe": "/engine/", - "gpu": [ - 0, - 1 - ], - "gpus_asked": true, - "layer_split": "auto", - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_s.log", - "model_name": "qwen3.8-flash-next-iq3_s", - "port": 8080, - "tokenizer": "/data/packs/iq3_s/tokenizer" - } - }, - "32GB-2x24GB qwen IQ3_XXS": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_xxs", - "--native", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--resident-experts" - ], - "cwd": "", - "exe": "/engine/", - "gpu": [ - 0, - 1 - ], - "gpus_asked": true, - "layer_split": "auto", - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_xxs.log", - "model_name": "qwen3.8-flash-next-iq3_xxs", - "port": 8080, - "tokenizer": "/data/packs/iq3_xxs/tokenizer" - } - }, - "32GB-2x24GB qwen Q2_0": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/q2_0", - "--native", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", - "--ple-gguf", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--resident-experts" - ], - "cwd": "", - "exe": "/engine/", - "gpu": [ - 0, - 1 - ], - "gpus_asked": true, - "layer_split": "auto", - "lib_dirs": [ - "" - ], - "log": "/strata-q2_0.log", - "model_name": "qwen3.8-flash-next-q2_0", - "port": 8080, - "tokenizer": "/data/packs/q2_0/tokenizer" - } - }, - "32GB-2x24GB qwen recommended": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/q2_0", - "--native", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", - "--ple-gguf", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--resident-experts" - ], - "cwd": "", - "exe": "/engine/", - "gpu": [ - 0, - 1 - ], - "gpus_asked": true, - "layer_split": "auto", - "lib_dirs": [ - "" - ], - "log": "/strata-q2_0.log", - "model_name": "qwen3.8-flash-next-q2_0", - "port": 8080, - "tokenizer": "/data/packs/q2_0/tokenizer" - } - }, - "32GB-2x24GB unsloth UD-Q4_K_XL": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/unsloth-ud-q4_k_xl", - "--native", - "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "32768", - "--kv", - "int8", - "--resident-budget-gib", - "8", - "--vision", - "--vram-reserve-mib", - "700" - ], - "cwd": "", - "env": { - "STRATA_HC_Q8": "1" - }, - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-unsloth-ud-q4_k_xl.log", - "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", - "port": 8080, - "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", - "vision": { - "exe": "/engine/strata-vision.exe", - "gpu": true, - "max_tokens": 1024, - "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", - "model": "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" - } - } - }, - "47GB-2x16GB qwen IQ3_S": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_s", - "--native", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8", - "--resident-experts" - ], - "cwd": "", - "exe": "/engine/", - "gpu": [ - 0, - 1 - ], - "gpus_asked": true, - "layer_split": "auto", - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_s.log", - "model_name": "qwen3.8-flash-next-iq3_s", - "port": 8080, - "tokenizer": "/data/packs/iq3_s/tokenizer" - } - }, - "47GB-2x16GB qwen IQ3_XXS": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_xxs", - "--native", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8", - "--resident-experts" - ], - "cwd": "", - "exe": "/engine/", - "gpu": [ - 0, - 1 - ], - "gpus_asked": true, - "layer_split": "auto", - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_xxs.log", - "model_name": "qwen3.8-flash-next-iq3_xxs", - "port": 8080, - "tokenizer": "/data/packs/iq3_xxs/tokenizer" - } - }, - "47GB-2x16GB qwen Q2_0": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/q2_0", - "--native", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", - "--ple-gguf", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8" - ], - "cwd": "", - "exe": "/engine/", - "gpu": [ - 0, - 1 - ], - "gpus_asked": true, - "layer_split": "auto", - "lib_dirs": [ - "" - ], - "log": "/strata-q2_0.log", - "model_name": "qwen3.8-flash-next-q2_0", - "port": 8080, - "tokenizer": "/data/packs/q2_0/tokenizer" - } - }, - "47GB-2x16GB qwen recommended": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/q2_0", - "--native", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", - "--ple-gguf", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8" - ], - "cwd": "", - "exe": "/engine/", - "gpu": [ - 0, - 1 - ], - "gpus_asked": true, - "layer_split": "auto", - "lib_dirs": [ - "" - ], - "log": "/strata-q2_0.log", - "model_name": "qwen3.8-flash-next-q2_0", - "port": 8080, - "tokenizer": "/data/packs/q2_0/tokenizer" - } - }, - "47GB-2x16GB unsloth UD-Q4_K_XL": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/unsloth-ud-q4_k_xl", - "--native", - "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "32768", - "--kv", - "int8", - "--resident-budget-gib", - "23", - "--vision", - "--vram-reserve-mib", - "700" - ], - "cwd": "", - "env": { - "STRATA_HC_Q8": "1" - }, - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-unsloth-ud-q4_k_xl.log", - "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", - "port": 8080, - "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", - "vision": { - "exe": "/engine/strata-vision.exe", - "gpu": false, - "max_tokens": 300, - "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", - "model": "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", - "threads": 6 - } - } - }, - "64GB-1x32GB qwen IQ3_S": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_s", - "--native", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_s.log", - "model_name": "qwen3.8-flash-next-iq3_s", - "port": 8080, - "tokenizer": "/data/packs/iq3_s/tokenizer" - } - }, - "64GB-1x32GB qwen IQ3_XXS": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_xxs", - "--native", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_xxs.log", - "model_name": "qwen3.8-flash-next-iq3_xxs", - "port": 8080, - "tokenizer": "/data/packs/iq3_xxs/tokenizer" - } - }, - "64GB-1x32GB qwen Q2_0": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/q2_0", - "--native", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", - "--ple-gguf", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-q2_0.log", - "model_name": "qwen3.8-flash-next-q2_0", - "port": 8080, - "tokenizer": "/data/packs/q2_0/tokenizer" - } - }, - "64GB-1x32GB qwen recommended": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_s", - "--native", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "131072", - "--kv", - "int8" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_s.log", - "model_name": "qwen3.8-flash-next-iq3_s", - "port": 8080, - "tokenizer": "/data/packs/iq3_s/tokenizer" - } - }, - "64GB-1x32GB unsloth UD-Q4_K_XL": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/unsloth-ud-q4_k_xl", - "--native", - "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "32768", - "--kv", - "int8", - "--resident-budget-gib", - "40", - "--vision", - "--vram-reserve-mib", - "700" - ], - "cwd": "", - "env": { - "STRATA_HC_Q8": "1" - }, - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-unsloth-ud-q4_k_xl.log", - "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", - "port": 8080, - "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", - "vision": { - "exe": "/engine/strata-vision.exe", - "gpu": true, - "max_tokens": 1024, - "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", - "model": "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" - } - } - }, - "96GB-1x16GB qwen IQ3_S": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_s", - "--native", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_s.log", - "model_name": "qwen3.8-flash-next-iq3_s", - "port": 8080, - "tokenizer": "/data/packs/iq3_s/tokenizer" - } - }, - "96GB-1x16GB qwen IQ3_XXS": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_xxs", - "--native", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_xxs.log", - "model_name": "qwen3.8-flash-next-iq3_xxs", - "port": 8080, - "tokenizer": "/data/packs/iq3_xxs/tokenizer" - } - }, - "96GB-1x16GB qwen Q2_0": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/q2_0", - "--native", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", - "--ple-gguf", - "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-q2_0.log", - "model_name": "qwen3.8-flash-next-q2_0", - "port": 8080, - "tokenizer": "/data/packs/q2_0/tokenizer" - } - }, - "96GB-1x16GB qwen recommended": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/iq3_s", - "--native", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", - "--ple-gguf", - "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8", - "--kv-resident", - "32768" - ], - "cwd": "", - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-iq3_s.log", - "model_name": "qwen3.8-flash-next-iq3_s", - "port": 8080, - "tokenizer": "/data/packs/iq3_s/tokenizer" - } - }, - "96GB-1x16GB unsloth UD-Q4_K_XL": { - "code": 0, - "config": { - "args": [ - "--pack", - "/data/packs/unsloth-ud-q4_k_xl", - "--native", - "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", - "--expert-profile", - "/data/expert-profile.bin", - "--expert-cache", - "auto", - "--prefill", - "auto", - "--spec", - "4", - "--spec-min-p", - "0.5", - "--mtp", - "/data/mtp/rt", - "--max-context", - "65536", - "--kv", - "int8", - "--kv-resident", - "32768", - "--vision", - "--vram-reserve-mib", - "700" - ], - "cwd": "", - "env": { - "STRATA_HC_Q8": "1", - "STRATA_ROUTE_TAIL_SKIP": "0" - }, - "exe": "/engine/", - "gpu": 0, - "gpus_asked": true, - "lib_dirs": [ - "" - ], - "log": "/strata-unsloth-ud-q4_k_xl.log", - "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", - "port": 8080, - "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", - "vision": { - "exe": "/engine/strata-vision.exe", - "gpu": false, - "max_tokens": 300, - "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", - "model": "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", - "threads": 6 - } - } - } -} diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py deleted file mode 100644 index e5ab2c1..0000000 --- a/tools/test_setup_golden.py +++ /dev/null @@ -1,214 +0,0 @@ -"""The owner's rule for setup (#403 #406 #364 #384): setup RECOMMENDS, it never forces - and the recommended answers -stay exactly what they were. setup.main() with --yes (and with Enter for every question) on a few PCs writes the same -run config, byte for byte, as 0.1.32 plus the fixes on top of it did (tools/test_setup_golden.json, written by that -setup). Every outside effect is mocked: no GPU, no downloads, nothing written outside a temp folder. - - python -m unittest tools.test_setup_golden - python tools/test_setup_golden.py --write (only to record a new baseline on purpose) -""" -from __future__ import annotations - -import contextlib -import io -import json -import re -import sys -import tempfile -import types -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - -GOLDEN = Path(__file__).with_name("test_setup_golden.json") - - -def card(i, name, vram, arch): - return {"index": i, "name": name, "vram_gb": vram, "arch": arch, "driver": "580.97"} - - -# the PCs: total RAM as ram_gb() reads it (a little under the label), the cards as nvidia-smi lists them -PROFILES = { - "64GB-1x32GB": (63.7, [card(0, "NVIDIA GeForce RTX 5090", 31.8, "120")]), # #406 - "32GB-2x24GB": (31.9, [card(i, "NVIDIA GeForce RTX 3090", 24.0, "86") for i in range(2)]), # #364 - "47GB-2x16GB": (47.0, [card(i, "NVIDIA GeForce RTX 5060 Ti", 15.9, "120") for i in range(2)]), # #384 - "96GB-1x16GB": (95.8, [card(0, "NVIDIA GeForce RTX 5080", 15.9, "120")]), - "128GB-1x24GB": (127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89")]), -} -# (family, model): None = the recommended size -MODELS = [("qwen", None), ("qwen", "Q2_0"), ("qwen", "IQ3_XXS"), ("qwen", "IQ3_S"), ("unsloth", "UD-Q4_K_XL")] - - -class FakeGGUF: - """gguf_reader.GGUFFile: shard 2 holds the PLE table.""" - def __init__(self, path): - names = ["per_layer_token_embd.weight"] if "00002-of" in str(path) else ["blk.0.ffn_up_exps.weight"] - self.tensors = [types.SimpleNamespace(name=n) for n in names] - - -def normalize(v, t: Path): - """The config with the temp folder and the platform's names taken out (it compares on Windows and Linux).""" - if isinstance(v, dict): - return {k: normalize(x, t) for k, x in v.items()} - if isinstance(v, list): - return [normalize(x, t) for x in v] - if isinstance(v, str): - return re.sub(rf"(?", v.replace(str(t), "").replace("\\", "/")) # #973: only the whole name, not "strata-x.log" on Linux - return v - - -def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()): - """setup.main() on a mocked PC -> (exit code, printed text, the written config or None, the questions asked). - answers: None = --yes (a question fails the run), "" = Enter for every question, a list of answers in order, or - {words of a question: its answer} (Enter for the others). - extra: more patches (mock.patch objects). configs: (name, dict) run configs already in the PolyStrata folder.""" - with tempfile.TemporaryDirectory() as tmp: - t = Path(tmp) - (t / "data" / "mtp" / "rt").mkdir(parents=True) - (t / "data" / "mtp" / "rt" / "experts.bin").write_bytes(b"") - eng = t / "engine" - eng.mkdir() - (eng / "BUILD.json").write_text(json.dumps({"version": "0.1.32", "source": "local", "cuda_dirs": [""]})) - for name, c in configs: - (t / name).write_text(json.dumps(c)) - asked = [] - - def fake_input(prompt=""): - asked.append(prompt) - if answers is None: - raise AssertionError(f"asked {prompt!r} with --yes") - if isinstance(answers, list): - return answers.pop(0) if answers else "" - if isinstance(answers, dict): # {words of the question: answer}, else Enter - return next((v for k, v in answers.items() if k in prompt), "") - return answers - - def fake_download(url, dst, what=None): - dst.parent.mkdir(parents=True, exist_ok=True) - dst.write_bytes(b"") - setup.mark(dst) - - patches = [ - mock.patch.object(setup, "ROOT", t), - mock.patch.object(setup, "GPU_PICK", None), - mock.patch.object(setup, "data_folder", lambda d: (t / "data", [])), - mock.patch.object(setup, "load_settings", lambda: {}), - mock.patch.object(setup, "save_settings", lambda s: None), - mock.patch.object(setup, "gpus", lambda: found), - mock.patch.object(setup, "amd_gpus", lambda: []), - mock.patch.object(setup, "ram_gb", lambda: ram), - mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, avx512)), - mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU - mock.patch.object(setup.os, "cpu_count", lambda: 12), # the CPU image encoder's threads: half of them - mock.patch.object(setup, "page_file_gb", lambda: 16.0), - mock.patch.object(setup, "is_wsl", lambda: False), - mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: the test PC's own disk - mock.patch.object(setup, "free_gb", lambda p: 900.0), - mock.patch.object(setup, "pip_install", lambda *a, **k: None), - mock.patch.object(setup, "get_llama_cpp", lambda: t / "llama.cpp"), - mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), - mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None), - mock.patch.object(setup, "download", fake_download), - mock.patch.object(setup, "check_shards", lambda shards: None), - mock.patch.object(setup, "verify_sha256", lambda *a: None), - mock.patch.object(setup, "run", lambda *a, **k: None), - mock.patch.object(setup, "mtp_corrupt", lambda *a, **k: False), - mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), - mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: t / f"run-{tag}.bat"), - mock.patch.object(setup, "saved_calibration", lambda cfg: None), - mock.patch.object(setup, "calibrate_config", mock.Mock(side_effect=AssertionError("calibrated"))), - mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}), - mock.patch.object(sys, "argv", ["setup.py", "--models-dir", str(t / "models"), *argv] - + (["--yes"] if answers is None else [])), - mock.patch("builtins.input", fake_input), - *extra, - ] - out = io.StringIO() - code = None - with contextlib.ExitStack() as st: - for p in patches: - st.enter_context(p) - with contextlib.redirect_stdout(out): - try: - code = setup.main() - except SystemExit as e: - code = e.code - written = sorted(t.glob("strata-*.json"), key=lambda p: p.stat().st_mtime) - cfg = None - if written and code == 0: - cfg = normalize(json.loads(written[-1].read_text(encoding="utf-8")), t) - return code, out.getvalue(), cfg, asked - - -def argv_for(family, model): - return ["--family", family, "--no-start"] + (["--model", model] if model else []) - - -def record() -> dict: - """Every profile x model with --yes: the exit code and the config (the baseline this test compares against).""" - res = {} - for prof, (ram, found) in PROFILES.items(): - for family, model in MODELS: - code, out, cfg, _ = install(ram, found, argv_for(family, model)) - res[f"{prof} {family} {model or 'recommended'}"] = {"code": code, "config": cfg} - return res - - -class Golden(unittest.TestCase): - """--yes and Enter: the same config as the baseline wherever the baseline wrote one.""" - - @classmethod - def setUpClass(cls): - cls.golden = json.loads(GOLDEN.read_text(encoding="utf-8")) - - def cases(self): - for prof, (ram, found) in PROFILES.items(): - for family, model in MODELS: - key = f"{prof} {family} {model or 'recommended'}" - if self.golden[key]["code"] == 0: - yield key, ram, found, family, model - - def test_the_baseline_covers_every_kind_of_pc(self): - written = [k for k, v in self.golden.items() if v["code"] == 0] - self.assertGreaterEqual(len(written), 20) - lowram_multi = self.golden["32GB-2x24GB qwen IQ3_XXS"]["config"] # #364 -> #642: low-RAM, two cards -> both - self.assertIn("--resident-experts" if "--resident-experts" in lowram_multi["args"] else "--mmap-experts", - lowram_multi["args"]) - self.assertEqual(lowram_multi.get("gpu"), [0, 1]) # 0.1.40 (#642): resident on both cards - - def test_yes(self): - for key, ram, found, family, model in self.cases(): - with self.subTest(key): - code, out, cfg, asked = install(ram, found, argv_for(family, model)) - self.assertEqual(code, 0, out[-3000:]) - self.assertEqual(cfg, self.golden[key]["config"], out[-3000:]) - self.assertEqual(asked, []) - - def test_enter_for_every_question(self): - for key, ram, found, family, model in self.cases(): - if "UD-Q4_K_XL" in key and ram < 48: # --yes consents to the risk; Enter declines it (the - continue # "Install it anyway? [n]" question), by design - with self.subTest(key): - code, out, cfg, asked = install(ram, found, argv_for(family, model), answers="") - self.assertEqual(code, 0, out[-3000:]) - self.assertEqual(cfg, self.golden[key]["config"], out[-3000:]) - - def test_the_refusals_with_yes_alone_stay(self): - """A size the baseline refused with --yes and no explicit --model still stops (--yes alone is no consent).""" - for prof, (ram, found) in PROFILES.items(): - for family, model in MODELS: - key = f"{prof} {family} {model or 'recommended'}" - if self.golden[key]["code"] != 0 and model is None: - with self.subTest(key): - self.assertNotEqual(install(ram, found, argv_for(family, model))[0], 0) - - -if __name__ == "__main__": - if "--write" in sys.argv: - GOLDEN.write_text(json.dumps(record(), indent=1, sort_keys=True) + "\n", encoding="utf-8") - print(f"wrote {GOLDEN}") - else: - unittest.main() diff --git a/tools/test_setup_hotfix_tag.py b/tools/test_setup_hotfix_tag.py deleted file mode 100644 index be4a8d3..0000000 --- a/tools/test_setup_hotfix_tag.py +++ /dev/null @@ -1,53 +0,0 @@ -"""A four-part version (0.1.40.2) cannot break setup: versions compare all four numbers (0.1.40 < 0.1.40.2, so a -0.1.40 engine is updated), the engine zips are looked for under the checkout's own v tag first and -the latest release second, and a binary that says `engine=0.1.40.2` is read as (0, 1, 40, 2). - - python -m unittest tools.test_setup_hotfix_tag -""" -from __future__ import annotations - -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - - -class HotfixTag(unittest.TestCase): - def test_a_four_part_version_compares_all_four_numbers(self): - ver = tuple(int(x) for x in "0.1.40.3".split(".")) # a hotfix version has four numbers; MIN_ENGINE may have three - self.assertEqual(len(ver), 4) - self.assertLess(ver, setup.MIN_ENGINE) # an installed hotfix of the older release is replaced - self.assertGreaterEqual((0, 1, 45), setup.MIN_ENGINE) # the minimum itself (or a later hotfix) is accepted - self.assertLess((0, 1, 44, 1), setup.MIN_ENGINE) # the 0.1.44.1 hotfix is replaced - self.assertLess((0, 1, 44), setup.MIN_ENGINE) # the release before is replaced - self.assertLess((0, 1, 43, 1), setup.MIN_ENGINE) # the 0.1.43.1 hotfix is replaced - self.assertLess((0, 1, 42, 1), setup.MIN_ENGINE) # 0.1.42.1 is replaced - self.assertLess((0, 1, 40), setup.MIN_ENGINE) # an installed 0.1.40 engine is replaced - - def test_the_engine_zips_are_found_for_a_hotfix_tag(self): - # a hotfix that keeps CMakeLists.txt at the engine's version: the v0.1.40 release still holds the zips - bases = setup.prebuilt_bases(setup.PREBUILT_URL) - self.assertEqual(bases[0], setup.PREBUILT_TAG_URL.format(version=setup.source_version())) - self.assertEqual(bases[-1], setup.PREBUILT_URL) - # and if a four-part project version ever exists, its tag is tried first, the latest release is the fallback - with mock.patch.object(setup, "source_version", return_value="0.1.40.1"): - self.assertEqual(setup.prebuilt_bases(setup.PREBUILT_URL), - ["https://github.com/Niko1221/Strata/releases/download/v0.1.40.1/", setup.PREBUILT_URL]) - - def test_an_engine_that_says_four_parts_is_read_as_four(self): - with tempfile.TemporaryDirectory() as d: - exe = Path(d) / "strata.exe" - exe.write_bytes(b"MZ\x00engine=0.1.40.2\n\x00") - self.assertEqual(setup.engine_version(exe), (0, 1, 40, 2)) - exe.write_bytes(b"MZ\x00engine=0.1.40\n\x00") - self.assertEqual(setup.engine_version(exe), (0, 1, 40)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_hybrid.py b/tools/test_setup_hybrid.py deleted file mode 100644 index 3a5882e..0000000 --- a/tools/test_setup_hybrid.py +++ /dev/null @@ -1,117 +0,0 @@ -"""#642: setup recommends the expert pool's worker count on a hybrid CPU (the P-cores but the host loop's one, plus -half of the E-cores) and writes nothing new anywhere else; a calibration's measured count wins over the rule. - - python -m unittest tools.test_setup_hybrid -""" -from __future__ import annotations - -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 -from test_setup_golden import PROFILES, install # noqa: E402 - - -def fake_sys(root: Path, caps: list, pmu=None, smt=False) -> None: - """A /sys tree: cpu N's capacity (and, with smt, a sibling CPU per core), and the hybrid PMU lists when given.""" - cpu_dir = root / "devices" / "system" / "cpu" - n = 0 - for core, cap in enumerate(caps): - for _ in range(2 if smt and cap >= 1000 else 1): - d = cpu_dir / f"cpu{n}" - (d / "topology").mkdir(parents=True) - (d / "topology" / "physical_package_id").write_text("0") - (d / "topology" / "core_id").write_text(str(core)) - (d / "cpu_capacity").write_text(str(cap)) - n += 1 - if pmu: - for name, lst in zip(("cpu_core", "cpu_atom"), pmu): - (root / "devices" / name).mkdir(parents=True) - (root / "devices" / name / "cpus").write_text(lst + "\n") - - -class LinuxCores(unittest.TestCase): - """#798: Turbo Boost Max 3.0's "favored" P-cores have a slightly higher cpu_capacity.""" - - def classes(self, caps, **kw): - with tempfile.TemporaryDirectory() as d: - fake_sys(Path(d), caps, **kw) - cl = setup.linux_core_classes(d) - if not cl or max(cl) == min(cl): - return None - p = sum(1 for c in cl if c == max(cl)) - return p, len(cl) - p - - def test_favored_cores_do_not_hide_the_p_cores(self): - caps = [1024, 1012, 1024, 1012, 1012, 1012, 1012, 1012] + [768] * 16 # Core Ultra 7 270K Plus - self.assertEqual(self.classes(caps), (8, 16)) # by capacity: >= 90% of the largest - self.assertEqual(self.classes(caps, pmu=("0-7", "8-23")), (8, 16)) # by the PMU lists - self.assertEqual(setup.hybrid_pool_workers((8, 16)), 15) - - def test_plain_capacities_and_plain_cpus(self): - self.assertEqual(self.classes([1024] * 8 + [512] * 8), (8, 8)) - self.assertIsNone(self.classes([1024] * 8)) # no E-cores - self.assertIsNone(self.classes([1024, 1012, 1012, 1012])) # favored cores only: not hybrid - - def test_smt_siblings_count_once(self): - self.assertEqual(self.classes([1024, 1012] * 4 + [768] * 8, smt=True, pmu=("0-15", "16-23")), (8, 8)) - - def test_no_capacity_files_and_no_pmu_says_nothing(self): - with tempfile.TemporaryDirectory() as d: - fake_sys(Path(d), [1024, 768]) - (Path(d) / "devices/system/cpu/cpu1/cpu_capacity").unlink() - self.assertIsNone(setup.linux_core_classes(d)) - - -class HybridWorkers(unittest.TestCase): - def test_rule(self): - self.assertIsNone(setup.hybrid_pool_workers(None)) - self.assertEqual(setup.hybrid_pool_workers((8, 16)), 15) # i9-14900K: the fork's measured 15 - self.assertEqual(setup.hybrid_pool_workers((6, 8)), 9) # i5-13600K - self.assertEqual(setup.hybrid_pool_workers((4, 8)), 7) # Ryzen AI 9 HX 370 (Zen 5 + Zen 5c) - self.assertIsNone(setup.hybrid_pool_workers((8, 8))) # i7-13700K: all cores measured faster (AMD_HIP.md) - self.assertIsNone(setup.hybrid_pool_workers((8, 4))) - - def test_recommend_keeps_a_given_count(self): - with mock.patch.object(setup, "cpu_cores", lambda: (8, 16)), mock.patch.object(setup, "ok", lambda *a: None): - self.assertEqual(setup.recommend_pool_workers(["--spec", "4"]), ["--spec", "4", "--pool-workers", "15"]) - given = ["--pool-workers", "12"] - self.assertEqual(setup.recommend_pool_workers(given), given) - with mock.patch.object(setup, "cpu_cores", lambda: None): - self.assertEqual(setup.recommend_pool_workers(["--spec", "4"]), ["--spec", "4"]) - - def test_install_on_a_hybrid_cpu(self): - ram, found = PROFILES["96GB-1x16GB"] - hybrid = [mock.patch.object(setup, "cpu_cores", lambda: (8, 16))] - code, text, cfg, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"], extra=hybrid) - self.assertEqual(code, 0, text) - a = cfg["args"] - self.assertEqual(a[a.index("--pool-workers") + 1], "15") - self.assertIn("hybrid CPU (8 performance + 16 efficiency cores)", text) - # the same PC without the hybrid CPU: the config is the one it always was (no --pool-workers) - code, text, plain, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"]) - self.assertEqual(code, 0, text) - self.assertNotIn("--pool-workers", plain["args"]) - i = a.index("--pool-workers") - self.assertEqual(a[:i] + a[i + 2:], plain["args"]) - - def test_calibration_wins(self): - ram, found = PROFILES["96GB-1x16GB"] - cal = {"settings": {"--pool-workers": "11"}, "date": "2026-10-03"} - extra = [mock.patch.object(setup, "cpu_cores", lambda: (8, 16)), - mock.patch.object(setup, "saved_calibration", lambda cfg: cal)] - code, text, cfg, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"], extra=extra) - self.assertEqual(code, 0, text) - a = cfg["args"] - self.assertEqual(a[a.index("--pool-workers") + 1], "11") - self.assertEqual(a.count("--pool-workers"), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_lfm.py b/tools/test_setup_lfm.py deleted file mode 100644 index 217fa70..0000000 --- a/tools/test_setup_lfm.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Tests for setup.py's LFM2.5-24B-A2B (docs/BACKENDS.md): its five pinned files, two repositories, the estimates -for an 8 GB card, and the install by GLM's steps with no draft model and no image encoder. Mocked like -tools/test_setup_glm.py, whose harness this uses. - - python -m unittest tools.test_setup_lfm -""" -from __future__ import annotations - -import json -import sys -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 -from tools import test_setup_glm as glm_tests # noqa: E402 - -FAM = setup.FAMILIES["lfm25"] -# setup's order: the size taken with the RAM for it, the one with the least RAM, then the others -SIZES = [("UD-Q4_K_XL", 14876901632), ("UD-Q3_K_XL", 10947100928), ("QAD-Q4_0", 13578190880), - ("UD-Q6_K_XL", 21861204224), ("Q8_0", 25493733344)] - - -class Pins(unittest.TestCase): - def test_the_files(self): - self.assertEqual(list(setup.family_models("lfm25")), [m for m, _ in SIZES]) - self.assertRegex(FAM["hf"], r"^https://huggingface.co/unsloth/LFM2.5-24B-A2B-GGUF/resolve/[0-9a-f]{40}/$") - self.assertEqual(list(FAM["sha256"]), [f"LFM2.5-24B-A2B-{m}.gguf" for m, _ in SIZES]) - for size, n in SIZES: - file = f"LFM2.5-24B-A2B-{size}.gguf" - d = FAM["models"][size] - self.assertEqual((setup.model_file(FAM, size, 1), setup.model_shards(FAM, size)), (file, 1)) - self.assertEqual(FAM["sha256"][file][0], n) - self.assertRegex(FAM["sha256"][file][1], r"^[0-9a-f]{64}$") - self.assertAlmostEqual(n / 1e9, d["download_gb"], delta=0.05) - self.assertLess(d["arena_gb"], d["download_gb"]) - self.assertEqual(d["ram_gb"], round(setup.poly_ram_need(d, 8.0)), size) - # Liquid AI's own file is in its repository, the others in Unsloth's - self.assertRegex(FAM["models"]["QAD-Q4_0"]["hf"], - r"^https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-GGUF/resolve/[0-9a-f]{40}/$") - self.assertEqual([m for m, d in FAM["models"].items() if "hf" in d], ["QAD-Q4_0"]) - - def test_the_about_line_says_the_first_size(self): - n = setup.poly_ram_need(FAM["models"]["UD-Q4_K_XL"], 8.0) - self.assertIn(f"~{n:.0f} GB of RAM beside an 8 GB card", FAM["about"]) - - -class Batch(unittest.TestCase): - def test_where_the_card_holds_every_expert_beside_it(self): - sizes = FAM["models"] - # LFM2.5 on any card from 8 GB; Qwen3.6 where the card holds every expert of the size - for vram, want in ((6.0, []), (7.6, list(sizes)), (31.8, list(sizes))): - with self.subTest(vram=vram): - self.assertEqual([m for m, d in sizes.items() if setup.poly_batch(FAM, d, vram, 32768)], want) - qwen = setup.FAMILIES["qwen36"] - for vram, ctx, want in ((8.0, 32768, []), (23.6, 32768, ["UD-Q3_K_M", "UD-Q2_K_XL"]), - (23.6, 131072, ["UD-Q3_K_M", "UD-Q2_K_XL"]), (31.8, 131072, list(qwen["models"]))): - with self.subTest(vram=vram, ctx=ctx): - self.assertEqual([m for m, d in qwen["models"].items() if setup.poly_batch(qwen, d, vram, ctx)], want) - # a family without the figure keeps the engine's batch - self.assertFalse(setup.poly_batch(setup.FAMILIES["gemma4"], setup.FAMILIES["gemma4"]["models"]["UD-Q2_K_XL"], - 96.0, 32768)) - - -class Main(unittest.TestCase): - setUp, tearDown, main = glm_tests.Main.setUp, glm_tests.Main.tearDown, glm_tests.Main.main - - def test_install_each_size(self): - for size, _n in SIZES: - with self.subTest(size): - self.downloads, self.runs, self.verified = [], [], [] - code, out, _ = self.main(family="lfm25", model=size, ram=64.0, vram=8188 / 1024) - self.assertEqual(code, 0, out) - cfg = json.loads((self.t / f"strata-lfm25-{size.lower()}.json").read_text()) # one config a size - file = f"LFM2.5-24B-A2B-{size}.gguf" - self.assertEqual(self.downloads, [FAM["models"][size].get("hf", FAM["hf"]) + file]) - self.assertEqual(self.verified, [(file, *FAM["sha256"][file])]) - tag = "lfm25-" + size - pack = self.t / "data" / "packs" / tag.lower() - self.assertEqual([Path(r[1]).name for r in self.runs], ["strata_tokenizer.py"]) - args = cfg["args"] - self.assertEqual(Path(args[args.index("--model") + 1]), self.t / "models" / tag / file) - self.assertEqual(Path(args[args.index("--expert-profile") + 1]), pack / "expert-profile.txt") - for flag in ("--draft-model", "--tail-skip"): - self.assertNotIn(flag, args) - self.assertEqual(args[args.index("--prompt-batch") + 1], "2048") # on the 8 GB card too - self.assertEqual(cfg["model_name"], f"lfm2.5-24b-a2b-{size.lower()}") - self.assertEqual(cfg["display_name"], f"LFM2.5-24B-A2B {size}") - self.assertNotIn("vision", cfg) - - def test_a_card_that_holds_every_expert_reads_2048_tokens_at_a_time(self): - code, out, _ = self.main(family="lfm25", model="Q8_0", ram=64.0, vram=32607 / 1024) # an RTX 5090 - self.assertEqual(code, 0, out) - args = json.loads((self.t / "strata-lfm25-q8_0.json").read_text())["args"] - self.assertEqual(args[args.index("--prompt-batch") + 1], "2048") - - def test_the_context_question_has_this_model_s_laptop_numbers(self): - code, out, _ = self.main(family="lfm25", ram=32.0, vram=8.0) - self.assertEqual(code, 0, out) - for line in ("32K tokens (recommended; 8 GB card: 69-74 tokens/s after a full prompt)", - "128K tokens (2.0 GB more VRAM; 8 GB card: 35-37 tokens/s after a full prompt)"): - self.assertIn(line, out) - self.assertNotIn("52-58", out) # Qwen3.6's and the others' - - def test_the_size_taken_without_a_name(self): - for ram, size in ((32.0, "UD-Q4_K_XL"), (14.0, "UD-Q3_K_XL")): - with self.subTest(ram=ram): - code, out, _ = self.main(family="lfm25", ram=ram, vram=8.0) - self.assertEqual(code, 0, out) - self.assertTrue((self.t / f"strata-lfm25-{size.lower()}.json").is_file(), out) - - def test_windows_is_not_asked(self): - code, out, cfg = self.main(win=True, family="lfm25", ram=32.0, vram=8.0) - self.assertEqual(code, 0, out) - self.assertNotIn("Windows", out) - - def test_vision_is_not_used(self): - code, out, cfg = self.main(["--vision", "yes"], family="lfm25", ram=32.0, vram=8.0) - self.assertEqual(code, 0, out) - self.assertIn("not used with LFM2.5-24B-A2B", out) - self.assertNotIn("vision", cfg) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_llama_archive.py b/tools/test_setup_llama_archive.py deleted file mode 100644 index 9a7bda5..0000000 --- a/tools/test_setup_llama_archive.py +++ /dev/null @@ -1,173 +0,0 @@ -"""#1797: a damaged llama.cpp source zip must not be kept as an already-downloaded source. - - python tools/test_setup_llama_archive.py - -Only tiny local zip files and the standard library are used; no GPU, model or network is needed. -""" -from __future__ import annotations - -import contextlib -import io -import sys -import tempfile -import unittest -import zipfile -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -class LlamaSourceArchive(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - self.source = self.root / "source.zip" - self.prefix = "llama.cpp-" + setup.LLAMA_CPP_COMMIT - with zipfile.ZipFile(self.source, "w", compression=zipfile.ZIP_STORED) as z: - z.writestr(self.prefix + "/ggml/CMakeLists.txt", "ggml fixture") - z.writestr(self.prefix + "/gguf-py/fixture.txt", "gguf fixture") - z.writestr(self.prefix + "/tools/ui/not-needed.txt", "unused web UI") - self.archive = self.root / "third_party" / f"llama.cpp-{setup.LLAMA_CPP_COMMIT[:7]}.zip" - self.marker = self.archive.with_name(self.archive.name + ".done") - self.llama = self.archive.parent / "llama.cpp" - self.archive.parent.mkdir() - self.unrelated = self.archive.parent / "user-notes.txt" - self.unrelated.write_text("keep this", encoding="utf-8") - stack = contextlib.ExitStack() - self.addCleanup(stack.close) - stack.enter_context(mock.patch.object(setup, "ROOT", self.root)) - # a plain path: download() copies it (file:// plus a Windows drive letter is not one) - stack.enter_context(mock.patch.object(setup, "LLAMA_CPP_ZIP", str(self.source))) - stack.enter_context(mock.patch.object(setup.urllib.request, "urlopen", - side_effect=AssertionError("test must not use the network"))) - stack.enter_context(contextlib.redirect_stdout(io.StringIO())) - - def cached(self, data): - self.archive.write_bytes(data) - setup.mark(self.archive) - - def assert_cache_removed(self): - self.assertFalse(self.archive.exists()) - self.assertFalse(self.marker.exists()) - self.assertEqual(self.unrelated.read_text(encoding="utf-8"), "keep this") - - def assert_installed(self, result): - self.assertEqual(result, self.llama) - self.assertEqual((result / "ggml/CMakeLists.txt").read_text(), "ggml fixture") - self.assertEqual((result / "gguf-py/fixture.txt").read_text(), "gguf fixture") - self.assertFalse((result / "tools/ui").exists()) - self.assertFalse((self.archive.parent / "_unpack").exists()) - self.assert_cache_removed() - - def test_success_uses_local_source_and_removes_archive_and_mark(self): - self.assert_installed(setup.get_llama_cpp()) - - def test_installed_source_is_reused_without_downloading(self): - self.assert_installed(setup.get_llama_cpp()) - with mock.patch.object(setup, "download", side_effect=AssertionError("already installed")): - self.assertEqual(setup.get_llama_cpp(), self.llama) - - def test_bad_cached_zip_is_removed_and_the_next_call_recovers(self): - self.cached(b"not a zip") - with self.assertRaises(zipfile.BadZipFile): - setup.get_llama_cpp() - self.assert_cache_removed() - self.assert_installed(setup.get_llama_cpp()) - - def test_a_bad_new_download_is_also_removed(self): - self.source.write_bytes(b"not a zip") - with self.assertRaises(zipfile.BadZipFile): - setup.get_llama_cpp() - self.assert_cache_removed() - - def test_truncated_cached_zip_is_removed(self): - self.cached(self.source.read_bytes()[:-22]) # missing the end-of-central-directory record - with self.assertRaises(zipfile.BadZipFile): - setup.get_llama_cpp() - self.assert_cache_removed() - self.assert_installed(setup.get_llama_cpp()) - - def test_crc_failure_during_extraction_is_removed_and_the_next_call_recovers(self): - # Keep the ZIP directory intact; the second member fails its CRC after the first was extracted. - self.cached(self.source.read_bytes().replace(b"gguf fixture", b"BAD! fixture", 1)) - self.llama.mkdir() - user_file = self.llama / "user-file.txt" - user_file.write_text("keep until a source was unpacked", encoding="utf-8") - with self.assertRaisesRegex(zipfile.BadZipFile, "Bad CRC-32"): - setup.get_llama_cpp() - self.assert_cache_removed() - self.assertTrue((self.archive.parent / "_unpack" / self.prefix / "ggml/CMakeLists.txt").is_file()) - self.assertEqual(user_file.read_text(), "keep until a source was unpacked") - self.assert_installed(setup.get_llama_cpp()) - - def test_original_bad_zip_exception_is_preserved(self): - for target in ("ZipFile", "ZipFile.extractall"): - with self.subTest(target=target): - self.cached(self.source.read_bytes()) - error = zipfile.BadZipFile("original error") - with mock.patch("setup.zipfile." + target, side_effect=error), \ - self.assertRaises(zipfile.BadZipFile) as caught: - setup.get_llama_cpp() - self.assertIs(caught.exception, error) - self.assert_cache_removed() - - def test_missing_archive_or_mark_during_cleanup_is_harmless(self): - for absent in (self.archive, self.marker): - with self.subTest(absent=absent.name): - self.cached(b"not a zip") - error = zipfile.BadZipFile("original error") - - def fail_after_removal(*args, **kwargs): - absent.unlink() - raise error - - with mock.patch.object(zipfile, "ZipFile", side_effect=fail_after_removal), \ - self.assertRaises(zipfile.BadZipFile) as caught: - setup.get_llama_cpp() - self.assertIs(caught.exception, error) - self.assert_cache_removed() - - def test_cleanup_failure_does_not_replace_the_bad_zip_error(self): - real_unlink = Path.unlink - for blocked in (self.archive, self.marker): - with self.subTest(blocked=blocked.name): - self.cached(b"not a zip") - error = zipfile.BadZipFile("original error") - - def deny_unlink(path, *args, **kwargs): - if path == blocked: - raise PermissionError("held open") - return real_unlink(path, *args, **kwargs) - - with mock.patch.object(zipfile, "ZipFile", side_effect=error), \ - mock.patch.object(Path, "unlink", deny_unlink), mock.patch.object(setup, "warn") as warn, \ - self.assertRaises(zipfile.BadZipFile) as caught: - setup.get_llama_cpp() - self.assertIs(caught.exception, error) - self.assertEqual(self.archive.exists(), blocked == self.archive) - self.assertTrue(self.marker.exists()) - self.assertEqual(self.unrelated.read_text(), "keep this") - warn.assert_called_once() - self.assertIn("held open", warn.call_args.args[0]) - - def test_permission_and_disk_errors_do_not_discard_a_valid_archive(self): - for target in ("ZipFile", "ZipFile.extractall"): - for error in (PermissionError("access denied"), OSError("disk full")): - with self.subTest(target=target, error=type(error).__name__): - data = self.source.read_bytes() - self.cached(data) - with mock.patch("setup.zipfile." + target, side_effect=error), \ - self.assertRaises(OSError) as caught: - setup.get_llama_cpp() - self.assertIs(caught.exception, error) - self.assertEqual(self.archive.read_bytes(), data) - self.assertTrue(self.marker.exists()) - self.assertEqual(self.unrelated.read_text(), "keep this") - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_lowram.py b/tools/test_setup_lowram.py deleted file mode 100644 index b7240b8..0000000 --- a/tools/test_setup_lowram.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Tests for setup.py's low-RAM messages and the paging question (#250): the one-GPU warning says why and shows the -RAM math, and an explicit --low-ram off installs with --yes instead of stopping at "Install it anyway?" (default -n). Mocked input - no GPU, no downloads. - - python -m unittest tools.test_setup_lowram -""" -from __future__ import annotations - -import contextlib -import io -import sys -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -def run(fn, *args, stdin=None): - """-> (exit code or None, printed text); `stdin` answers input() (None: never asked).""" - out = io.StringIO() - asked = [] - - def fake_input(prompt=""): - asked.append(prompt) - if stdin is None: - raise AssertionError(f"asked {prompt!r} with --yes") - return stdin - - code = None - with contextlib.redirect_stdout(out), mock.patch("builtins.input", fake_input): - try: - fn(*args) - except SystemExit as e: - code = e.code - return code, out.getvalue(), asked - - -class OneGpuWhy(unittest.TestCase): - def test_auto_shows_the_ram_math(self): - lines = setup.low_ram_one_gpu_why("IQ3_XXS", 46, "auto") # the #250 report: 46 GB, IQ3_XXS - text = "\n".join(lines) - arena = setup.MODELS["IQ3_XXS"]["arena_gb"] - need = arena + setup.LOW_RAM_HEADROOM_GB - self.assertIn(f"{arena:.0f} + {setup.LOW_RAM_HEADROOM_GB} = {need:.0f} GB", text) - self.assertIn("this PC has 46 GB", text) - self.assertIn("layer split", text) # why one GPU is recommended - self.assertIn("--gpus 0,1", text) # #364 #384: and the way to use them all - self.assertIn("OS file cache", text) - self.assertNotIn("--low-ram off", text) # (that pages the experts: not the way) - - def test_an_explicit_choice_says_so(self): - text = "\n".join(setup.low_ram_one_gpu_why("Q2_0", 64, "resident")) - self.assertIn("you chose the low-RAM mode (--low-ram resident)", text) - - -class PagingQuestion(unittest.TestCase): - MODEL, RAM = "IQ3_XXS", 46 # 60 GB wanted, 46 here - - def test_yes_with_low_ram_off_installs(self): - code, out, asked = run(setup.confirm_paging, self.MODEL, self.RAM, "off", True) - self.assertIsNone(code, out) - self.assertEqual(asked, []) - self.assertIn("installing IQ3_XXS with 46 GB of RAM, as you chose (--low-ram off)", out) - - def test_yes_with_auto_still_stops(self): - code, out, asked = run(setup.confirm_paging, self.MODEL, self.RAM, "auto", True) - self.assertEqual(code, 1) - self.assertIn("IQ3_XXS needs about 60 GB of RAM; this PC has 46 GB", out) - self.assertIn("--low-ram off --yes", out) # the way to insist - - def test_interactive(self): - for choice, answer, want in (("off", "", None), ("auto", "", 1), ("auto", "y", None), ("off", "n", 1)): - with self.subTest(choice=choice, answer=answer): - code, out, asked = run(setup.confirm_paging, self.MODEL, self.RAM, choice, False, stdin=answer) - self.assertEqual(code, want, out) - self.assertEqual(len(asked), 1) - self.assertIn("[y]" if choice == "off" else "[n]", asked[0]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_mac.py b/tools/test_setup_mac.py deleted file mode 100644 index 900180a..0000000 --- a/tools/test_setup_mac.py +++ /dev/null @@ -1,281 +0,0 @@ -"""Tests for setup on a Mac (metal/setup_mac.py and setup.py's hand-over): the Mac check, the pack recommended by -unified memory, what a bigger choice risks, the engine arguments with the Metal defaults and the config. Runs on any -PC: sysctl / sw_vers / xcode-select are mocked. No GPU, no network. - - python -m unittest tools.test_setup_mac -""" -from __future__ import annotations - -import os -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "metal")) -import setup # noqa: E402 -import setup_mac as M # noqa: E402 - - -def fake_run(values: dict, clt_rc=0): - def run(cmd, **kw): - if cmd[0] == "sysctl": - return subprocess.CompletedProcess(cmd, 0, values.get(cmd[2], ""), "") - if cmd[0] == "sw_vers": - return subprocess.CompletedProcess(cmd, 0, values.get("macos", ""), "") - if cmd[0] == "xcode-select": - return subprocess.CompletedProcess(cmd, clt_rc, "/Library/Developer/CommandLineTools" if clt_rc == 0 else "", - "") - raise AssertionError(cmd) - return run - - -M5 = {"machdep.cpu.brand_string": "Apple M5 Max", "hw.memsize": str(128 * 2 ** 30), "macos": "27.2", - "hw.perflevel0.physicalcpu": "12"} - - -class MacCheck(unittest.TestCase): - def test_reads_chip_memory_macos_and_tools(self): - with mock.patch.object(M.platform, "machine", return_value="arm64"): - info = M.mac_info(fake_run(M5)) - self.assertEqual(info["chip"], "Apple M5 Max") - self.assertAlmostEqual(info["ram_gb"], 128.0) - self.assertEqual(info["macos"], "27.2") - self.assertTrue(info["arm64"]) - self.assertTrue(info["clt"]) - self.assertEqual(M.mac_problems(info), []) - - def test_intel_old_macos_and_missing_tools_are_named(self): - with mock.patch.object(M.platform, "machine", return_value="x86_64"): - info = M.mac_info(fake_run({**M5, "macos": "14.6", "machdep.cpu.brand_string": "Intel Core i9"}, clt_rc=2)) - p = " | ".join(M.mac_problems(info)) - self.assertIn("Apple Silicon", p) - self.assertIn("macOS 15", p) - self.assertIn("xcode-select --install", p) - - -class Recommendation(unittest.TestCase): - def test_by_memory(self): - # IQ3_S and UD-Q4_K_XL are the recommended sizes; IQ3_S is the default wherever it stays resident - self.assertEqual(M.RECOMMENDED, ("IQ3_S", "UD-Q4_K_XL")) - rec, notes = M.recommend_model(128) - self.assertEqual(rec, "IQ3_S") - self.assertTrue(any("UD-Q4_K_XL" in n and "higher quality" in n for n in notes)) # named next to it - rec96, notes96 = M.recommend_model(96) - self.assertEqual(rec96, "IQ3_S") - self.assertFalse(notes96) # UD-Q4_K_XL does not fit 96 GB resident: no note - self.assertEqual(M.recommend_model(64)[0], "Q2_0") # no recommended size fits: the largest that does - self.assertEqual(M.recommend_model(80)[0], "IQ3_XXS") - rec, notes = M.recommend_model(32) - self.assertEqual(rec, "Q2_0") - self.assertTrue(notes and "stream" in notes[0] and "~14 tok/s" in notes[0]) - self.assertTrue(M.streams("Q2_0", 32) and M.streams("Q2_0", 48) and not M.streams("Q2_0", 64)) - - def test_a_bigger_choice_is_kept_with_a_note(self): - notes = M.model_note("IQ3_XXS", 64) - self.assertTrue(any("stream from the SSD" in n for n in notes)) - self.assertEqual(M.model_note("Q2_0", 128), []) - self.assertEqual(M.model_note("IQ3_S", 128), []) - - def test_context(self): - self.assertEqual(M.recommend_context(64), 32768) - self.assertEqual(M.recommend_context(128), 65536) - - -class Config(unittest.TestCase): - def test_engine_args_carry_the_metal_defaults(self): - args = M.engine_args(Path("/p/packs/q2_0"), [Path("/m/a-00001.gguf"), Path("/m/a-00002.gguf")], - Path("/d/mtp/rt"), 32768) - self.assertEqual(args[args.index("--spec") + 1], "2") - self.assertEqual(args[args.index("--native") + 1], str(Path("/m/a-00001.gguf"))) - self.assertEqual(args[args.index("--ple-gguf") + 1], str(Path("/m/a-00002.gguf"))) - self.assertEqual(args[args.index("--mtp") + 1], str(Path("/d/mtp/rt"))) - self.assertIn("--expert-profile", args) - self.assertNotIn("--hc-q8", args) # Q8_0 HC is the engine's own default on Metal - st = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 32768, stream=True) - self.assertNotIn("--mtp", st) # streaming: one token per step, no draft layer - self.assertEqual(st[st.index("--suffix-draft") + 1], "0") - self.assertEqual(st[st.index("--spec") + 1], "2") - # a big Mac that streams (UD-Q5/Q6 on 128 GB) keeps the draft layer, with a longer window - big = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 65536, stream=True, - ram_gb=128) - self.assertEqual(big[big.index("--mtp") + 1], str(Path("/d/mtp/rt"))) - self.assertEqual(big[big.index("--spec") + 1], "3") - self.assertEqual(big[big.index("--suffix-draft") + 1], "0") - small = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 32768, stream=True, - ram_gb=32) - self.assertNotIn("--mtp", small) - self.assertTrue(M.stream_mtp(False, 16) and M.stream_mtp(True, 128) and not M.stream_mtp(True, 64)) - - def test_config_is_a_model_config_with_the_metal_backend(self): - cfg = M.mac_config(Path("/r/build-metal/strata"), ["--pack", "x"], Path("/p"), "qwen3.8-flash-next-q2_0", - "Q2_0", 8080) - self.assertEqual(cfg["backend"], "metal") - self.assertEqual(cfg["tokenizer"], str(Path("/p") / "tokenizer")) - self.assertTrue(cfg["exe"] and isinstance(cfg["args"], list)) - - -class Vision(unittest.TestCase): - def test_the_projector_is_pinned_and_the_encoder_builds_with_metal(self): - self.assertIn("mmproj-Qwen3.8-Flash-Next-BF16.gguf", M.VISION_SHA256) - src = (ROOT / "metal" / "setup_mac.py").read_text(encoding="utf-8") - self.assertIn('"-DSTRATA_VISION_CUDA=OFF"', src) - self.assertIn('cfg["args"] += ["--vision"]', src) - - -class ExpertsFile(unittest.TestCase): - """The streaming Mac's .experts: written only with room on the disk, else a warning and the GGUF.""" - - def run_it(self, free_gb, done=False): - import tempfile - sys.path.insert(0, str(ROOT / "metal" / "tools")) - import stream_experts - d = Path(tempfile.mkdtemp()) - native = d / "m.gguf" - native.write_bytes(b"") - if done: - (d / "m.gguf.experts").write_bytes(b"") - (d / "m.gguf.experts.done").write_text("x") - with mock.patch.object(stream_experts, "size_bytes", return_value=40e9), \ - mock.patch.object(M.S, "free_gb", return_value=free_gb), \ - mock.patch.object(M.S, "run") as run, mock.patch.object(M.S, "warn") as warn, \ - mock.patch.object(M.S, "mark") as mark, mock.patch.object(M.S, "say"), mock.patch.object(M.S, "ok"): - M.experts_file(native) - return run, warn, mark - - def test_fits_needs_the_margin(self): - self.assertFalse(M.experts_file_fits(40, 40 + M.EXPERTS_MARGIN_GB - 0.1)) - self.assertTrue(M.experts_file_fits(40, 40 + M.EXPERTS_MARGIN_GB)) - - def test_written_and_verified_with_room(self): - run, warn, mark = self.run_it(100) - self.assertIn("--verify", run.call_args[0][0]) - self.assertTrue(str(run.call_args[0][0][1]).endswith("stream_experts.py")) - mark.assert_called_once() - warn.assert_not_called() - - def test_too_little_disk_warns_and_goes_on(self): - run, warn, mark = self.run_it(45) - run.assert_not_called() - mark.assert_not_called() - self.assertIn("not written", warn.call_args[0][0]) - - def test_done_is_not_written_again(self): - run, warn, mark = self.run_it(100, done=True) - run.assert_not_called() - - -class HandOver(unittest.TestCase): - def test_darwin_hands_the_run_to_setup_mac(self): - with mock.patch.object(setup.sys, "platform", "darwin"), \ - mock.patch.object(setup.subprocess, "call", return_value=0) as call, \ - mock.patch.object(setup.sys, "argv", ["setup.py", "--model", "Q2_0", "--yes"]): - self.assertEqual(setup.main(), 0) - cmd = call.call_args[0][0] - self.assertTrue(cmd[1].endswith(str(Path("metal") / "setup_mac.py"))) - self.assertEqual(cmd[2:], ["--model", "Q2_0", "--yes"]) - - def test_other_platforms_never_reach_it(self): - src = (ROOT / "setup.py").read_text(encoding="utf-8") - self.assertIn('if sys.platform == "darwin":', src) - with mock.patch.object(setup, "mac_setup", side_effect=AssertionError("called")), \ - mock.patch.object(setup.sys, "platform", "linux"), \ - mock.patch.object(setup.sys, "argv", ["setup.py", "--inspect", "x"]), \ - mock.patch.object(setup.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)): - with self.assertRaises(SystemExit): - setup.main() - - def test_setup_sh_fetches_a_pinned_python_on_macos_only(self): - sh = (ROOT / "setup.sh").read_text(encoding="utf-8") - self.assertIn('[ "$(uname -s)" = Darwin ]', sh) - self.assertIn("83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8", sh) - - -class RepackGuard(unittest.TestCase): - """No engine beside a repack: the locks, and the resident rule that matches the engine's arena_budget.h.""" - - def test_resident_rule_matches_the_engine(self): - # the resident cap: Metal's working set (3/4), and on a Mac of 64 GB or more the RAM less 30% - self.assertAlmostEqual(M.gpu_budget_gb(128), 128 * 1.073741824 * 0.70, places=3) # 96.2 GB, as arena_budget.h - self.assertAlmostEqual(M.gpu_budget_gb(96), 96 * 1.073741824 * 0.70, places=3) - self.assertAlmostEqual(M.gpu_budget_gb(32), 32 * 1.073741824 * 0.75, places=3) # a small Mac: the working set - self.assertFalse(M.streams("UD-Q4_K_XL", 128)) # 82.6 + 8 GB: resident (measured: nothing compressed) - self.assertTrue(M.streams("UD-Q5_K_XL", 128)) - self.assertTrue(M.streams("UD-Q4_K_XL", 96)) - - @unittest.skipIf(sys.platform == "win32", "os.kill(pid, 0) is a probe on macOS and Linux only") - def test_a_live_lock_is_seen_a_stale_one_is_dropped(self): - import os - import tempfile - with tempfile.TemporaryDirectory() as d: - d = Path(d) - self.assertEqual(M.repack_running(d), []) - (d / "m-metal.gguf.repack.lock").write_text(str(os.getppid())) # a live process that is not us - self.assertEqual(M.repack_running(d), [os.getppid()]) - (d / "m-metal.gguf.repack.lock").write_text("999999999") # no such process - self.assertEqual(M.repack_running(d), []) - self.assertFalse((d / "m-metal.gguf.repack.lock").exists()) # the stale lock was removed - (d / M.PREPARE_LOCK).write_text(str(os.getppid())) - self.assertEqual(M.repack_running(d), [os.getppid()]) - (d / M.PREPARE_LOCK).write_text(str(os.getpid())) # our own setup's lock does not stop us - self.assertEqual(M.repack_running(d), []) - - @unittest.skipIf(sys.platform == "win32", "os.kill(pid, 0) is a probe on macOS and Linux only") - def test_start_refuses_while_a_repack_runs(self): - import json - import os - import tempfile - with tempfile.TemporaryDirectory() as d: - d = Path(d) - gguf, exe = d / "m-metal.gguf", d / "strata" - gguf.write_bytes(b"x") - exe.write_bytes(b"x") - cfg = d / "strata-x.json" - cfg.write_text(json.dumps({"exe": str(exe), "args": ["--native", str(gguf)], "port": 8080})) - (d / "m-metal.gguf.repack.lock").write_text(str(os.getppid())) - with mock.patch.object(M.subprocess, "call", side_effect=AssertionError("started")), \ - mock.patch.object(M.S, "fail", side_effect=SystemExit("refused")) as fail: - with self.assertRaises(SystemExit): - M.start(cfg, None, False) - self.assertIn("repack is still running", fail.call_args[0][0]) - - def test_the_repack_writes_in_bounded_pieces(self): - src = (ROOT / "metal" / "tools" / "metal_repack.py").read_text(encoding="utf-8") - self.assertIn("SYNC_EVERY = 1 << 30", src) # flushed every GiB - self.assertIn("nocache(o)", src) # F_NOCACHE on the output - self.assertIn("buffering=0", src) # write() is a write - self.assertNotIn("mmap", src) # no dirty mapping of the output - - -class Source(unittest.TestCase): - """setup.py hands a Mac over before its own parser runs, so the Mac parser has to know --source: - source_hint() recommends it on every platform (#2363).""" - - def test_the_source_flag_reaches_strata_source(self): - env = mock.patch.dict(os.environ, {}, clear=False) - env.start() - self.addCleanup(env.stop) - os.environ.pop("STRATA_SOURCE", None) - warnings = [] - # setup.data_folder() is mocked: the real one moves the model files of this checkout and of the data folder in - # the user's settings.json into --data-dir, and saves that dir as the new data folder; with a temp dir that - # deletes the models on exit and leaves settings.json pointing at a deleted directory - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(setup, "data_folder", lambda requested: (Path(tmp), [])), \ - mock.patch("subprocess.run", fake_run(M5)), \ - mock.patch.object(setup, "warn", lambda *a, **k: warnings.append(" ".join(str(x) for x in a))), \ - mock.patch.object(setup, "say", lambda *a, **k: None), \ - mock.patch.object(setup, "ok", lambda *a, **k: None), \ - mock.patch.object(setup, "step", lambda *a, **k: None): - M.main(["--source", "modelscope", "--yes", "--check", "--data-dir", tmp]) - self.assertEqual(os.environ.get("STRATA_SOURCE"), "modelscope") - self.assertFalse([w for w in warnings if "--source" in w], - f"--source was not used: {warnings}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_menu.py b/tools/test_setup_menu.py deleted file mode 100644 index b195c52..0000000 --- a/tools/test_setup_menu.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Tests for setup.py's model menu (0.1.44): the family order, NVFP4 hidden on AMD and Intel, the NVFP4 line's card note -(RTX 50 native FP4, older RTX slower than UD-IQ4_XS), the Unsloth sizes in order with images on, and the prebuilt -install removing a stale strata_kq library. - - python -m unittest tools.test_setup_menu -""" -from __future__ import annotations - -import sys -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - - -class FamilyOrder(unittest.TestCase): - def test_the_menu_order_on_nvidia(self): - fams = setup.menu_families(False) + list(setup.OWN_PATH_FAMILIES) - self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "nvfp4", "glm", "deepseek", "lfm25", "qwen36", - "ornith", "gemma4", "tiel", "minicpmv", "qwen36-strata"]) - - def test_the_default_stays_the_first_family(self): - self.assertEqual(setup.menu_families(False)[0], "qwen") - self.assertIn("GSQ-RCO", setup.FAMILIES["qwen"]["by"]) - - def test_nvfp4_is_not_listed_on_amd_and_intel(self): - fams = setup.menu_families(True) - self.assertNotIn("nvfp4", fams) - self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "glm", "deepseek", "lfm25", "qwen36", "ornith", - "gemma4", "tiel", "minicpmv"]) - self.assertIn("nvfp4", setup.FAMILIES) # --family nvfp4 still exists, and says why not - - def test_the_unsloth_line_names_the_alternative_on_amd_and_intel(self): - self.assertIn("UD-IQ4_XS", setup.family_menu_note("unsloth", True, None)) - self.assertEqual(setup.family_menu_note("unsloth", False, {"arch": 86}), "") - self.assertEqual(setup.family_menu_note("coder", True, None), "") - - -class Nvfp4Note(unittest.TestCase): - def test_rtx_50_has_native_fp4(self): - line = setup.family_menu_note("nvfp4", False, {"arch": 120, "name": "RTX 5070"}) - self.assertIn("native FP4 on this card", line) - - def test_older_rtx_runs_but_is_slower_than_ud_iq4_xs(self): - for arch in (75, 86, 89): - line = setup.family_menu_note("nvfp4", False, {"arch": arch}) - self.assertIn("runs, but UD-IQ4_XS is faster on this card", line, arch) - self.assertNotIn("native FP4", line) - - def test_an_avx2_cpu_is_told_its_rows_but_not_refused(self): # #2347 - line = setup.family_menu_note("nvfp4", False, {"arch": 120}, avx2=True, avx512=False) - self.assertIn("no AVX-512", line) - self.assertIn("AVX2", line) - self.assertIn("native FP4 on this card", line) # the card part is unchanged - self.assertTrue(setup.nvfp4_cpu_note(True, False)) - - def test_an_avx512_cpu_and_a_cpu_without_avx2_get_no_cpu_note(self): - self.assertEqual(setup.nvfp4_cpu_note(True, True), "") - self.assertEqual(setup.nvfp4_cpu_note(False, False), "") # the older-CPU build says its own piece - line512 = setup.family_menu_note("nvfp4", False, {"arch": 120}) - self.assertNotIn("AVX", line512) - self.assertEqual(line512, setup.family_menu_note("nvfp4", False, {"arch": 120}, avx2=True, avx512=True)) - - def test_the_line_gives_the_download_and_the_ram_need(self): - line = setup.family_menu_note("nvfp4", False, {"arch": 120}) - d = setup.MODELS["NVFP4"] - self.assertIn(f"{d['download_gb']:.0f} GB download", line) - self.assertIn(f"~{d['ram_gb']} GB of RAM", line) - - -class UnslothSizes(unittest.TestCase): - def test_the_sizes_in_menu_order(self): - names = [m for m in setup.MODELS if "unsloth" in setup.MODELS[m].get("families", ())] - self.assertEqual(names, ["UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"]) - - def test_nothing_is_experimental_and_images_are_on(self): - for m in ("UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"): - d = setup.MODELS[m] - self.assertFalse(d.get("experimental"), m) - self.assertFalse(d.get("nvidia_only"), m) - self.assertIs(d.get("vision"), True, m) - self.assertIn("download_gb", d) - self.assertIn("ram_gb", d) - self.assertNotIn("experimental", setup.MODELS["UD-Q4_K_XL"]["about"].lower()) - self.assertTrue(setup.FAMILIES["unsloth"]["vision"]) - - def test_the_family_line_lists_every_size(self): - about = setup.FAMILIES["unsloth"]["about"] - for m in ("UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"): - self.assertIn(m, about) - - -class RecommendedSizes(unittest.TestCase): - """0.1.44 (owner): IQ3_S, UD-Q4_K_XL and UD-IQ4_XS are the recommended sizes; recommend, never force.""" - - def names(self, family): - return [m for m in setup.MODELS if family in setup.MODELS[m].get("families", ("qwen", "swift"))] - - def test_qwen_and_swift_default_to_iq3_s_when_it_fits(self): - for fam in ("qwen", "swift"): - n = self.names(fam) - self.assertIn("IQ3_S", n) - self.assertEqual(setup.recommended_size(fam, n, 63.7), "IQ3_S") - self.assertEqual(setup.recommended_size(fam, n, 191.0), "IQ3_S") # not the largest: IQ3_S stays the pick - self.assertEqual([m for m in n if setup.size_tag(fam, m)], ["IQ3_S"]) # the others are choices, unmarked - - def test_without_the_ram_the_largest_that_fits_and_iq3_s_stays_marked(self): - n = self.names("qwen") - self.assertEqual(setup.recommended_size("qwen", n, 61.0), "IQ3_XXS") # IQ3_S needs 62 GB - self.assertEqual(setup.recommended_size("qwen", n, 50.0), "IQ2_XS") - self.assertEqual(setup.size_tag("qwen", "IQ3_S"), " (recommended)") - - def test_coder_has_nothing_marked(self): - n = self.names("coder") - self.assertEqual([setup.size_tag("coder", m) for m in n], [""] * len(n)) - self.assertEqual(setup.recommended_size("coder", n, 64.0), n[0]) - - -class UnslothDefaultEnv(unittest.TestCase): - """0.1.44 (owner): the env setup writes for Unsloth's files (review-quants.md section 5).""" - - def test_q5_and_q6_turn_the_k_quant_prompt_kernels_on_q4_does_not(self): - f = setup.unsloth_default_env - self.assertEqual(f("unsloth", "UD-Q5_K_XL", False, False)["STRATA_MMQ_KQ"], "1") - self.assertEqual(f("unsloth", "UD-Q6_K_XL", True, True)["STRATA_MMQ_KQ"], "1") - for m in ("UD-Q4_K_XL", "UD-IQ4_XS", "Q8_0"): - self.assertNotIn("STRATA_MMQ_KQ", f("unsloth", m, False, False), m) - - def test_hc_q8_on_cuda_for_the_ud_files_only(self): - f = setup.unsloth_default_env - for m in ("UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL"): - self.assertEqual(f("unsloth", m, False, True)["STRATA_HC_Q8"], "1", m) - self.assertNotIn("STRATA_HC_Q8", f("unsloth", m, True, True), m) # not on AMD - self.assertNotIn("STRATA_HC_Q8", f("unsloth", "Q8_0", False, True)) - - def test_tail_skip_off_only_when_every_expert_is_in_ram(self): - f = setup.unsloth_default_env - self.assertEqual(f("unsloth", "UD-Q4_K_XL", False, False)["STRATA_ROUTE_TAIL_SKIP"], "0") - self.assertNotIn("STRATA_ROUTE_TAIL_SKIP", f("unsloth", "UD-Q4_K_XL", False, True)) # budget mode keeps the skip - - def test_other_families_are_untouched(self): - for fam, m in (("qwen", "IQ3_S"), ("swift", "Q2_0"), ("coder", "IQ1_M"), ("nvfp4", "NVFP4")): - self.assertEqual(setup.unsloth_default_env(fam, m, False, False), {}, fam) - - -class EnginePlaceholders(unittest.TestCase): - def test_every_engine_minimum_is_this_release(self): - self.assertEqual(setup.NVFP4_ENGINE, (0, 1, 44)) - self.assertEqual(setup.MIN_ENGINE, (0, 1, 45)) - for m in ("UD-Q5_K_XL", "UD-Q6_K_XL", "NVFP4", "NVFP4-NVIDIA"): - self.assertEqual(setup.MODELS[m]["engine"], (0, 1, 44), m) - self.assertIn("0.1.45", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8").split("project(strata VERSION", 1)[1][:12]) - - -class KqLibrary(unittest.TestCase): - def test_a_zip_without_strata_kq_does_not_leave_an_old_one(self): - with tempfile.TemporaryDirectory() as d: - eng, tmp = Path(d) / "engine", Path(d) / "new" - eng.mkdir() - tmp.mkdir() - (eng / setup.EXE).write_bytes(b"old") - (eng / setup.KQ_LIB).write_bytes(b"old kq") - (tmp / setup.EXE).write_bytes(b"new") - setup.install_unpacked(tmp, eng) - self.assertEqual((eng / setup.EXE).read_bytes(), b"new") - self.assertFalse((eng / setup.KQ_LIB).exists()) - self.assertEqual((eng / setup.PREVIOUS_ENGINE / setup.KQ_LIB).read_bytes(), b"old kq") # a rollback gets it back - - def test_a_zip_with_strata_kq_replaces_it(self): - with tempfile.TemporaryDirectory() as d: - eng, tmp = Path(d) / "engine", Path(d) / "new" - eng.mkdir() - tmp.mkdir() - (eng / setup.KQ_LIB).write_bytes(b"old kq") - (tmp / setup.EXE).write_bytes(b"new") - (tmp / setup.KQ_LIB).write_bytes(b"new kq") - setup.install_unpacked(tmp, eng) - self.assertEqual((eng / setup.KQ_LIB).read_bytes(), b"new kq") - - -class ImageEncoderDefault(unittest.TestCase): - """#2406: "images: yes" gets the CPU encoder on an NVIDIA card under 24 GB (the GPU encoder cost 3-5% of text speed on - 16 GB cards, 35-60% on an RTX 4080 SUPER under Windows); --vision gpu is kept with a note.""" - - def test_yes_follows_the_card(self): - f = setup.flash_vision_encoder - self.assertEqual(f("yes", {"vram_gb": 12.0}), "cpu") - self.assertEqual(f("yes", {"vram_gb": 15.9}), "cpu") - self.assertEqual(f("yes", {"vram_gb": 24.0}), "gpu") - self.assertEqual(f("yes", {"vram_gb": 32.0}), "gpu") - self.assertEqual(f("yes", {}), "gpu") # unknown VRAM: the old default - self.assertEqual(f("cpu", {"vram_gb": 32.0}), "cpu") - self.assertEqual(f("none", {"vram_gb": 16.0}), "none") - - def test_gpu_asked_is_kept_with_a_note(self): - import contextlib, io - out = io.StringIO() - with contextlib.redirect_stdout(out): - self.assertEqual(setup.flash_vision_encoder("gpu", {"vram_gb": 16.0}), "gpu") - self.assertEqual(setup.flash_vision_encoder("gpu", {"vram_gb": 32.0}), "gpu") - self.assertEqual(out.getvalue().count("kept as you chose"), 1) - self.assertIn("#2406", out.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_modelscope.py b/tools/test_setup_modelscope.py deleted file mode 100644 index cf1cdf2..0000000 --- a/tools/test_setup_modelscope.py +++ /dev/null @@ -1,139 +0,0 @@ -"""ModelScope as a download source (--source / STRATA_SOURCE): which source is used, the URL mapping, and that a file -from ModelScope is checked against the SHA-256 ModelScope publishes (a wrong one is deleted). No network: a local -HTTP server plays ModelScope. - - python -m unittest tools.test_setup_modelscope -""" -from __future__ import annotations - -import hashlib -import http.server -import json -import os -import sys -import tempfile -import threading -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - -REPO = "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" -PATH = "Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" -HF_URL = setup.hf(REPO) + PATH - - -class Quiet(http.server.SimpleHTTPRequestHandler): - def log_message(self, *a): - pass - - -class Base(unittest.TestCase): - def setUp(self): - for name in ("say", "ok", "warn"): - p = mock.patch.object(setup, name, lambda *a, **k: None) - p.start() - self.addCleanup(p.stop) - env = mock.patch.dict(os.environ, {}, clear=False) - env.start() - self.addCleanup(env.stop) - for k in ("STRATA_SOURCE", "HF_ENDPOINT", "MODELSCOPE_ENDPOINT"): - os.environ.pop(k, None) - setup._sources.clear() - setup._ms_files.clear() - self.addCleanup(setup._sources.clear) - - -class Source(Base): - def test_explicit(self): - for value, want in (("modelscope", "modelscope"), ("ms", "modelscope"), ("huggingface", "huggingface"), - ("hf", "huggingface")): - setup._sources.clear() - os.environ["STRATA_SOURCE"] = value - self.assertEqual(setup.model_source(), want, value) - - def test_auto_is_huggingface_and_never_asks_the_network(self): - """#908: setup does not switch hosts by itself, whatever answers.""" - with mock.patch.object(setup, "reachable", side_effect=AssertionError("no probe")): - self.assertEqual(setup.model_source(), "huggingface") - - def test_a_failed_download_recommends_modelscope(self): - self.assertIn("--source modelscope", setup.source_hint(HF_URL)) - self.assertEqual(setup.source_hint(setup.LLAMA_CPP_ZIP), "") - - def test_hf_endpoint_is_a_choice(self): - os.environ["HF_ENDPOINT"] = "https://hf-mirror.com" - with mock.patch.object(setup, "reachable", return_value=True) as r: - self.assertEqual(setup.model_source(), "huggingface") - r.assert_not_called() - - def test_mapping(self): - self.assertEqual(setup.ms_file(HF_URL), (REPO, PATH)) - self.assertEqual(setup.ms_url(REPO, PATH), - "https://www.modelscope.cn/models/" + REPO + "/resolve/master/" + PATH) - self.assertIsNone(setup.ms_file("https://huggingface.co/someone/other/resolve/main/x.gguf")) - self.assertIsNone(setup.ms_file(setup.LLAMA_CPP_ZIP)) - - -class Download(Base): - """download() through a local server laid out as ModelScope: /models//resolve/master/ and - /api/v1/models//repo/files (the query string is ignored by the test server).""" - - def setUp(self): - super().setUp() - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.www = Path(self.tmp.name) / "www" - self.data = os.urandom(300_000) - f = self.www / "models" / REPO / "resolve" / "master" / PATH - f.parent.mkdir(parents=True) - f.write_bytes(self.data) - self.server = http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), lambda *a, **k: Quiet(*a, directory=str(self.www), **k)) - threading.Thread(target=self.server.serve_forever, daemon=True).start() - self.addCleanup(self.server.server_close) - self.addCleanup(self.server.shutdown) - os.environ["MODELSCOPE_ENDPOINT"] = "http://127.0.0.1:%d" % self.server.server_address[1] - os.environ["STRATA_SOURCE"] = "modelscope" - self.dst = Path(self.tmp.name) / "out" / Path(PATH).name - - def api(self, sha): - p = self.www / "api" / "v1" / "models" / REPO / "repo" / "files" - p.parent.mkdir(parents=True, exist_ok=True) - p.write_text(json.dumps({"Data": {"Files": [{"Path": PATH, "Size": len(self.data), "Sha256": sha}]}})) - - def test_right_hash_is_kept(self): - sha = hashlib.sha256(self.data).hexdigest() - self.api(sha) - setup.download(HF_URL, self.dst) - self.assertEqual(self.dst.read_bytes(), self.data) - self.assertIn("sha256 " + sha, self.dst.with_name(self.dst.name + ".done").read_text()) - - def test_wrong_hash_is_deleted(self): - self.api("0" * 64) - with mock.patch.object(setup, "say"), self.assertRaises(SystemExit): - setup.download(HF_URL, self.dst) - self.assertFalse(self.dst.exists()) - self.assertFalse(self.dst.with_name(self.dst.name + ".done").exists()) - - def test_no_hash_published(self): - setup.download(HF_URL, self.dst) # no API file: the download is kept, as from Hugging Face - self.assertEqual(self.dst.read_bytes(), self.data) - self.assertTrue(self.dst.with_name(self.dst.name + ".done").exists()) - - def test_falls_back_when_modelscope_is_silent(self): - calls = [] - with mock.patch.object(setup, "reachable", return_value=False), \ - mock.patch.object(setup.urllib.request, "urlopen", - side_effect=lambda req, timeout=0: calls.append(req.full_url) or (_ for _ in ()).throw( - OSError("offline"))), \ - mock.patch.object(setup.time, "sleep"), self.assertRaises(SystemExit): - setup.download(HF_URL, self.dst) - self.assertTrue(calls and all(u == HF_URL for u in calls), calls[:2]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_nvfp4.py b/tools/test_setup_nvfp4.py deleted file mode 100644 index d4304fe..0000000 --- a/tools/test_setup_nvfp4.py +++ /dev/null @@ -1,180 +0,0 @@ -"""Tests for setup.py's NVFP4 family (ready-made packs, NVFP4_REPOS): every file fetched from its pinned revision and -checked against its size and SHA-256, a file both packs share linked instead of downloaded twice, a wrong file -refused, and the config's name read back as the same size. A local file:// mirror - nothing is downloaded. - - python -m unittest tools.test_setup_nvfp4 -""" -from __future__ import annotations - -import contextlib -import hashlib -import io -import os -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - -A, B = "owner/pack-a", "owner/pack-b" -REV_A, REV_B = "a" * 40, "b" * 40 - - -def quiet(fn, *args, **kw): - with contextlib.redirect_stdout(io.StringIO()): - return fn(*args, **kw) - - -class ReadyPacks(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = Path(self.tmp.name) - self.mirror = self.root / "mirror" - self.models = self.root / "models" - bodies = { - (A, REV_A, "pack/index.txt"): b"index a", (A, REV_A, "pack/experts.bin"): b"experts a" * 50, - (A, REV_A, "dense-a.gguf"): b"dense a", (A, REV_A, "ple-fp8.gguf"): b"the shared table" * 100, - (B, REV_B, "pack/index.txt"): b"index b", (B, REV_B, "pack/experts.bin"): b"experts b" * 50, - (B, REV_B, "dense-b.gguf"): b"dense b", (B, REV_B, "ple-fp8.gguf"): b"the shared table" * 100, - } - roles = {"pack/index.txt": "pack", "pack/experts.bin": "pack", "dense-a.gguf": "dense", "dense-b.gguf": "dense", - "ple-fp8.gguf": "ple"} - repos = {A: {"revision": REV_A, "files": {}}, B: {"revision": REV_B, "files": {}}} - for (repo, rev, path), body in bodies.items(): - f = self.mirror / repo / "resolve" / rev / path - f.parent.mkdir(parents=True, exist_ok=True) - f.write_bytes(body) - repos[repo]["files"][path] = (roles[path], len(body), hashlib.sha256(body).hexdigest()) - models = {"NVFP4": {**setup.MODELS["NVFP4"], "repo": A}, "NVFP4-NVIDIA": {**setup.MODELS["NVFP4-NVIDIA"], "repo": B}} - self.patches = [mock.patch.object(setup, "NVFP4_REPOS", repos), - mock.patch.dict(setup.MODELS, models), - mock.patch.dict(os.environ, {"HF_ENDPOINT": "file://" + self.mirror.as_posix()})] - for p in self.patches: - p.start() - - def tearDown(self): - for p in reversed(self.patches): - p.stop() - self.tmp.cleanup() - - def test_fetch_checks_and_links_the_shared_file(self): - quiet(setup.ready_fetch, "NVFP4", self.models) - for f in setup.ready_files("NVFP4"): - self.assertTrue(setup.ready_verified(setup.ready_where(self.models, f), f[5]), f[3]) - quiet(setup.ready_fetch, "NVFP4-NVIDIA", self.models) - a = self.models / "owner--pack-a" / "ple-fp8.gguf" - b = self.models / "owner--pack-b" / "ple-fp8.gguf" - self.assertTrue(setup.ready_verified(b, setup.NVFP4_REPOS[B]["files"]["ple-fp8.gguf"][2])) - self.assertTrue(os.path.samefile(a, b), "the shared table is linked, not a second copy") - p = setup.ready_paths("NVFP4-NVIDIA", self.models) - self.assertEqual(p["pack"], self.models / "owner--pack-b" / "pack") - self.assertEqual(p["dense"].name, "dense-b.gguf") - self.assertEqual(p["ple"], b) - - def test_a_second_run_downloads_nothing(self): - quiet(setup.ready_fetch, "NVFP4", self.models) - with mock.patch.object(setup, "download", side_effect=AssertionError("downloaded again")): - quiet(setup.ready_fetch, "NVFP4", self.models) - - def test_a_wrong_file_is_refused_and_deleted(self): - bad = self.mirror / A / "resolve" / REV_A / "dense-a.gguf" - bad.write_bytes(b"dense X") # same size, other bytes - with self.assertRaises(SystemExit): - quiet(setup.ready_fetch, "NVFP4", self.models) - self.assertFalse((self.models / "owner--pack-a" / "dense-a.gguf").exists()) - - def test_config_name_reads_back_as_the_size(self): - for model in ("NVFP4", "NVFP4-NVIDIA"): - cfg = self.root / f"strata-{(setup.FAMILIES['nvfp4']['tag'] + model).lower()}.json" - cfg.write_text('{"args": ["--max-context", "32768"]}', encoding="utf-8") - ch = setup.choices_from_config(cfg) - self.assertEqual((ch["family"], ch["model"]), ("nvfp4", model)) - - -class Family(unittest.TestCase): - def test_sizes_and_family(self): - self.assertTrue(setup.FAMILIES["nvfp4"]["ready"]) - names = [m for m in setup.MODELS if "nvfp4" in setup.MODELS[m].get("families", ())] - self.assertEqual(names, ["NVFP4", "NVFP4-NVIDIA"]) # the GPTQ pack first: the default size - for m in names: - d = setup.MODELS[m] - self.assertTrue(d["nvidia_only"]) - self.assertTrue(d["vision"]) - self.assertIn("License", d["license"]) - self.assertEqual(d["engine"], setup.NVFP4_ENGINE) - - def test_gguf_names_skip_the_ready_family(self): - self.assertIsNone(setup.gguf_choice("pack-a.gguf")) - self.assertEqual(setup.gguf_choice("Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf"), ("qwen", "IQ3_XXS")) - - -class MockedInstall(unittest.TestCase): - """setup.main() --family nvfp4 --yes on mocked PCs (test_setup_golden's harness): the run config's model flags.""" - - def run_install(self, prof, model=None, extra_argv=()): - import test_setup_golden as G - ram, found = G.PROFILES[prof] - return G.install(ram, found, ["--family", "nvfp4", "--no-start", *(["--model", model] if model else []), - *extra_argv]) - - def flag(self, args, name): - return args[args.index(name) + 1] if name in args else None - - def test_recommended_size_on_128gb(self): - code, out, cfg, _ = self.run_install("128GB-1x24GB") - self.assertEqual(code, 0, out[-2000:]) - a = cfg["args"] - self.assertTrue(self.flag(a, "--pack").endswith("Maximilian228--Qwen3.8-Flash-Next-NVFP4-GPTQ-Strata/pack")) - dense = self.flag(a, "--native") - self.assertTrue(dense.endswith("/qwen-nvfp4-gptq-dense.gguf")) - self.assertEqual(self.flag(a, "--native-dense-gguf"), dense) - self.assertTrue(self.flag(a, "--ple-gguf").endswith("/ple-fp8.gguf")) - self.assertTrue(self.flag(a, "--embd-gguf").endswith("/token-embd-bf16.gguf")) - self.assertNotIn("--mmap-experts", a) # 128 GB: every expert in RAM - self.assertNotIn("--resident-experts", a) - self.assertNotIn("vision", cfg) # --yes: images default off, as for every model - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-nvfp4-nvfp4") - self.assertIn("Qwen Community License", out) - - def test_images_use_the_dense_gguf_and_the_pinned_encoder(self): - code, out, cfg, _ = self.run_install("128GB-1x24GB", extra_argv=["--vision", "gpu"]) - self.assertEqual(code, 0, out[-2000:]) - v = cfg["vision"] - self.assertTrue(v["model"].endswith("/qwen-nvfp4-gptq-dense.gguf")) - self.assertTrue(v["mmproj"].endswith("/mmproj-Qwen3.8-Flash-Next-BF16.gguf")) - self.assertTrue(v["gpu"]) - self.assertIn("--vision", cfg["args"]) - - def test_nvidia_size_and_its_license(self): - code, out, cfg, _ = self.run_install("128GB-1x24GB", "NVFP4-NVIDIA") - self.assertEqual(code, 0, out[-2000:]) - self.assertIn("NVIDIA-NVFP4-Strata/pack", self.flag(cfg["args"], "--pack")) - self.assertIn("NVIDIA Open Model License", out) - - def test_96gb_keeps_every_expert_in_ram_64gb_takes_the_ram_budget(self): - code, out, cfg, _ = self.run_install("96GB-1x16GB") # 68 GB of experts + 10 GB beside them fit 95.8 - self.assertEqual(code, 0, out[-2000:]) - self.assertFalse({"--mmap-experts", "--resident-experts"} & set(cfg["args"])) - code, out, cfg, _ = self.run_install("64GB-1x32GB") # 64 GB: the RAM-budget mode (RAM less 24 GB) - self.assertEqual(code, 0, out[-2000:]) - a = cfg["args"] - self.assertFalse({"--mmap-experts", "--resident-experts"} & set(a)) - self.assertEqual(a[a.index("--resident-budget-gib") + 1], "40") - - def test_amd_is_refused_with_a_recommendation(self): - import test_setup_golden as G - ram, _ = G.PROFILES["128GB-1x24GB"] - amd = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201"}] - code, out, cfg, _ = G.install(ram, [], ["--family", "nvfp4", "--no-start", "--backend", "hip"], - extra=[mock.patch.object(setup, "amd_gpus", lambda *a, **k: amd)]) - self.assertNotEqual(code, 0) - self.assertIn("UD-IQ4_XS", out) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_oldcpu.py b/tools/test_setup_oldcpu.py deleted file mode 100644 index 7233f6d..0000000 --- a/tools/test_setup_oldcpu.py +++ /dev/null @@ -1,95 +0,0 @@ -"""Tests for setup.py's experimental older-CPU build (#394 #595 #623): which floor a CPU without AVX2 gets, the CMake -definition, a build folder configured afresh when the floor changes, and the MCP server's note instead of a refusal. -No compiler, no GPU. - - python -m unittest tools.test_setup_oldcpu -""" -from __future__ import annotations - -import io -import os -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - - -def cpuinfo(flags: str): - return mock.patch("builtins.open", lambda *a, **k: io.StringIO(f"model name\t: Old Xeon\nflags\t\t: {flags}\n")) - - -class FloorTest(unittest.TestCase): - def setUp(self): - self.env = mock.patch.dict(os.environ, {"STRATA_ISA_FLOOR": ""}) - self.env.start() - - def tearDown(self): - self.env.stop() - - def test_avx2_cpu_gets_the_normal_engine(self): - self.assertEqual(setup.cpu_floor(True), "") - - def test_linux_flags(self): - with mock.patch.object(setup, "WIN", False): - with cpuinfo("fpu sse4_1 sse4_2 popcnt avx xsave"): - self.assertEqual(setup.cpu_floor(False), "avx") - with cpuinfo("fpu sse4_1 sse4_2 popcnt"): - self.assertEqual(setup.cpu_floor(False), "none") - with cpuinfo("fpu sse3 ssse3"): - self.assertEqual(setup.cpu_floor(False), "unsupported") - - def test_windows_probe(self): - with mock.patch.object(setup, "WIN", True): - for probe, want in (("avx", "avx"), ("sse4.2", "none"), ("", "unsupported")): - with mock.patch.object(setup, "_cpuid_floor", lambda p=probe: p): - self.assertEqual(setup.cpu_floor(False), want) - - def test_env_asks_for_a_floor_build_on_any_cpu(self): - for v in ("avx", "none", "AVX"): - with mock.patch.dict(os.environ, {"STRATA_ISA_FLOOR": v}): - self.assertEqual(setup.cpu_floor(True), v.lower()) - with mock.patch.dict(os.environ, {"STRATA_ISA_FLOOR": "bogus"}): - self.assertEqual(setup.cpu_floor(True), "") - - @unittest.skipUnless(os.name == "nt", "the CPUID stub runs on Windows") - def test_this_pc_probe(self): - self.assertIn(setup._cpuid_floor(), ("avx", "sse4.2")) # any x86-64 PC that runs the tests - - -class DefsTest(unittest.TestCase): - def test_defs_and_fresh_configure(self): - with tempfile.TemporaryDirectory() as d: - b = Path(d) - cache = b / "CMakeCache.txt" - self.assertEqual(setup.isa_floor_defs("", b, {}), []) # the normal build: nothing added - cache.write_text("x") - self.assertEqual(setup.isa_floor_defs("avx", b, {"isa_floor": "avx"}), ["-DSTRATA_ISA_FLOOR=avx"]) - self.assertTrue(cache.exists()) # same floor: the folder is kept - self.assertEqual(setup.isa_floor_defs("none", b, {"isa_floor": "avx"}), ["-DSTRATA_ISA_FLOOR=none"]) - self.assertFalse(cache.exists()) # another floor: configured afresh - cache.write_text("x") - self.assertEqual(setup.isa_floor_defs("", b, {"isa_floor": "none"}), []) - self.assertFalse(cache.exists()) # back to the normal build - cache.write_text("x") - setup.isa_floor_defs("", b, {}) - self.assertTrue(cache.exists()) # the normal build's folder untouched - - -class McpTest(unittest.TestCase): - def test_no_avx2_is_a_note_not_a_refusal(self): - import strata_mcp as M - s = M.Strata(ROOT) - gpu = [{"index": 0, "name": "x", "vram_gb": 24.0, "usable": True, "vendor": "nvidia"}] - r = s.recommend({"ram_gb": 64, "gpus": gpu, "cpu": {"avx2": False}}) - self.assertIsNotNone(r["model"]) - self.assertTrue(any("no AVX2" in n and "EXPERIMENTAL" in n for n in r["notes"])) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_older_gpus.py b/tools/test_setup_older_gpus.py deleted file mode 100644 index d19fd4b..0000000 --- a/tools/test_setup_older_gpus.py +++ /dev/null @@ -1,287 +0,0 @@ -"""Older NVIDIA GPUs (experimental): Pascal / Volta run a second engine built with CUDA 12 (engine-cuda12/), chosen per -model config by its oldest card; --cuda 12|13 overrides it. A PC whose cards the ready-made CUDA 13 engine runs on -gets exactly what it got before. No GPU, no downloads. - - python -m unittest tools.test_setup_older_gpus -""" -from __future__ import annotations - -import json -import os -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import setup # noqa: E402 -from test_setup_choices import quiet # noqa: E402 -from test_setup_golden import PROFILES, install, argv_for # noqa: E402 - - -def card(i, name, vram, arch, driver="580.97"): - return {"index": i, "name": name, "vram_gb": vram, "arch": arch, "driver": driver} - - -V100 = card(0, "Tesla V100-PCIE-32GB", 32.0, "70", "575.57") -P40 = card(0, "Tesla P40", 24.0, "61", "535.104") - - -class Choice(unittest.TestCase): - def test_by_the_oldest_card(self): - self.assertEqual(setup.cuda_choice(["120"]), (13, None)) - self.assertEqual(setup.cuda_choice([75, 86, 89]), (13, None)) - for archs in ([70], [61], [60], [70, 86]): - tk, why = setup.cuda_choice(archs) - self.assertEqual(tk, 12, archs) - self.assertIn(f"sm_{min(archs)} is older than CUDA 13 supports", why) - - def test_the_override_is_honored_with_a_warning(self): - tk, why = setup.cuda_choice([70], "13") - self.assertEqual(tk, 13) # recommend, never force: kept, and said - self.assertIn("will not run on that card", why) - self.assertEqual(setup.cuda_choice([86], "12")[0], 12) - self.assertIn("#220", setup.cuda_choice([86, 120], "12")[1]) - self.assertEqual(setup.cuda_choice([70], "auto")[0], 12) - self.assertEqual(setup.cuda_choice([86], "auto"), (13, None)) - - def test_engine_folders_and_configs(self): - with mock.patch.object(setup, "ROOT", Path("/s")): - self.assertEqual(setup.engine_dir(), Path("/s/engine")) - self.assertEqual(setup.engine_dir(12), Path("/s/engine-cuda12")) - self.assertEqual(setup.config_toolkit({"exe": "/s/engine/strata.exe"}), 13) - self.assertEqual(setup.config_toolkit({"exe": "/s/engine-cuda12/strata.exe"}), 12) - self.assertEqual(setup.config_toolkit({"exe": "x", "cuda": 12}), 12) - self.assertEqual(setup.engine_defs([86], 12), ["-DSTRATA_EXPERIMENTAL_SM60=ON"]) - self.assertEqual(setup.engine_defs([86]), []) - - -class OptIn(unittest.TestCase): - """Pascal / Volta cards are used only when chosen; a PC with a newer card keeps recommending the newer one.""" - - def setUp(self): - self.env = mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": ""}) - self.env.start() - - def tearDown(self): - self.env.stop() - - def test_reasons(self): - rtx = card(0, "RTX 3090", 24.0, "86") - v100 = {**V100, "index": 1} - self.assertIsNone(setup.old_gpus_opt_in([rtx])) - self.assertIsNone(setup.old_gpus_opt_in([rtx, v100])) # the default: unchanged - self.assertIn("you chose GPU 1", setup.old_gpus_opt_in([rtx, v100], [1])) - self.assertIsNone(setup.old_gpus_opt_in([rtx, v100], [0])) - self.assertEqual(setup.old_gpus_opt_in([rtx, v100], cuda="12"), "--cuda 12") - self.assertIn("only kind", setup.old_gpus_opt_in([V100])) - self.assertIsNone(setup.old_gpus_opt_in([V100], other=True)) # an AMD card it can use instead - self.assertIsNone(setup.old_gpus_opt_in([card(0, "GTX 980", 4.0, "52")])) - with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}): - self.assertEqual(setup.old_gpus_opt_in([rtx, v100]), "STRATA_EXPERIMENTAL_SM60=1") - - def test_named(self): - self.assertEqual(setup.named_gpus(None, "0,2"), [0, 2]) - self.assertEqual(setup.named_gpus(1, None), [1]) - self.assertEqual(setup.named_gpus(None, "all"), []) - self.assertEqual(setup.named_gpus(None, "x"), []) - - def test_the_gate_follows_the_opt_in(self): - with mock.patch.object(setup, "OLD_GPUS", None): - self.assertIsNotNone(setup.gpu_problem(V100)) - with mock.patch.object(setup, "OLD_GPUS", "you chose GPU 0"): - self.assertIsNone(setup.gpu_problem(V100)) - self.assertIsNotNone(setup.gpu_problem(card(0, "GTX 980", 4.0, "52"))) - - -class Libraries(unittest.TestCase): - def test_cuda12_wheels_two_folders(self): - with tempfile.TemporaryDirectory() as d: - sp = Path(d) / "site-packages" - names = {"cublas/bin/cublas64_12.dll", "cuda_runtime/bin/cudart64_12.dll", "cu13/bin/x86_64/cublas64_13.dll", - "cublas/lib/libcublas.so.12", "cuda_runtime/lib/libcudart.so.12", "cu13/lib/libcublas.so.13"} - for n in names: - f = sp / "nvidia" / n - f.parent.mkdir(parents=True, exist_ok=True) - f.write_bytes(b"") - with mock.patch.object(sys, "path", [str(sp)]): - for win in (True, False): - with mock.patch.object(setup, "WIN", win): - got12 = sorted(Path(x).relative_to(sp / "nvidia").as_posix() for x in setup.cuda_lib_dirs(12)) - got13 = [Path(x).relative_to(sp / "nvidia").as_posix() for x in setup.cuda_lib_dirs()] - if win: - self.assertEqual(got12, ["cublas/bin", "cuda_runtime/bin"]) - self.assertEqual(got13, ["cu13/bin/x86_64"]) - else: - self.assertEqual(got12, ["cublas/lib", "cuda_runtime/lib"]) - self.assertEqual(got13, ["cu13/lib"]) - - def test_wheels_pinned_to_12(self): - self.assertTrue(all("-cu12==12." in w for w in setup.CUDA12_WHEELS)) - self.assertEqual(setup.CUDA12_ASSET, "strata-windows-x64-cuda12.zip" if setup.WIN else - "strata-linux-x64-cuda12.zip") - - -class BuildTools(unittest.TestCase): - """The compile path: a CUDA 12 engine looks for a 12.x toolkit (STRATA_NVCC picks one), sm_120 needs 12.8+.""" - - def tools(self, gpu, nvcc): - seen = [] - - def find(below=None): - seen.append(below) - return nvcc(below) - - with mock.patch.object(setup, "find_nvcc", find), mock.patch.object(setup, "find_vcvars", lambda cuda_v=None: "vcvars"), \ - mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n): - got, text = quiet(setup.install_build_tools, gpu, True) - return got, seen, text - - def test_cuda12_on_a_newer_card(self): - got, seen, _ = self.tools({"arch": "86", "archs": [86], "toolkit": 12}, - lambda below: ("nvcc12", (12, 9)) if below else ("nvcc13", (13, 0))) - self.assertEqual((got[0], seen), ("nvcc12", [(13, 0)])) - - def test_sm120_in_a_cuda12_engine_warns_and_needs_12_8(self): - got, _, text = self.tools({"arch": "70", "archs": [70, 120]}, - lambda below: ("nvcc12", (12, 9)) if below else ("nvcc13", (13, 0))) - self.assertEqual(got[0], "nvcc12") - self.assertIn("#220", text) - with self.assertRaises(SystemExit): - self.tools({"arch": "70", "archs": [70, 120]}, lambda below: ("nvcc12", (12, 6)) if below else (None, None)) - - -def fake_prebuilt(calls): - """get_prebuilt that installs an engine in the folder of the toolkit it is asked for (and says which).""" - def get(url_base, gpu, vision, updating=False, toolkit=13): - calls.append(toolkit) - eng = setup.engine_dir(toolkit) - eng.mkdir(exist_ok=True) - (eng / "BUILD.json").write_text(json.dumps({"version": "0.1.39", "source": "release", "archs": [86], "ptx": True, - "cuda": "12.9" if toolkit == 12 else "13.0", "vision": "gpu"})) - (eng / setup.EXE).write_bytes(b"") - return eng - return get - - -class Install(unittest.TestCase): - """setup.main() on mocked PCs (tools/test_setup_golden.py's harness).""" - - def run_setup(self, ram, found, argv, env=None): - calls, libs = [], [] - extra = [mock.patch.object(setup, "get_prebuilt", fake_prebuilt(calls)), - mock.patch.object(setup, "pip_cuda_libs", lambda tk=13: libs.append(tk)), - mock.patch.object(setup, "OLD_GPUS", None), - mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "", "STRATA_CUDA": "", **(env or {})})] - code, out, cfg, asked = install(ram, found, argv, extra=extra) - return code, out, cfg, calls, libs - - def test_a_v100_alone_gets_the_cuda12_engine(self): - code, out, cfg, calls, libs = self.run_setup(95.0, [V100], argv_for("qwen", "IQ3_XXS")) - self.assertEqual(code, 0, out[-3000:]) - self.assertEqual((calls, libs), ([12], [12])) - self.assertEqual(cfg["cuda"], 12) - self.assertEqual(cfg["exe"], "/engine-cuda12/") - self.assertIn("sm_70 is older than CUDA 13 supports", out) - self.assertIn("experimental", out) - - def test_a_p40_with_an_older_driver(self): - code, out, cfg, calls, _ = self.run_setup(95.0, [P40], argv_for("qwen", "IQ3_XXS")) - self.assertEqual(code, 0, out[-3000:]) # driver 535: enough for CUDA 12 - self.assertEqual(calls, [12]) - - def test_a_newer_card_beside_a_v100_is_unchanged(self): - """The RTX 3090 is recommended as before; the V100 is listed with how to choose it.""" - rtx = card(0, "NVIDIA GeForce RTX 3090", 24.0, "86") - found = [rtx, {**V100, "index": 1}] - code, out, cfg, calls, libs = self.run_setup(95.0, found, argv_for("qwen", "IQ3_XXS")) - code0, _, cfg0, _ = install(95.0, [rtx], argv_for("qwen", "IQ3_XXS")) - self.assertEqual(code, 0, out[-3000:]) - self.assertEqual((calls, libs), ([13], [13])) - self.assertNotIn("cuda", cfg) - self.assertEqual(cfg["exe"], "/engine/") - self.assertIn("choose it with --gpu 1", out) - skip = ("gpu", "gpus_asked", "lib_dirs") # one card vs two; the fake engine's library folders - self.assertEqual({k: v for k, v in cfg.items() if k not in skip}, {k: v for k, v in cfg0.items() if k not in skip}) - - def test_naming_the_v100_beside_a_newer_card(self): - found = [card(0, "NVIDIA GeForce RTX 3090", 24.0, "86"), {**V100, "index": 1}] - code, out, cfg, calls, _ = self.run_setup(95.0, found, argv_for("qwen", "IQ3_XXS") + ["--gpu", "1"]) - self.assertEqual(code, 0, out[-3000:]) - self.assertEqual(calls, [12]) - self.assertEqual((cfg["cuda"], cfg["gpu"]), (12, 1)) - self.assertIn("you chose GPU 1", out) - - def test_cuda12_asked_for_on_a_newer_card(self): - ram, found = PROFILES["128GB-1x24GB"] - for argv, env in ((["--cuda", "12"], None), ([], {"STRATA_CUDA": "12"})): - with self.subTest(argv=argv, env=env): - code, out, cfg, calls, _ = self.run_setup(ram, found, argv_for("qwen", "IQ3_XXS") + argv, env) - self.assertEqual(code, 0, out[-3000:]) - self.assertEqual((calls, cfg["cuda"]), ([12], 12)) - self.assertIn("--cuda 12 (as you chose", out) - - def test_an_old_driver_is_told_about_cuda12(self): - code, out, _, _, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")], - argv_for("qwen", "IQ3_XXS")) - self.assertEqual(code, 1) - self.assertIn("580 or newer is needed", out) - self.assertIn("--cuda 12", out) - code, out, cfg, calls, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")], - argv_for("qwen", "IQ3_XXS") + ["--cuda", "12"]) - self.assertEqual(code, 0, out[-3000:]) - self.assertEqual(calls, [12]) - - def test_cuda13_forced_on_a_v100_is_said(self): - code, out, cfg, calls, _ = self.run_setup(95.0, [V100], argv_for("qwen", "IQ3_XXS") + ["--cuda", "13"]) - self.assertIn("will not run on that card", out) - - -class Start(unittest.TestCase): - """At a start: a Pascal / Volta card added to a CUDA 13 model moves that model to the CUDA 12 engine; updates - look at both engine folders.""" - - def test_an_old_card_added_moves_the_model(self): - with tempfile.TemporaryDirectory() as d: - root = Path(d) - cfg_path = root / "strata-iq3_xxs.json" - cfg = {"exe": str(root / "engine" / setup.EXE), "args": [], "lib_dirs": [""]} - calls = [] - with mock.patch.object(setup, "ROOT", root), \ - mock.patch.object(setup, "get_prebuilt", fake_prebuilt(calls)), \ - mock.patch.object(setup, "pip_cuda_libs", lambda tk=13: None), \ - mock.patch.object(setup, "cuda_lib_dirs", lambda tk=13: [f""]), \ - mock.patch.object(setup, "gpu_info", lambda i=None: None): - got, text = quiet(setup.ensure_engine_for, [card(0, "RTX 3090", 24.0, "86"), {**V100, "index": 1}], - cfg_path, dict(cfg), True) - self.assertEqual(calls, [12]) - self.assertEqual(Path(got["exe"]).parent.name, "engine-cuda12") - self.assertEqual((got["cuda"], got["lib_dirs"]), (12, [""])) - self.assertIn("moves to the experimental CUDA 12 engine", text) - self.assertEqual(json.loads(cfg_path.read_text())["cuda"], 12) - - def test_update_looks_at_both_engines(self): - with tempfile.TemporaryDirectory() as d: - root = Path(d) - seen = [] - real = setup.update_installed_engine - - def spy(url_base, toolkit=None): - if toolkit is None: - return real(url_base, toolkit) - seen.append(toolkit) - with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "update_installed_engine", spy): - spy("u") - self.assertEqual(seen, [13]) - (root / "engine-cuda12").mkdir() - (root / "engine-cuda12" / "BUILD.json").write_text("{}") - seen.clear() - spy("u") - self.assertEqual(seen, [13, 12]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_page_file.py b/tools/test_setup_page_file.py deleted file mode 100644 index 287f51e..0000000 --- a/tools/test_setup_page_file.py +++ /dev/null @@ -1,158 +0,0 @@ -"""Step 1's page-file check: only the size the page files have for sure counts - their size now (the commit limit -minus RAM), or a file's configured initial size when larger - never what Windows may grow them to, and the warning -(below 4 GB, as before) advises a fixed size. When the Virtual memory setting (the registry's PagingFiles) has Windows -grow a file on demand ("System managed", or an initial size below the maximum), the warning says why that is not -enough (issue #60). The registry, the drives and GlobalMemoryStatusEx are mocked, so it runs on Linux too. - - python -m unittest tools.test_setup_page_file -""" -from __future__ import annotations - -import contextlib -import sys -import types -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 -from test_setup_golden import PROFILES, install # noqa: E402 - -PAGE_FILE_GB, PAGE_FILE_SETTING = setup.page_file_gb, setup.page_file_setting # the golden harness mocks the first -GROWS = "It is set to grow on demand" -FIXED = f"Custom size with initial and maximum size {setup.PAGE_FILE_FIXED_MB} MB" - - -def windows(paging, ram=31.9, now_mb=0, drives=None, existing=("\\??\\C:\\pagefile.sys",)): - """What Windows answers page_file_gb() and page_file_setting(), mocked: PagingFiles (None: it cannot be read), - ExistingPageFiles, each drive's (free MB, page file MB now), and GlobalMemoryStatusEx (commit limit = RAM + the - files' size now).""" - drives = {"C": (400000, now_mb)} if drives is None else drives - ms = types.SimpleNamespace(ullTotalPhys=int(ram * 2**30), ullTotalPageFile=int(ram * 2**30) + now_mb * 2**20) - return [mock.patch.object(setup, "_mm_multi_sz", lambda name: None if paging is None else - list(paging) if name == "PagingFiles" else list(existing)), - mock.patch.object(setup, "_drive_mb", lambda d: drives.get(d)), - mock.patch.object(setup, "_memory_status", lambda: ms)] - - -def on_windows(fn): - def call(*a): - with mock.patch.object(setup, "WIN", True): - return fn(*a) - return call - - -class Parse(unittest.TestCase): - def test_entries(self): - self.assertEqual(setup.parse_paging_file("c:\\pagefile.sys 64000 64000"), ("C", 64000, 64000)) - self.assertEqual(setup.parse_paging_file("D:\\pagefile.sys 1024 32768"), ("D", 1024, 32768)) - for managed in ("C:\\pagefile.sys 0 0", "C:\\pagefile.sys", "C:\\pagefile.sys x y"): - self.assertEqual(setup.parse_paging_file(managed), ("C", -1, -1), managed) - self.assertEqual(setup.parse_paging_file("?:\\pagefile.sys"), ("?", -1, -1)) # every drive automatic - for junk in ("", "x", "pagefile.sys 1 2"): - self.assertIsNone(setup.parse_paging_file(junk), junk) - - -class Reading(unittest.TestCase): - def read(self, paging, **k): - with contextlib.ExitStack() as st: - for p in windows(paging, **k): - st.enter_context(p) - files = on_windows(PAGE_FILE_SETTING)() - return on_windows(PAGE_FILE_GB)(), files - - def test_two_fixed_files(self): # this PR's author: 2 x 64000 MB on C: and D: - gb, files = self.read(["c:\\pagefile.sys 64000 64000", "d:\\pagefile.sys 64000 64000"], ram=127.2, - now_mb=128000, drives={"C": (334983, 64000), "D": (178396, 64000)}) - self.assertEqual(gb, 125.0) - self.assertFalse(setup.page_file_grows(files)) - - def test_a_growing_file_counts_its_size_now(self): - for paging in (["?:\\pagefile.sys"], ["C:\\pagefile.sys 0 0"], ["C:\\pagefile.sys"]): # system-managed - with self.subTest(paging): - gb, files = self.read(paging, now_mb=4083) - self.assertAlmostEqual(gb, 4083 / 1024) # not 3 x RAM: it may not grow in time (#60) - self.assertTrue(setup.page_file_grows(files)) - gb, files = self.read(["C:\\pagefile.sys 1024 32768"], now_mb=1024) - self.assertEqual(gb, 1.0) # its initial size, not its maximum - self.assertTrue(setup.page_file_grows(files)) - _, files = self.read(["?:\\pagefile.sys"], now_mb=4083, existing=("\\??\\D:\\pagefile.sys",), - drives={"D": (100000, 4083)}) - self.assertEqual(files, [("D", -1, -1, 4083, 100000)]) # "?:" is where Windows keeps it - - def test_an_initial_size_larger_than_the_file_now_counts(self): - self.assertEqual(self.read(["C:\\pagefile.sys 8192 8192"], now_mb=2048, drives={"C": (400000, 2048)})[0], 8.0) - gb, _ = self.read(["C:\\pagefile.sys 8192 8192"], now_mb=2048, drives={"C": (1000, 2048)}) # a full drive - self.assertAlmostEqual(gb, 3048 / 1024) - - def test_off_and_unread(self): - gb, files = self.read([]) - self.assertEqual((gb, files), (0.0, [])) - self.assertFalse(setup.page_file_grows(files)) - gb, files = self.read(None, now_mb=4083) # the setting cannot be read: the commit limit alone - self.assertAlmostEqual(gb, 4083 / 1024) - self.assertIsNone(files) - self.assertFalse(setup.page_file_grows(files)) - - def test_not_windows(self): - with mock.patch.object(setup, "WIN", False): - self.assertIsNone(setup.page_file_gb()) - self.assertIsNone(setup.page_file_setting()) - - -class Advice(unittest.TestCase): - def test_fixed_size_always_and_why_when_it_grows(self): - fixed = setup.page_file_advice(2.0, [("C", 2048, 2048, 2048, 400000)]) - self.assertIn("Windows' page file is 2.0 GB: the graphics card's memory needs room there too", fixed) - self.assertIn(FIXED, fixed) - self.assertNotIn(GROWS, fixed) - self.assertNotIn("Set it to \"System managed\"", fixed) - for files in ([("C", -1, -1, 4083, 400000)], [("C", 1024, 32768, 1024, 400000)], - [("C", 2048, 2048, 2048, 400000), ("D", -1, -1, 1024, 400000)]): - with self.subTest(files): - text = setup.page_file_advice(3.99, files) - self.assertIn(GROWS, text) - self.assertIn("a fixed 64 GB worked", text) - self.assertIn(FIXED, text) - self.assertNotIn(GROWS, setup.page_file_advice(0.0, [])) - self.assertNotIn(GROWS, setup.page_file_advice(1.0, None)) # the setting unread - - -class StepOne(unittest.TestCase): - """setup --check on the harness's 32 GB PC with the page-file reading of a Windows PC: warned below 4 GB.""" - WARN = "Windows' page file is" - - def check(self, paging, now_mb, ram=None): - ram0, found = PROFILES["32GB-2x24GB"] - ram = ram or ram0 - extra = [mock.patch.object(setup, "page_file_gb", on_windows(PAGE_FILE_GB)), - mock.patch.object(setup, "page_file_setting", on_windows(PAGE_FILE_SETTING)), - *windows(paging, ram=ram, now_mb=now_mb)] - code, out, _, _ = install(ram, found, ["--check"], extra=extra) - self.assertEqual(code, 0, out[-3000:]) - return next((x for x in out.splitlines() if self.WARN in x), None) - - def test_a_system_managed_file_is_warned_with_the_reason(self): - line = self.check(["?:\\pagefile.sys"], 4083) - self.assertIn("Windows' page file is 4.0 GB", line) - self.assertIn(GROWS, line) - self.assertIn(FIXED, line) - - def test_a_small_fixed_file_and_none(self): - for paging, now in ((["C:\\pagefile.sys 2048 2048"], 2048), ([], 0)): - with self.subTest(paging): - line = self.check(paging, now) - self.assertIn(f"Windows' page file is {now / 1024:.1f} GB", line) - self.assertIn(FIXED, line) - self.assertNotIn(GROWS, line) - - def test_the_threshold_is_unchanged(self): - self.assertIsNone(self.check(["?:\\pagefile.sys"], 8192)) # 8 GB now: not warned, as before - self.assertIsNone(self.check(["C:\\pagefile.sys 64000 64000"], 64000)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_parallel.py b/tools/test_setup_parallel.py deleted file mode 100644 index 4c04331..0000000 --- a/tools/test_setup_parallel.py +++ /dev/null @@ -1,63 +0,0 @@ -"""#465: setup's recommendation for "parallel" (several requests decoded together in the engine's batch slots). -No GPU or download needed: python tools/test_setup_parallel.py""" -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -import setup as S # noqa: E402 - - -class Parallel(unittest.TestCase): - def test_slot_size(self): - # measured: a slot's session at 32K, int8 KV: 0.56 GiB = 0.60 GB - self.assertAlmostEqual(S.parallel_slot_gb(32768, "int8", False), 0.59, delta=0.03) - # KV streaming keeps only the attention's 32K positions in VRAM, whatever the context - self.assertEqual(S.parallel_slot_gb(262144, "int8", True), S.parallel_slot_gb(32768, "int8", False)) - self.assertLess(S.parallel_slot_gb(32768, "q4_0", False), S.parallel_slot_gb(32768, "int8", False)) - - def test_recommendation_only_where_the_experts_mostly_fit(self): - q2, iq3s = S.MODELS["Q2_0"]["arena_gb"], S.MODELS["IQ3_S"]["arena_gb"] - # most experts on the CPU: slots cost speed per request (measured on the 12 GB 5070) - none recommended - self.assertEqual(S.parallel_recommend(12, q2, 32768, "int8", False), 0) - self.assertEqual(S.parallel_recommend(16, q2, 32768, "int8", False), 0) - self.assertEqual(S.parallel_recommend(24, iq3s, 32768, "int8", False), 0) - # the cache holds most of the experts beside the slots: recommended - self.assertEqual(S.parallel_recommend(24, q2, 32768, "int8", False), 3) - self.assertEqual(S.parallel_recommend(48, q2, 32768, "int8", False), 4) # capped at 4 - self.assertEqual(S.parallel_recommend([24, 24], iq3s, 32768, "int8", False), 4) # a layer split: every card - self.assertEqual(S.parallel_recommend([16, 16], q2, 32768, "int8", False), 4) - self.assertEqual(S.parallel_recommend(32, q2, 262144, "int8", False), 0) # a 262K KV per slot: no - self.assertEqual(S.parallel_recommend(32, q2, 262144, "int8", True), 4) # ... unless it streams - - def test_notes_recommend_never_force(self): - q2 = S.MODELS["Q2_0"]["arena_gb"] - # 12 GB: left at one, with the reason - note = S.parallel_note(None, 12, q2, 32768, "int8", False) - self.assertEqual(len(note), 1) - self.assertIn("one at a time", note[0]) - self.assertIn("costs about 10-25% speed per request on this card", note[0]) - self.assertIn("--parallel 3", S.parallel_note(None, 24, q2, 32768, "int8", False)[0]) - # asked on 12 GB: kept, with the cost said - lines = S.parallel_note(4, 12, q2, 32768, "int8", False) - self.assertIn("4 at once", lines[0]) - self.assertTrue(any("one at a time" in x and "kept as you chose" in x and "10-25%" in x for x in lines)) - # asked above the recommendation where it pays - lines = S.parallel_note(4, 24, q2, 32768, "int8", False) - self.assertTrue(any("recommended for this card: 3" in x for x in lines)) - self.assertTrue(any("at most 8" in x for x in S.parallel_note(12, 48, q2, 32768, "int8", False))) - self.assertEqual(len(S.parallel_note(3, 24, q2, 32768, "int8", False)), 1) # as recommended: no warning - - def test_poly_notes(self): - d = S.family_models("qwen36")["UD-Q3_K_M"] - # 8 GB: most experts on the CPU, so requests at once gain less - self.assertIn("gain less", S.poly_parallel_note(None, d, 8.0)[0]) - self.assertTrue(any("gain less" in x for x in S.poly_parallel_note(3, d, 8.0))) - # 32 GB holds every expert: worth it, and asked for, nothing to warn of - self.assertIn("--parallel 2 to 4", S.poly_parallel_note(None, d, 31.8)[0]) - self.assertEqual(len(S.poly_parallel_note(3, d, 31.8)), 1) - self.assertTrue(any("at most 8" in x for x in S.poly_parallel_note(12, d, 31.8))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_pcie.py b/tools/test_setup_pcie.py deleted file mode 100644 index a412fab..0000000 --- a/tools/test_setup_pcie.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Step 1's PCIe line: the generation card and board both run, the lanes, and a warning when the card runs on fewer -lanes than it has. No GPU needed: nvidia-smi's answer is given. - - python -m unittest tools.test_setup_pcie -""" -from __future__ import annotations - -import sys -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -class Link(unittest.TestCase): - def test_parse(self): - with mock.patch.object(setup, "out", return_value="3, 4, 3, 8, 8\n"): - self.assertEqual(setup.pcie_link(0), {"gen": 3, "gpu_gen": 4, "host_gen": 3, "width": 8, "max_width": 8}) - for bad in ("", "[N/A], 4, 3, 8, 8\n", "garbage"): - with mock.patch.object(setup, "out", return_value=bad): - self.assertIsNone(setup.pcie_link(0), bad) - - def test_board_limit_and_slow_link(self): # llmserver: RTX 4060 Ti (4.0 x8) on an X99 board (3.0) - line, warn = setup.pcie_lines({"gen": 3, "gpu_gen": 4, "host_gen": 3, "width": 8, "max_width": 8}) - self.assertIn("PCIe: 3.0 x8 (the card supports 4.0, the board 3.0)", line) - self.assertIn("~8 GB/s", line) - self.assertIsNone(warn) - - def test_fast_link_says_nothing_more(self): - line, warn = setup.pcie_lines({"gen": 4, "gpu_gen": 4, "host_gen": 5, "width": 16, "max_width": 16}) - self.assertEqual(line, "PCIe: 4.0 x16") - self.assertIsNone(warn) - - def test_fewer_lanes_warns(self): - _, warn = setup.pcie_lines({"gen": 3, "gpu_gen": 3, "host_gen": 3, "width": 4, "max_width": 16}) - self.assertIn("reads 4 of its 16 lanes right now", warn) - self.assertIn("narrow it when idle", warn) # the width is read at idle: a hint, not a verdict - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py deleted file mode 100644 index 0c1d2a1..0000000 --- a/tools/test_setup_pins.py +++ /dev/null @@ -1,360 +0,0 @@ -"""Tests for setup.py's reproducible installs (#214): the engine of the checkout's own release first (the latest as -the fallback), Hugging Face files at pinned revisions (the current files when a revision is gone), the pinned -requirements file, and an existing install left as it is. Mocked network - nothing is downloaded. - - python -m unittest tools.test_setup_pins -""" -from __future__ import annotations - -import contextlib -import hashlib -import io -import json -import re -import sys -import tempfile -import unittest -import urllib.error -import zipfile -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - -SHA = re.compile(r"/resolve/[0-9a-f]{40}/") - - -class Response(io.BytesIO): - def __init__(self, body=b"", status=200): - super().__init__(body) - self.status = status - self.headers = {"Content-Length": str(len(body))} - - def __enter__(self): - return self - - def __exit__(self, *exc): - self.close() - - -def not_found(url): - return urllib.error.HTTPError(url, 404, "Not Found", {}, None) - - -def quiet(fn, *args, **kw): - out = io.StringIO() - with contextlib.redirect_stdout(out): - return fn(*args, **kw), out.getvalue() - - -class HuggingFacePins(unittest.TestCase): - def test_every_model_url_is_pinned(self): - for name, fam in setup.FAMILIES.items(): - if fam.get("ready"): # ready-made packs: pinned per file (test_ready_packs_pinned) - continue - for key in ("hf", "mmproj_hf"): - if key == "mmproj_hf" and "mmproj" not in fam: # GLM 5.3 Flash: no image encoder - continue - with self.subTest(family=name, key=key): - self.assertRegex(fam[key], SHA) - self.assertNotIn("/resolve/main/", fam[key]) - self.assertRegex(setup.HF, SHA) - - def test_ready_packs_pinned(self): - """NVFP4: every size names a repository of NVFP4_REPOS, pinned by a commit; every file has a size and a - SHA-256, and the pack folder, dense GGUF, n-gram table and embedding are each there.""" - sizes = [m for m, d in setup.MODELS.items() if d.get("repo")] - self.assertEqual(sorted(sizes), ["NVFP4", "NVFP4-NVIDIA"]) - for m in sizes: - t = setup.NVFP4_REPOS[setup.MODELS[m]["repo"]] - self.assertRegex(t["revision"], r"^[0-9a-f]{40}$") - for path, (role, size, sha) in t["files"].items(): - with self.subTest(model=m, path=path): - self.assertIn(role, ("pack", "dense", "ple", "embd")) - self.assertGreater(size, 0) - self.assertRegex(sha, r"^[0-9a-f]{64}$") - p = setup.ready_paths(m, setup.Path("M")) - self.assertEqual(sorted(p), ["dense", "embd", "pack", "ple"]) - self.assertEqual(p["pack"].name, "pack") - self.assertIn("experts.bin", t["files"] and [x.split("/")[-1] for x in t["files"]]) - - def test_unpinned(self): - url = setup.FAMILIES["swift"]["hf"] + "x.gguf" - self.assertEqual(setup.hf_unpinned(url), - "https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/x.gguf") - self.assertEqual(setup.hf_unpinned("https://example.com/a/b"), "https://example.com/a/b") - - def test_a_gone_revision_downloads_the_current_file(self): - seen = [] - - def urlopen(req, timeout=None): - seen.append((req.get_method(), req.full_url)) - if "/resolve/main/" not in req.full_url: - raise not_found(req.full_url) - return Response(b"model bytes", status=200) - - # the pinned Hugging Face path itself (setup's --source huggingface; auto may pick ModelScope) - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ - mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}): - dst = Path(d) / "m.gguf" - _, out = quiet(setup.download, setup.FAMILIES["qwen"]["mmproj_hf"] + "m.gguf", dst) - self.assertEqual(dst.read_bytes(), b"model bytes") - self.assertIn("not at the pinned revision any more", out) - self.assertEqual([m for m, _ in seen], ["HEAD", "HEAD", "GET"]) - self.assertTrue(all("/resolve/main/" in u for _, u in seen[1:])) - - def test_a_complete_part_is_finished_without_a_request(self): - """A .part with every byte (setup stopped between the last byte and the rename): renamed, not resumed with a - range past its end - the server answers that with 416, which download() retried 30 times, 10 s apart.""" - seen = [] - - def urlopen(req, timeout=None): - seen.append((req.get_method(), req.headers.get("Range"))) - if req.get_method() == "HEAD": - return Response(b"model bytes") - raise urllib.error.HTTPError(req.full_url, 416, "Range Not Satisfiable", {}, None) - - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ - mock.patch.object(setup.time, "sleep", lambda s: None): - dst = Path(d) / "m.gguf" - dst.with_name("m.gguf.part").write_bytes(b"model bytes") - quiet(setup.download, "https://example.com/m.gguf", dst) - self.assertEqual(dst.read_bytes(), b"model bytes") - self.assertTrue(setup.done(dst)) - self.assertEqual(seen, [("HEAD", None)]) - - def test_mtp_fetch_is_pinned_and_falls_back(self): - import mtp_fetch - self.assertRegex(mtp_fetch.REPO, SHA) - self.assertIn(mtp_fetch.REVISION, mtp_fetch.REPO) - pinned = mtp_fetch.REPO - - def urlopen(req, timeout=None): - raise not_found(req.full_url) - - try: - with mock.patch.object(mtp_fetch.urllib.request, "urlopen", urlopen), \ - contextlib.redirect_stderr(io.StringIO()) as err: - self.assertEqual(mtp_fetch.resolve_repo(), "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/") - self.assertIn("pinned revision", err.getvalue()) - finally: - mtp_fetch.REPO = pinned - - def test_hf_endpoint(self): - # #495: HF_ENDPOINT (a mirror) serves the same pinned revision; a trailing slash and blanks are dropped - repo = "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" - with mock.patch.dict(setup.os.environ, {}, clear=False): - setup.os.environ.pop("HF_ENDPOINT", None) - self.assertEqual(setup.hf(repo), f"https://huggingface.co/{repo}/resolve/{setup.HF_REVISIONS[repo]}/") - for value in ("https://hf-mirror.com", "https://hf-mirror.com/", " https://hf-mirror.com/ "): - setup.os.environ["HF_ENDPOINT"] = value - url = setup.hf(repo) - self.assertEqual(url, f"https://hf-mirror.com/{repo}/resolve/{setup.HF_REVISIONS[repo]}/") - self.assertRegex(url, SHA) - self.assertEqual(setup.hf_unpinned(url + "x.gguf"), f"https://hf-mirror.com/{repo}/resolve/main/x.gguf") - setup.os.environ["HF_ENDPOINT"] = "" - self.assertEqual(setup.hf_endpoint(), "https://huggingface.co") - - def test_mtp_fetch_honours_hf_endpoint(self): - import importlib - import mtp_fetch - try: - with mock.patch.dict(mtp_fetch.os.environ, {"HF_ENDPOINT": "https://hf-mirror.com/"}): - importlib.reload(mtp_fetch) - self.assertTrue(mtp_fetch.REPO.startswith("https://hf-mirror.com/Qwen/Qwen3.8-Flash-Next/resolve/")) - self.assertRegex(mtp_fetch.REPO, SHA) - self.assertTrue(mtp_fetch.pinned()) # the tensors' SHA-256 checks still apply - finally: - importlib.reload(mtp_fetch) - self.assertTrue(mtp_fetch.REPO.startswith("https://huggingface.co/")) - - def test_step5_names_the_folder(self): - # #495: where setup expects the model files, and how to give it files downloaded by hand - from test_setup_golden import PROFILES, install - ram, found = PROFILES["96GB-1x16GB"] - with mock.patch.dict(setup.os.environ, {"HF_ENDPOINT": "https://hf-mirror.com"}): - code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "IQ3_XXS", "--no-start"]) - self.assertEqual(code, 0) - text = out.replace("\\", "/") - self.assertRegex(text, r"The model files go in .*/models/IQ3_XXS") - self.assertIn("put them here with their original names (Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", - text) - self.assertIn("--gguf-dir", text) - self.assertIn("Downloading from https://hf-mirror.com (HF_ENDPOINT)", text) - - -class Engine(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = Path(self.tmp.name) - (self.root / "engine").mkdir() - self.patches = [mock.patch.object(setup, "ROOT", self.root), - mock.patch.object(setup, "source_version", lambda: "0.1.31")] - for p in self.patches: - p.start() - - def tearDown(self): - for p in reversed(self.patches): - p.stop() - self.tmp.cleanup() - - def fake_download(self, got, wrote=None): - def download(url, dst, what=None): - got.append(url) - if wrote is not None: - wrote.append(Path(dst)) - with zipfile.ZipFile(dst, "w") as z: - z.writestr("BUILD.json", json.dumps({"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]})) - z.writestr(setup.EXE, b"engine") - return download - - def fake_digest(self, wrote): - """The SHA-256 of whatever the fake download just wrote, computed for real. - - `get_prebuilt()` now checks the archive against GitHub's size and SHA-256 before it unpacks - anything, so a test that mocks the download has to supply a hash or it stops at the check. These - tests are about WHICH release and WHICH asset are chosen, not about the bytes; what happens when - the hash is wrong has its own file (tools/test_setup_engine_hash.py). - """ - def digest(asset, base): - data = Path(wrote[-1]).read_bytes() - return len(data), hashlib.sha256(data).hexdigest() - return digest - - def run_get(self, published): - heads, got, wrote = [], [], [] - - def urlopen(req, timeout=None): - heads.append(req.full_url) - if not any(req.full_url.startswith(p) for p in published): - raise not_found(req.full_url) - return Response() - - with mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ - mock.patch.object(setup, "download", self.fake_download(got, wrote)), \ - mock.patch.object(setup, "engine_digest", self.fake_digest(wrote)): - eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") - return eng, out, heads, got - - def test_bases(self): - self.assertEqual(setup.prebuilt_bases(setup.PREBUILT_URL), - ["https://github.com/Niko1221/Strata/releases/download/v0.1.31/", setup.PREBUILT_URL]) - self.assertEqual(setup.prebuilt_bases("https://mirror.example/x"), ["https://mirror.example/x/"]) - - def test_the_checkout_s_release_first(self): - tag = "https://github.com/Niko1221/Strata/releases/download/v0.1.31/" - eng, out, heads, got = self.run_get([tag, setup.PREBUILT_URL]) - self.assertEqual(eng, self.root / "engine") - self.assertEqual(got, [tag + setup.PREBUILT_ASSET]) - self.assertEqual(len(heads), 1) - - def test_latest_when_it_is_not_published(self): - eng, out, heads, got = self.run_get([setup.PREBUILT_URL]) - self.assertEqual(eng, self.root / "engine") - self.assertEqual(got, [setup.PREBUILT_URL + setup.PREBUILT_ASSET]) - self.assertIn("No ready-made engine for v0.1.31", out) - - def test_a_refused_archive_is_not_kept(self): - """PR #324: a refused archive (too old, or no code for the GPU) kept its zip and .done mark, and every later - run reused it ("already downloaded") instead of the published one.""" - for meta in ({"version": "0.1.0", "archs": [89]}, - {"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [120]}): - with self.subTest(meta=meta): - wrote = [] - - def download(url, dst, what=None): - wrote.append(Path(dst)) - with zipfile.ZipFile(dst, "w") as z: - z.writestr("BUILD.json", json.dumps(meta)) - z.writestr(setup.EXE, b"engine") - setup.mark(dst) - - with mock.patch.object(setup.urllib.request, "urlopen", lambda req, timeout=None: Response()), \ - mock.patch.object(setup, "download", download), \ - mock.patch.object(setup, "engine_digest", self.fake_digest(wrote)): - eng, _ = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") - self.assertIsNone(eng) - z = self.root / "engine" / setup.PREBUILT_ASSET - self.assertFalse(z.exists()) - self.assertFalse(z.with_name(z.name + ".done").exists()) - - def test_an_archive_that_does_not_unpack_is_not_kept(self): - """#397, for an archive that does not unpack (not a zip, or a damaged one): it kept its zip and .done mark, - so every later run failed on it, even after the right one was published.""" - with tempfile.TemporaryDirectory() as folder: # a --prebuilt folder, through the real download() - asset = Path(folder) / setup.PREBUILT_ASSET - asset.write_bytes(b"not a zip") - with self.assertRaises(zipfile.BadZipFile): - quiet(setup.get_prebuilt, folder, {"arch": 89}, "gpu") - with zipfile.ZipFile(asset, "w") as z: - z.writestr("BUILD.json", json.dumps({"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]})) - z.writestr(setup.EXE, b"engine") - eng, _ = quiet(setup.get_prebuilt, folder, {"arch": 89}, "gpu") - self.assertEqual(eng, self.root / "engine") - self.assertEqual((self.root / "engine" / setup.EXE).read_bytes(), b"engine") - - def test_an_installed_engine_is_kept(self): - (self.root / "engine" / "BUILD.json").write_text(json.dumps( - {"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]})) - (self.root / "engine" / setup.EXE).write_bytes(b"old") - - def urlopen(req, timeout=None): - raise AssertionError("asked the network for an installed engine") - - with mock.patch.object(setup.urllib.request, "urlopen", urlopen): - eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") - self.assertEqual(eng, self.root / "engine") - self.assertEqual((self.root / "engine" / setup.EXE).read_bytes(), b"old") - - -class Requirements(unittest.TestCase): - def test_every_package_is_pinned(self): - lines = setup.requirement_lines() - names = {setup.req_name(x) for x in lines} - for p in setup.PY_PACKAGES: - self.assertIn(p, names) - for x in lines: - self.assertIn("==", x, x) - self.assertEqual(setup.req_name('numpy==2.5.3; python_version >= "3.12"'), "numpy") - self.assertEqual(setup.req_name("charset_normalizer==3"), "charset-normalizer") - - def pip(self, stamp, packages, installed=()): - ran = [] - with tempfile.TemporaryDirectory() as d: - if stamp is not None: - (Path(d) / ".strata-pip.json").write_text(json.dumps(stamp)) - with mock.patch.object(setup.sys, "prefix", d), \ - mock.patch.object(setup, "run", lambda cmd, **kw: ran.append(cmd)), \ - mock.patch.object(setup, "_installed", lambda name: name in installed): - quiet(setup.pip_install, packages, "the packages") - after = json.loads((Path(d) / ".strata-pip.json").read_text()) if ran else stamp - return [c for cmd in ran for c in cmd if "==" in c or c in setup.PY_PACKAGES], after - - def test_fresh_install_gets_every_pin(self): - lines = setup.requirement_lines() - ran, stamp = self.pip(None, lines) - self.assertEqual(ran, lines) - self.assertEqual(sorted(stamp), sorted(lines)) - self.assertEqual(self.pip(stamp, lines)[0], []) # the second run: nothing - - def test_an_install_from_before_the_pins_is_left_alone(self): - lines = setup.requirement_lines() - legacy = sorted(setup.PY_PACKAGES) + ["nvidia-cublas==13.0.2.14"] - deps = {"markupsafe", "certifi", "charset-normalizer", "idna", "urllib3", "colorama"} - self.assertEqual(self.pip(legacy, lines, installed=deps)[0], []) - missing = [p for p in legacy if p != "psutil"] # an older list without psutil - ran, _ = self.pip(missing, lines, installed=deps) - self.assertEqual(ran, ["psutil==7.2.2"]) - - def test_a_changed_pin_is_installed(self): - lines = setup.requirement_lines() - old = [x.replace("tqdm==4.70.1", "tqdm==4.60.0") for x in lines] - ran, _ = self.pip(old, lines) - self.assertEqual(ran, ["tqdm==4.70.1"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_prompts.py b/tools/test_setup_prompts.py deleted file mode 100644 index 98cfd4b..0000000 --- a/tools/test_setup_prompts.py +++ /dev/null @@ -1,149 +0,0 @@ -"""Setup prompts require input or --yes; EOF must not authorize system installs (#393). -No GPU, downloads or installers are used. - - python -m unittest tools.test_setup_prompts -""" -from __future__ import annotations - -import contextlib -import io -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -class Prompts(unittest.TestCase): - def test_eof_stops_with_guidance(self): - out = io.StringIO() - with mock.patch("sys.stdin", io.StringIO()), contextlib.redirect_stdout(out): - with self.assertRaises(SystemExit) as cm: - setup.ask("Install them now?", ["y", "n"], "y", False) - self.assertEqual(cm.exception.code, 1) - self.assertIn("Install them now?", out.getvalue()) - self.assertIn("--yes", out.getvalue()) - self.assertIn("Setup stopped", out.getvalue()) - - def test_yes_accepts_the_default_without_reading_input(self): - with mock.patch("builtins.input", side_effect=AssertionError("unexpected prompt")): - for default in ("y", "n"): - with self.subTest(default=default): - self.assertEqual(setup.ask("Install?", ["y", "n"], default, True), default) - - def test_enter_and_explicit_answers(self): - for answer, expected in (("\n", "y"), (" \n", "y"), ("y\n", "y"), (" N \n", "n")): - with self.subTest(answer=answer), mock.patch("sys.stdin", io.StringIO(answer)), \ - contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(setup.ask("Install?", ["y", "n"], "y", False), expected) - - def test_invalid_answer_reprompts_and_preserves_choice_case(self): - out = io.StringIO() - with mock.patch("sys.stdin", io.StringIO("invalid\nyArN\n")), contextlib.redirect_stdout(out): - self.assertEqual(setup.ask("Method?", ["Yarn", "Linear"], "Linear", False), "Yarn") - self.assertIn("please answer one of: Yarn, Linear", out.getvalue()) - - def test_eof_after_invalid_answer_stops(self): - with mock.patch("sys.stdin", io.StringIO("invalid\n")), contextlib.redirect_stdout(io.StringIO()): - with self.assertRaises(SystemExit) as cm: - setup.ask("Install?", ["y", "n"], "y", False) - self.assertEqual(cm.exception.code, 1) - - -class BuildTools(unittest.TestCase): - def test_eof_never_starts_an_installer(self): - for win in (True, False): - with self.subTest(win=win), mock.patch.object(setup, "WIN", win), \ - mock.patch.object(setup, "find_nvcc", return_value=(None, (0, 0))), \ - mock.patch.object(setup, "find_vcvars", return_value=None), \ - mock.patch.object(setup.shutil, "which", side_effect=lambda name: None if name == "g++" else name), \ - mock.patch.object(setup, "run", side_effect=AssertionError("installer started")) as run, \ - mock.patch.object(setup, "download", side_effect=AssertionError("download started")) as download, \ - mock.patch("sys.stdin", io.StringIO()), contextlib.redirect_stdout(io.StringIO()): - with self.assertRaises(SystemExit) as cm: - setup.install_build_tools({"arch": "120"}, False) - self.assertEqual(cm.exception.code, 1) - run.assert_not_called() - download.assert_not_called() - - def test_yes_still_installs_missing_windows_tools(self): - nvcc, vcvars = Path("nvcc"), Path("vcvars64.bat") - with mock.patch.object(setup, "WIN", True), \ - mock.patch.object(setup, "find_nvcc", side_effect=[(None, (0, 0)), (nvcc, (13, 0))]), \ - mock.patch.object(setup, "find_vcvars", side_effect=[None, vcvars, vcvars, vcvars]), \ - mock.patch.object(setup.shutil, "which", return_value="winget"), \ - mock.patch.object(setup, "run") as run, \ - mock.patch("builtins.input", side_effect=AssertionError("unexpected prompt")), \ - contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(setup.install_build_tools({"arch": "120"}, True), (nvcc, vcvars)) - commands = [call.args[0] for call in run.call_args_list] - self.assertEqual(len(commands), 2) - self.assertIn("Microsoft.VisualStudio.2022.BuildTools", commands[0]) - self.assertIn("Nvidia.CUDA", commands[1]) - - -class VisualStudio(unittest.TestCase): - """CUDA 13 takes the compilers of Visual Studio 2019 and 2022. A newer Visual Studio can have the 2022 one - in it, and is then called for that one.""" - - def vs(self, t, own, v143=None): - build = Path(t) / "VC" / "Auxiliary" / "Build" - build.mkdir(parents=True) - (build / "vcvars64.bat").write_text("") - (build / "Microsoft.VCToolsVersion.default.txt").write_text(own + "\n") - if v143: - (build / "Microsoft.VCToolsVersion.v143.default.txt").write_text(v143 + "\n") - return build / "vcvars64.bat" - - def test_the_toolset_asked_for(self): - with tempfile.TemporaryDirectory() as t: - for name, own, v143, want in (("2026", "14.51.36231", "14.44.35207", " -vcvars_ver=14.44.35207"), - ("2026-alone", "14.51.36231", None, ""), - ("2022", "14.44.35207", "14.44.35207", ""), - ("2019", "14.29.30133", None, "")): - with self.subTest(name): - self.assertEqual(setup.vcvars_toolset(self.vs(Path(t) / name, own, v143)), want) - self.assertEqual(setup.vcvars_toolset(Path("no") / "vcvars64.bat"), "") - - def found(self, t, installs): - """find_vcvars() for CUDA 13.0 with vswhere answering from `installs`: {version range or "": installation - path}. Without a CUDA version any Visual Studio will do (#881).""" - vswhere = Path(t) / "Microsoft Visual Studio" / "Installer" / "vswhere.exe" - vswhere.parent.mkdir(parents=True, exist_ok=True) - vswhere.write_text("") - - def out(cmd, **_): - return installs.get(cmd[cmd.index("-version") + 1] if "-version" in cmd else "", "") - - with mock.patch.dict(setup.os.environ, {"ProgramFiles(x86)": str(t)}), mock.patch.object(setup, "out", out): - return setup.find_vcvars((13, 0)) - - def test_2022_before_a_newer_one(self): - with tempfile.TemporaryDirectory() as t: - old, new = self.vs(Path(t) / "2022", "14.44.35207", "14.44.35207"), \ - self.vs(Path(t) / "2026", "14.51.36231", "14.44.35207") - both = {"[16.0,18.0)": str(Path(t) / "2022"), "": str(Path(t) / "2026")} - self.assertEqual(self.found(t, both), old) - self.assertEqual(self.found(t, {"": str(Path(t) / "2026")}), new) - - def test_a_newer_one_without_the_2022_compiler_is_none(self): - with tempfile.TemporaryDirectory() as t: - self.vs(Path(t) / "2026", "14.51.36231") - self.assertIsNone(self.found(t, {"": str(Path(t) / "2026")})) - self.assertIsNone(self.found(t, {})) - - def test_the_build_script_calls_it_with_the_toolset(self): - with tempfile.TemporaryDirectory() as t: - vcvars = self.vs(Path(t) / "2026", "14.51.36231", "14.44.35207") - with mock.patch.object(setup, "WIN", True), mock.patch.object(setup, "ROOT", Path(t)), \ - mock.patch.object(setup, "find_tool", lambda name: name), mock.patch.object(setup, "run"): - setup.cmake_build(Path(t), Path(t) / "b", "strata-poly", [], vcvars, "build.bat") - self.assertIn(f'call "{vcvars}" -vcvars_ver=14.44.35207 >nul', (Path(t) / "build.bat").read_text()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_qwen36.py b/tools/test_setup_qwen36.py deleted file mode 100644 index b02c2e1..0000000 --- a/tools/test_setup_qwen36.py +++ /dev/null @@ -1,307 +0,0 @@ -"""Tests for setup.py's Qwen3.6-35B-A3B install (a family with its own engine path: OWN_PATH_FAMILIES): the pinned and -hashed files, the menu entry, steps 2-7 of install_own_path (size, context, the engine's --families check, the -download, the tokenizer, the config) and reading such a config back. Mocked engine, downloads and processes - -nothing is built, fetched or started. - - python -m unittest tools.test_setup_qwen36 -""" -from __future__ import annotations - -import argparse -import contextlib -import io -import json -import re -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 - -SHA = re.compile(r"/resolve/[0-9a-f]{40}/") -REPO = "unsloth/Qwen3.6-35B-A3B-MTP-GGUF" - - -def args(**kw): - base = dict(family="qwen36-strata", model=None, check=False, yes=True, vision=None, models_dir=None, gguf_dir=None, - context=None, rope_scaling=None, rope_scale=None, kv=None, resident_budget_gib=None, low_ram="auto", - vram_reserve_mib=None, host=None, api_key=None, browser=None, no_start=True, data_dir=None, gpu=None) - base.update(kw) - return argparse.Namespace(**base) - - -def run(fn, *a, **kw): - out = io.StringIO() - with contextlib.redirect_stdout(out): - try: - return fn(*a, **kw), out.getvalue() - except SystemExit as e: - return e.code, out.getvalue() - - -class Qwen36Entries(unittest.TestCase): - def test_pinned_and_hashed(self): - fam = setup.OWN_PATH_FAMILIES["qwen36-strata"] - self.assertIs(setup.PREVIEW_FAMILIES, setup.OWN_PATH_FAMILIES) # the earlier name still works - self.assertEqual(setup.HF_REVISIONS[REPO], "5bc3e238d916f48a861bac2f8a1990a0e9b7e98d") - for key in ("hf", "mmproj_hf"): - self.assertRegex(fam[key], SHA) - self.assertIn(REPO, fam[key]) - self.assertEqual(fam["arch"], "qwen35moe") - self.assertEqual(list(fam["models"]), ["UD-Q4_K_XL", "UD-Q6_K_XL", "Q8_0"]) - for m in fam["models"]: - size, sha = fam["sha256"][fam["file"].format(q=m)] - self.assertGreater(size, 20e9) - self.assertRegex(sha, r"^[0-9a-f]{64}$") - self.assertEqual(fam["sha256"]["Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf"][0], 22853663008) - - def test_not_a_pack_family(self): - # FAMILIES are Flash-Next files with packs; Qwen3.6 is installed by install_own_path - self.assertNotIn("qwen36-strata", setup.FAMILIES) - for m, d in setup.MODELS.items(): - self.assertNotIn("qwen36-strata", d.get("families", ())) - - def test_size_recommendation(self): - fam = setup.OWN_PATH_FAMILIES["qwen36-strata"] - self.assertEqual(setup.own_path_size(fam, 24.0), "UD-Q4_K_XL") # none fits: the smallest - self.assertEqual(setup.own_path_size(fam, 32.0), "UD-Q4_K_XL") - self.assertEqual(setup.own_path_size(fam, 46.0), "UD-Q6_K_XL") - self.assertEqual(setup.own_path_size(fam, 64.0), "Q8_0") - - def test_context_recommendation(self): - fam = setup.OWN_PATH_FAMILIES["qwen36-strata"] - self.assertEqual(setup.own_path_context(fam, 12.0), 32768) - self.assertEqual(setup.own_path_context(fam, 16.0), 32768) - self.assertEqual(setup.own_path_context(fam, 24.0), 65536) - self.assertEqual(setup.own_path_context(fam, 32.0), 131072) - - -class InstallOwnPath(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.root = Path(self.tmp.name) - self.calls = [] - self.families = {"qwen4exp", "qwen35moe"} - eng = self.root / "engine" - self.cfg = {} - - def engine_step(a, gpu, hip, amd, cuda_tk, vision): - self.calls.append(("engine", vision)) - if vision != "none": # the image encoder beside the engine - eng.mkdir(parents=True, exist_ok=True) - (eng / setup.VEXE).write_text("x") - return self.root / "llama", eng, {"version": "0.1.44"}, ["/libs"], gpu, vision - - def write_cfg(path, cfg, source=None): - self.cfg = cfg - self.calls.append(("config", path.name)) - - patches = [mock.patch.object(setup, "download", lambda url, dst, what=None: self.calls.append(("get", url, dst))), - mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.calls.append(("sha", s.name))), - mock.patch.object(setup, "free_gb", lambda p: 500.0), - mock.patch.object(setup, "pip_install", lambda *a, **k: None), - mock.patch.object(setup, "engine_step", engine_step), - mock.patch.object(setup, "engine_families", lambda e: self.families), - mock.patch.object(setup, "run", lambda cmd, **k: self.calls.append(("run", cmd))), - mock.patch.object(setup, "data_folder", lambda d: (self.root / "data", [])), - mock.patch.object(setup, "write_setup_config", write_cfg), - mock.patch.object(setup, "write_run_script", lambda tag, p, port, o=True: self.root / f"run-{tag}.sh"), - mock.patch.object(setup, "recommend_pool_workers", lambda a: a), - mock.patch.object(setup, "ROOT", self.root)] - for p in patches: - p.start() - self.addCleanup(p.stop) - - def install(self, ram=64.0, vram=16.0, hip=False, **kw): - gpu = {"index": 0, "count": 1, "vram_gb": vram, "name": "Test GPU"} - return run(setup.install_own_path, args(models_dir=str(self.root / "models"), **kw), "qwen36-strata", gpu, hip, [], - 13, [], 8080, ram, None) - - def test_installs_the_pinned_file_and_writes_the_config(self): - rc, out = self.install(model="UD-Q4_K_XL", vision="no") - self.assertEqual(rc, 0, out) - get = [c for c in self.calls if c[0] == "get"] - self.assertEqual(len(get), 1) - gguf = self.root / "models" / "qwen36s-UD-Q4_K_XL" / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf" - self.assertEqual(get[0][1], setup.hf(REPO) + gguf.name) - self.assertEqual(get[0][2], gguf) - self.assertIn(("sha", gguf.name), self.calls) - self.assertIn(("engine", "none"), self.calls) # --vision no: no image encoder - self.assertNotIn("--vision", self.cfg["args"]) - self.assertNotIn("vision", self.cfg) - tok = [c for c in self.calls if c[0] == "run"] - self.assertTrue(tok and "strata_tokenizer.py" in str(tok[0][1])) - a = self.cfg["args"] - self.assertEqual(a[a.index("--native") + 1], str(gguf)) - self.assertEqual(a[a.index("--max-context") + 1], "32768") # 16 GB card - self.assertEqual(a[a.index("--mtp") + 1], "2") - self.assertNotIn("--pack", a) - self.assertNotIn("--expert-cache", a) - self.assertEqual(self.cfg["arch"], "qwen35moe") - self.assertEqual(self.cfg["model_name"], "qwen3.6-35b-a3b-ud-q4_k_xl") - self.assertEqual(Path(self.cfg["exe"]).parent, self.root / "engine") - self.assertIn(("config", "strata-qwen36s-ud-q4_k_xl.json"), self.calls) - - def test_default_size_follows_the_ram(self): - rc, out = self.install(ram=64.0) - self.assertEqual(rc, 0, out) - self.assertIn("Recommended for 64 GB of RAM: Q8_0", out) - self.assertTrue(self.cfg["args"][self.cfg["args"].index("--native") + 1].endswith("Qwen3.6-35B-A3B-Q8_0.gguf")) - rc, out = self.install(ram=46.0) - self.assertTrue(self.cfg["args"][self.cfg["args"].index("--native") + 1].endswith("UD-Q6_K_XL.gguf")) - - def test_a_bigger_size_than_the_ram_is_asked_not_refused(self): - with mock.patch.object(setup, "confirm_risk", lambda *a, **k: None): - rc, out = self.install(ram=32.0, model="Q8_0") - self.assertEqual(rc, 0, out) - self.assertIn("installing Q8_0 with 32 GB of RAM, as you chose", out) - - def test_an_engine_without_the_family_is_refused_before_the_download(self): - self.families = {"qwen4exp"} - rc, out = self.install(model="UD-Q4_K_XL") - self.assertEqual(rc, 1) - self.assertIn("does not run Qwen3.6-35B-A3B yet", out) - self.assertEqual([c for c in self.calls if c[0] == "get"], []) - - def test_a_flash_next_size_is_refused(self): - rc, out = self.install(model="IQ3_XXS") - self.assertEqual(rc, 1) - self.assertIn("has no IQ3_XXS", out) - self.assertEqual(self.calls, []) - - def test_too_little_disk(self): - with mock.patch.object(setup, "free_gb", lambda p: 10.0): - rc, out = self.install(model="Q8_0") - self.assertEqual(rc, 1) - self.assertIn("not enough free disk space", out) - - def test_bigger_card_bigger_context(self): - rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no") - self.assertEqual(rc, 0, out) - a = self.cfg["args"] - self.assertEqual(a[a.index("--max-context") + 1], "131072") - - def test_images_by_default_on_a_16gb_nvidia_card_use_the_gpu_encoder(self): - rc, out = self.install(model="UD-Q4_K_XL", vram=16.0) # --yes: the question's default answer - self.assertEqual(rc, 0, out) - self.assertIn(("engine", "gpu"), self.calls) - mm = self.root / "models" / "qwen36s-UD-Q4_K_XL" / "mmproj-F16.gguf" - self.assertIn(("get", setup.hf(REPO) + "mmproj-F16.gguf", mm), self.calls) - self.assertIn(("sha", "mmproj-F16.gguf"), self.calls) # pinned: size + SHA-256 (899283584 bytes) - self.assertEqual(setup.OWN_PATH_FAMILIES["qwen36-strata"]["sha256"]["mmproj-F16.gguf"][0], 899283584) - a = self.cfg["args"] - self.assertIn("--vision", a) - v = self.cfg["vision"] - self.assertTrue(v["gpu"]) - self.assertEqual(v["mmproj"], str(mm)) - self.assertTrue(v["model"].endswith("Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf")) # the text model, opened vocab-only - self.assertEqual(Path(v["exe"]).name, setup.VEXE) - self.assertEqual(v["max_tokens"], 1024) - self.assertIn("images: on", out) - - def test_a_12gb_card_is_recommended_the_cpu_encoder_never_forced(self): - rc, out = self.install(model="UD-Q4_K_XL", vram=12.0) # the default answer is no - self.assertEqual(rc, 0, out) - self.assertNotIn("vision", self.cfg) - rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="yes") # yes: the CPU encoder, said why - self.assertEqual(rc, 0, out) - self.assertFalse(self.cfg["vision"]["gpu"]) - self.assertEqual(self.cfg["vision"]["max_tokens"], 300) - self.assertIn("threads", self.cfg["vision"]) - rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="gpu") # gpu asked for: kept, with a note - self.assertEqual(rc, 0, out) - self.assertTrue(self.cfg["vision"]["gpu"]) - self.assertIn("kept as you chose", out) - - def test_amd_reads_pictures_on_the_cpu(self): - with mock.patch.object(setup, "WIN", False): - rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="yes") - self.assertEqual(rc, 0, out) - self.assertFalse(self.cfg["vision"]["gpu"]) - self.assertIn("--vision", self.cfg["args"]) - with mock.patch.object(setup, "WIN", True): - rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="cpu") - self.assertNotIn("vision", self.cfg) - self.assertIn("Linux-only", out) - - def test_parallel_is_opt_in_and_recommended_where_the_experts_fit(self): - fam = setup.OWN_PATH_FAMILIES["qwen36-strata"] - # nothing written without --parallel; the recommendation is said - rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no", context=32768) - self.assertEqual(rc, 0, out) - self.assertNotIn("parallel", self.cfg) - self.assertIn("--parallel 3", out) - # a 12 GB card runs the hybrid mode: parallel is offered there too, with its price said (never forced) - # (measured: 12 GB at 8K, 4 slots: a request alone -4%; 16 GB at 32K, 2 slots -9 to -11%, 4 slots no gain together) - self.assertEqual(setup.own_path_parallel_recommend(fam, "UD-Q4_K_XL", 12.0, 8192), 4) - self.assertEqual(setup.own_path_parallel_recommend(fam, "UD-Q4_K_XL", 12.0, 32768), 0) - self.assertEqual(setup.own_path_parallel_recommend(fam, "UD-Q4_K_XL", 16.0, 32768), 2) - self.assertEqual(setup.own_path_parallel_recommend(fam, "UD-Q4_K_XL", 12.0, 131072), 0) - self.assertEqual(setup.own_path_parallel_recommend(fam, "UD-Q4_K_XL", 8.0, 32768), 0) - # a card that holds every expert for ONE session only is not offered more: 4 slots on a 32 GB R9700 at 128K left - # 15 of 256 experts per layer in VRAM and decode ran 81 tok/s against ~180 - self.assertEqual(setup.own_path_parallel_recommend(fam, "UD-Q4_K_XL", 31.9, 131072), 0) - rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="no", context=8192) - self.assertNotIn("parallel", self.cfg) - self.assertIn("--parallel 4", out) - self.assertIn("does not hold every expert", out) - self.assertIn("a request alone runs about 4-11% slower", out) - self.assertIn("WITH the draft layer", out) - rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="no", context=8192, parallel=6) - self.assertEqual(self.cfg["parallel"], 6) - self.assertIn("recommended for this card: 4", out) - self.assertIn("kept as you chose", out) - rc, out = self.install(model="UD-Q4_K_XL", vram=8.0, vision="no", parallel=4) - self.assertEqual(self.cfg["parallel"], 4) - self.assertIn("recommended for this card: one at a time", out) - self.assertIn("kept as you chose", out) - rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="no", context=8192, parallel=1) - self.assertEqual(self.cfg["parallel"], 1) - rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no", parallel=12) - self.assertIn("at most 8", out) - self.assertEqual(self.cfg["parallel"], 12) # written as asked; the server and the engine cap it - self.assertGreater(setup.own_path_parallel_slot_gb(fam, 32768), 1.4) - - def test_parallel_is_asked_when_attended_and_enter_keeps_one_at_a_time(self): - asked = [] - - def ask(question, choices, default, yes): - if "requests at once" not in question: - return default # size, context, images: the recommended answers - asked.append((question, default)) - return answers.pop(0) - for answers, want in ((["1"], None), (["3"], 3)): - self.cfg = {} - with mock.patch.object(setup, "ask", ask): - rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="no", context=8192, yes=False) - self.assertEqual(rc, 0, out) - self.assertEqual(self.cfg.get("parallel"), want) - self.assertIn("--parallel 4", out) # the offer and its price are said before the question - self.assertEqual(out.count("Several requests at once (opt-in)"), 1) - self.assertTrue(all(d == "1" for _, d in asked)) # Enter = one at a time - # a card with no room for a second session is not asked - asked.clear() - with mock.patch.object(setup, "ask", ask): - rc, out = self.install(model="UD-Q4_K_XL", vram=8.0, vision="no", yes=False) - self.assertEqual(asked, []) - self.assertNotIn("parallel", self.cfg) - - def test_config_read_back(self): - self.install(model="UD-Q6_K_XL", context=65536) - p = self.root / "strata-qwen36s-ud-q6_k_xl.json" - p.write_text(json.dumps(self.cfg), encoding="utf-8") - ch = setup.choices_from_config(p) - self.assertEqual((ch["family"], ch["model"], ch["context"]), ("qwen36-strata", "UD-Q6_K_XL", 65536)) - self.assertEqual(ch["vision"], "gpu") # 16 GB NVIDIA, the default answer - self.assertTrue(setup.own_path_config(self.cfg)) - self.assertEqual(setup.calibration_targets([p], None, None), []) # the tuning is Flash-Next's - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_remote_opt.py b/tools/test_setup_remote_opt.py deleted file mode 100644 index 8d797a2..0000000 --- a/tools/test_setup_remote_opt.py +++ /dev/null @@ -1,98 +0,0 @@ -"""0.1.39b (#578): setup recommends --remote-expert-opt for a config on two or more GPUs, never for one, and keeps it -out when asked (setup's --no-remote-expert-opt, or "remote_expert_opt": false in the config). - - python -m unittest tools.test_setup_remote_opt -""" -from __future__ import annotations - -import sys -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 -from test_setup_golden import PROFILES, install # noqa: E402 - -FLAG = "--remote-expert-opt" -HELPER = ["--expert-cache-device1", "auto"] - - -class Rule(unittest.TestCase): - def setUp(self): - p = mock.patch.object(setup, "ok", lambda *a: None) - p.start() - self.addCleanup(p.stop) - - def test_two_gpus_get_it_once(self): - cfg = {"args": ["--spec", "4"] + HELPER, "gpu": [0, 1]} - setup.recommend_remote_expert_opt(cfg) - setup.recommend_remote_expert_opt(cfg) - self.assertEqual(cfg["args"], ["--spec", "4"] + HELPER + [FLAG]) - - def test_no_helper_cache_no_flag(self): - """#1447: on a plain layer split there is no helper cache for the flag to act on, so setup does not write it.""" - cfg = {"args": ["--spec", "4"], "gpu": [0, 1]} - setup.recommend_remote_expert_opt(cfg) - self.assertEqual(cfg["args"], ["--spec", "4"]) - kept = {"args": [FLAG], "gpu": [0, 1]} # a flag already there is the user's: left alone - setup.recommend_remote_expert_opt(kept) - self.assertEqual(kept["args"], [FLAG]) - eq = {"args": ["--expert-cache-device2=auto"], "gpu": [0, 1, 2]} - setup.recommend_remote_expert_opt(eq) - self.assertIn(FLAG, eq["args"]) - - def test_one_gpu_is_untouched(self): - for gpu in (None, 0, [0]): - cfg = {"args": ["--spec", "4"]} if gpu is None else {"args": ["--spec", "4"], "gpu": gpu} - setup.recommend_remote_expert_opt(cfg) - self.assertEqual(cfg["args"], ["--spec", "4"], gpu) - - def test_overrides(self): - cfg = {"args": ["--spec", "4", FLAG], "gpu": [0, 1]} - setup.recommend_remote_expert_opt(cfg, off=True) - self.assertEqual(cfg["args"], ["--spec", "4"]) - cfg = {"args": ["--spec", "4"] + HELPER, "gpu": [0, 1, 2], "remote_expert_opt": False} - setup.recommend_remote_expert_opt(cfg) - self.assertEqual(cfg["args"], ["--spec", "4"] + HELPER) - - def test_pipeline_windows_wins(self): - """#1352: the two exclude each other (the engine drops the pipeline beside the helper caches), so setup - does not add the flag to a config that asks for the pipeline, and says so when both are there.""" - cfg = {"args": ["--spec", "4", "--pipeline-windows", "2"] + HELPER, "gpu": [0, 1]} - setup.recommend_remote_expert_opt(cfg) - self.assertEqual(cfg["args"], ["--spec", "4", "--pipeline-windows", "2"] + HELPER) - both = {"args": [FLAG, "--pipeline-windows", "2"], "gpu": [0, 1]} - with mock.patch.object(setup, "warn") as w: - setup.recommend_remote_expert_opt(both) - self.assertEqual(both["args"], [FLAG, "--pipeline-windows", "2"]) # a recommendation, never forced - self.assertEqual(w.call_count, 1) - off = {"args": ["--pipeline-windows", "0"] + HELPER, "gpu": [0, 1]} # 0: no pipeline asked for - setup.recommend_remote_expert_opt(off) - self.assertIn(FLAG, off["args"]) - - def test_the_users_key_is_kept_on_a_rerun(self): - self.assertNotIn("remote_expert_opt", setup.SETUP_KEYS) # #629: carried over, so the opt-out survives - - -class Install(unittest.TestCase): - def test_install_on_two_gpus(self): - """#1447: a plain two-GPU install has no helper cache, so no --remote-expert-opt is written.""" - ram, found = PROFILES["47GB-2x16GB"] - args = ["--family", "qwen", "--no-start", "--model", "Q2_0"] - code, text, cfg, _ = install(ram, found, args) - self.assertEqual(code, 0, text) - self.assertIsInstance(cfg.get("gpu"), list) - self.assertNotIn(FLAG, cfg["args"]) - - def test_install_on_one_gpu(self): - ram, found = PROFILES["96GB-1x16GB"] - code, text, cfg, _ = install(ram, found, ["--family", "qwen", "--no-start", "--model", "Q2_0"]) - self.assertEqual(code, 0, text) - self.assertNotIn(FLAG, cfg["args"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_rerun_size.py b/tools/test_setup_rerun_size.py deleted file mode 100644 index 82f42ff..0000000 --- a/tools/test_setup_rerun_size.py +++ /dev/null @@ -1,104 +0,0 @@ -"""0.1.44.1: setup run again over an installed model keeps its size. - -0.1.44 made IQ3_S the recommended Qwen size on a PC with 64 GB or more (IQ3_S: about 15% slower decode than IQ3_XXS on an -RTX 5070, docs/MODELS.md, and about 7 GB more RAM). A first install takes the recommendation; SETUP.bat / --setup on a -folder that already has a model pre-selects the installed size (and `--yes` takes it), so Enter never moves a working -install to a slower size. The recommended size stays marked, every size stays a choice. - - python -m unittest tools.test_setup_rerun_size -""" -from __future__ import annotations - -import sys -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 -import test_setup_golden as g # noqa: E402 - -PC64 = (63.7, [g.card(0, "NVIDIA GeForce RTX 5070", 11.9, "120")]) - - -def earlier(model: str, family_tag: str = "") -> tuple: - tag = f"{family_tag}{model.lower()}" - return (f"strata-{tag}.json", {"exe": "x", "args": ["--pack", f"p/{tag}", "--max-context", "32768"], "cwd": ".", - "tokenizer": "t", "model_name": f"qwen3.8-flash-next-{tag}", "log": "l", "port": 8080}) - - -class RerunKeepsSize(unittest.TestCase): - def run_setup(self, argv, configs, answers=""): - ram, found = PC64 - code, out, cfg, asked = g.install(ram, found, argv, answers=answers, configs=configs) - self.assertEqual(code, 0, out[-2000:]) - return out, cfg, asked - - def test_first_install_takes_the_recommendation(self): - out, cfg, _ = self.run_setup(["--family", "qwen", "--no-start"], []) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-iq3_s") - self.assertNotIn("(installed)", out) - - def test_enter_over_an_installed_iq3_xxs_keeps_it(self): - out, cfg, asked = self.run_setup(["--family", "qwen", "--setup", "--no-start"], [earlier("IQ3_XXS")]) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-iq3_xxs", out[-1500:]) - line_s = next(x for x in out.splitlines() if " IQ3_S " in x or " IQ3_S\t" in x or "IQ3_S " in x) - self.assertIn("(recommended)", line_s) # still marked, still a choice - line_xxs = next(x for x in out.splitlines() if "IQ3_XXS" in x and "download" in x) - self.assertIn("(installed)", line_xxs) - self.assertTrue(any("Which size?" in a for a in asked)) - - def test_yes_over_an_installed_size_keeps_it_too(self): - _, cfg, asked = self.run_setup(["--family", "qwen", "--setup", "--no-start"], [earlier("Q2_0")], answers=None) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-q2_0") - self.assertEqual(asked, []) - - def test_a_named_size_still_wins(self): - _, cfg, _ = self.run_setup(["--family", "qwen", "--model", "IQ3_S", "--setup", "--no-start"], [earlier("IQ3_XXS")]) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-iq3_s") - - def test_another_family_is_not_touched(self): - # a Qwen IQ3_XXS install does not pre-select anything for the Unsloth family - _, cfg, _ = self.run_setup(["--family", "unsloth", "--setup", "--no-start"], [earlier("IQ3_XXS")]) - self.assertIn("unsloth", cfg["model_name"]) - - def test_the_helper_prefers_the_most_recent_config_of_the_family(self): - import json - import tempfile - with tempfile.TemporaryDirectory() as tmp: - t = Path(tmp) - paths = [] - for name, cfg in (earlier("IQ3_S"), earlier("Q2_0")): - p = t / name - p.write_text(json.dumps(cfg)) - paths.append(p) - names = [m for m in setup.MODELS if "qwen" in setup.MODELS[m].get("families", ("qwen", "swift"))] - self.assertEqual(setup.installed_size("qwen", names, paths), "IQ3_S") # first = most recently used - self.assertEqual(setup.installed_size("qwen", names, paths[1:]), "Q2_0") - self.assertIsNone(setup.installed_size("qwen", names, [])) - - -class RerunKeepsOwnEnv(unittest.TestCase): - """0.1.44 put STRATA_MMQ_KQ / STRATA_HC_Q8 / STRATA_ROUTE_TAIL_SKIP into SETUP_ENV (the entries setup writes, which a - setup run again does not carry over): a GSQ-RCO config of the user's own STRATA_ROUTE_TAIL_SKIP=0 was dropped with them. - Those three are setup's only in an Unsloth config.""" - - OLD = {"env": {"STRATA_ROUTE_TAIL_SKIP": "0", "STRATA_MMQ_KQ": "1", "STRATA_HC_Q8": "0", "STRATA_RESIDENT_PIN": "0", - "MY_VAR": "1"}} - - def test_a_gsq_rco_config_keeps_the_users_values(self): - new = {"model_name": "qwen3.8-flash-next-iq3_xxs"} - kept = setup.carry_over(dict(self.OLD), new) - self.assertEqual(new["env"], {"STRATA_ROUTE_TAIL_SKIP": "0", "STRATA_MMQ_KQ": "1", "STRATA_HC_Q8": "0", "MY_VAR": "1"}) - self.assertIn("env STRATA_ROUTE_TAIL_SKIP", kept) - self.assertNotIn("env STRATA_RESIDENT_PIN", kept) # the older entries stay setup's own - - def test_an_unsloth_config_gets_setups_values_not_the_old_ones(self): - new = {"model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "env": {"STRATA_HC_Q8": "1"}} - setup.carry_over(dict(self.OLD), new) - self.assertEqual(new["env"], {"STRATA_HC_Q8": "1", "MY_VAR": "1"}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_risk.py b/tools/test_setup_risk.py deleted file mode 100644 index 40c8342..0000000 --- a/tools/test_setup_risk.py +++ /dev/null @@ -1,514 +0,0 @@ -"""Tests for the owner's rule in setup.py - it recommends, it never forces: a choice bigger than the recommendation is -kept and its risk said (#406's 256K on 64 GB, #364/#384's two GPUs in the low-RAM mode, #403's RAM budget), and the -stops that stay are the ones a user can confirm (confirm_risk: --yes with an explicit flag, or y). The defaults are -tools/test_setup_golden.py's. Mocked - no GPU, no downloads, nothing written outside a temp folder. - - python -m unittest tools.test_setup_risk -""" -from __future__ import annotations - -import contextlib -import io -import itertools -import json -import os -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "tools")) -import setup # noqa: E402 -from test_setup_golden import PROFILES, card, install # noqa: E402 - - -def arg(cfg, flag): - a = cfg["args"] - return a[a.index(flag) + 1] if flag in a else None - - -def run(fn, *args, stdin=None): - """-> (exit code or None, printed text, questions asked); stdin answers every input() (None: never asked).""" - out, asked, code = io.StringIO(), [], None - - def fake_input(prompt=""): - asked.append(prompt) - if stdin is None: - raise AssertionError(f"asked {prompt!r} with --yes") - return stdin - - with contextlib.redirect_stdout(out), mock.patch("builtins.input", fake_input): - try: - fn(*args) - except SystemExit as e: - code = e.code - return code, out.getvalue(), asked - - -class ConfirmRisk(unittest.TestCase): - """S6: one helper for the stops a user may take on.""" - - def go(self, explicit, yes, stdin=None): - return run(setup.confirm_risk, "it may not fit", explicit, yes, "it does not fit", "a smaller size", - stdin=stdin) - - def test_yes_with_an_explicit_choice_is_consent(self): - code, out, asked = self.go(True, True) - self.assertIsNone(code) - self.assertIn("it may not fit", out) - self.assertEqual(asked, []) - - def test_yes_alone_keeps_the_stop(self): - code, out, asked = self.go(False, True) - self.assertEqual(code, 1) - self.assertIn("it does not fit", out) - self.assertIn("a smaller size", out) - - def test_interactive_default_is_no(self): - for explicit in (True, False): - code, out, asked = self.go(explicit, False, stdin="") - self.assertEqual(code, 1) - self.assertIn("[n]", asked[0]) - self.assertIsNone(self.go(explicit, False, stdin="y")[0]) - - def test_paging_with_an_explicit_model(self): - code, out, asked = run(setup.confirm_paging, "IQ3_XXS", 54, "auto", True, True) - self.assertIsNone(code, out) - self.assertIn("installing IQ3_XXS with 54 GB of RAM, as you chose (--model)", out) - - -class Context(unittest.TestCase): - """S1 (#406 #364): the RAM rule recommends, an explicit or picked context is kept with a note.""" - RAM64, GPU32 = PROFILES["64GB-1x32GB"] - - def test_the_ram_rule(self): - self.assertEqual(setup.ram_ctx("IQ3_S", 63.7), 131072) - self.assertEqual(setup.ram_ctx("IQ3_XXS", 63.7), 131072) - self.assertEqual(setup.ram_ctx("IQ3_XXS", 95.8), 524288) # 43 + 7.2 + 24 GB fits 96 - self.assertEqual(setup.ram_ctx("IQ3_S", 76.5), 131072) - self.assertEqual(setup.ram_ctx("IQ3_S", 78.5), 262144) - # #608: where the 200K estimate fits and the 256K one does not, the rule stays at 128K (200K is a menu step) - self.assertLessEqual(setup.ctx_ram_need("IQ3_S", 204800), 78.5) - self.assertGreater(setup.ctx_ram_need("IQ3_S", 262144), 77.5) - self.assertEqual(setup.ram_ctx("IQ3_S", 77.5), 131072) - for ram in range(16, 200): - for model in ("IQ3_S", "IQ3_XXS", "Q2_0"): - self.assertNotEqual(setup.ram_ctx(model, float(ram)), 204800) - self.assertEqual(setup.ram_ctx("Q2_0", 31.9), 524288) # other sizes: no RAM rule - self.assertEqual(setup.ram_ctx("IQ3_XXS", 31.9, low_ram=True), 524288) # the KV cache is in VRAM there - self.assertIsNone(setup.ctx_ram_need("IQ3_XXS", 262144, low_ram=True)) - self.assertAlmostEqual(setup.ctx_ram_need("IQ3_S", 262144), 77.9, places=1) - - def test_an_explicit_256k_is_kept(self): - code, out, cfg, _ = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start", - "--context", "262144"]) - self.assertEqual(code, 0, out) - self.assertEqual(arg(cfg, "--max-context"), "262144") - self.assertNotIn("--rope-scaling", cfg["args"]) - self.assertIn("256K with IQ3_S needs ~78 GB of RAM by setup's estimate", out) - self.assertIn("this PC has 64. Kept as you chose: it may be slower or run out of RAM under load. 128K is the " - "recommended size.", out) - - def test_a_picked_256k_is_kept_and_the_menu_says_the_risk(self): - code, out, cfg, asked = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start"], - answers={"Context?": "6"}) - self.assertEqual(code, 0, out) - self.assertEqual(arg(cfg, "--max-context"), "262144") - self.assertIn("256K tokens (needs ~78 GB RAM, this PC has 64: may run out of memory)", out) - self.assertIn("128K tokens (recommended for your GPU)\n", out) - self.assertIn("Kept as you chose", out) - - def test_a_200k_choice_is_kept(self): - """#406: 200K was added between the 128K rule and 256K - it is inside the trained 262144, so no rope scaling, - and a pick of it is kept with the note 256K gets instead of being capped to 128K.""" - code, out, cfg, _ = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start"], - answers={"Context?": "5"}) - self.assertEqual(code, 0, out) - self.assertEqual(arg(cfg, "--max-context"), "204800") - self.assertNotIn("--rope-scaling", cfg["args"]) - self.assertIn("200K tokens (needs ~77 GB RAM, this PC has 64: may run out of memory)", out) - self.assertIn("200K with IQ3_S needs ~77 GB of RAM by setup's estimate", out) - self.assertIn("Kept as you chose", out) - - def test_low_ram_mode_keeps_262k_without_a_ram_note(self): - ram, found = PROFILES["32GB-2x24GB"] # #364 - code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "IQ3_XXS", "--no-start", - "--context", "262144"]) - self.assertEqual(code, 0, out) - self.assertEqual(arg(cfg, "--max-context"), "262144") - self.assertNotIn("Kept as you chose: it may be slower", out) - - def test_the_earlier_install_keeps_its_context(self): - """An update (a new copy of PolyStrata) set up like the earlier install keeps its 256K instead of capping it.""" - with tempfile.TemporaryDirectory() as d: - prev = Path(d) / "strata-iq3_s.json" - prev.write_text(json.dumps({"args": ["--max-context", "262144", "--kv", "int8"], "port": 8080})) - started = mock.Mock(return_value=0) - code, out, cfg, _ = install(self.RAM64, self.GPU32, [], extra=[ - mock.patch.object(setup, "previous_config", lambda *a: prev), - mock.patch.object(setup, "start", started)]) - self.assertEqual(code, 0, out) - self.assertEqual(arg(cfg, "--max-context"), "262144") - self.assertIn("Kept as you chose", out) - self.assertTrue(started.called) - - -class BrokenEarlierConfig(unittest.TestCase): - """#459: a new copy of PolyStrata set up like an earlier install skips an earlier config that does not parse (an - empty strata-*.json crashed START-HERE with JSONDecodeError) and goes on as a fresh install; configs are written - whole (a temporary file moved over the old one).""" - RAM64, GPU32 = PROFILES["64GB-1x32GB"] - - def setup_with(self, files): - with tempfile.TemporaryDirectory() as d: - for i, (name, text) in enumerate(files): # in order, oldest first - (Path(d) / name).write_text(text, encoding="utf-8") - os.utime(Path(d) / name, (1_700_000_000 + i, 1_700_000_000 + i)) - return install(self.RAM64, self.GPU32, [], extra=[ - mock.patch.object(setup, "other_installs", lambda settings: [Path(d)]), - mock.patch.object(setup, "start", mock.Mock(return_value=0))]) - - def test_an_empty_config_is_skipped(self): - for text, why in (("", "the file is empty"), ("{\"args\": [", "not valid JSON"), ("[1]", "not a JSON object")): - with self.subTest(text=text): - code, out, cfg, _ = self.setup_with([("strata-iq3_s.json", text)]) - self.assertEqual(code, 0, out) - self.assertIn("skipped the earlier config ", out) - self.assertIn(f"strata-iq3_s.json ({why}): setting this copy up without it", out) - self.assertNotIn("Found your earlier install", out) - self.assertIsNotNone(cfg) # the fresh install's config - - def test_the_newest_readable_config_is_used(self): - good = json.dumps({"args": ["--max-context", "262144", "--kv", "int8"], "port": 8080}) - code, out, cfg, _ = self.setup_with([("strata-iq3_s.json", good), ("strata-q2_0.json", "")]) - self.assertEqual(code, 0, out) - self.assertIn("strata-q2_0.json (the file is empty)", out) - self.assertIn("Found your earlier install", out) - self.assertIn("(iq3_s)", out) - self.assertEqual(arg(cfg, "--max-context"), "262144") - - def test_write_config_leaves_no_partial_file(self): - with tempfile.TemporaryDirectory() as d: - p = Path(d) / "strata-iq3_s.json" - p.write_text("old", encoding="utf-8") - setup.write_config(p, {"args": ["--kv", "int8"]}) - self.assertEqual(p.read_text(encoding="utf-8"), json.dumps({"args": ["--kv", "int8"]}, indent=1)) - self.assertEqual([f.name for f in Path(d).iterdir()], ["strata-iq3_s.json"]) # no .tmp left - with mock.patch.object(Path, "write_text", side_effect=OSError(28, "No space left on device")): - with self.assertRaises(OSError): - setup.write_config(p, {"args": []}) - self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"args": ["--kv", "int8"]}) # kept whole - - -class LowRamGpus(unittest.TestCase): - """S2/S3 (#364 #384): one GPU recommended in the low-RAM mode, all of them when asked for.""" - - def setUp(self): - # the behaviour before RESIDENT_SPLIT_ENGINE (an engine from before 0.1.40); the tests of the newer engine - # patch MIN_ENGINE themselves, and the default (MIN_ENGINE = 0.1.40) is covered by test_setup_golden - p = mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) - p.start() - self.addCleanup(p.stop) - - def test_explicit_gpus_are_kept_with_the_mapped_variant(self): - for prof, model in (("32GB-2x24GB", "IQ3_XXS"), ("32GB-2x24GB", "Q2_0"), ("47GB-2x16GB", "IQ3_XXS")): - with self.subTest(prof=prof, model=model): - ram, found = PROFILES[prof] - code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", model, "--no-start", - "--gpus", "0,1"]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["layer_split"], "auto") - self.assertIn("--mmap-experts", cfg["args"]) - self.assertNotIn("--resident-experts", cfg["args"]) - self.assertIn("as you chose (--gpus)", out) - self.assertIn("RAM can fill up to 0 free", out) - self.assertIn("low-RAM mode on 2 GPUs", out) - - def test_the_share_counts_every_card(self): - ram, found = PROFILES["47GB-2x16GB"] # #384: 2 x 16 GB, 47 GB, IQ3_XXS at 64K - code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "IQ3_XXS", "--no-start", - "--gpus", "0,1"]) - one = setup.low_ram_gpu_gb("IQ3_XXS", 15.9, 65536, "int8") - self.assertIn(f"the GPUs hold ~{100 * 2 * one / setup.MODELS['IQ3_XXS']['arena_gb']:.0f}% of them", out) - - def test_asked_and_answered_two(self): - ram, found = PROFILES["32GB-2x24GB"] - code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], - answers={"Low-RAM mode: which GPUs?": "2"}) - self.assertEqual(code, 0, out) - self.assertTrue(any("Low-RAM mode: which GPUs? [1]" in q for q in asked), asked) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertIn("--mmap-experts", cfg["args"]) - self.assertIn("1) GPU 0 (NVIDIA GeForce RTX 3090, 24 GB) only", out) - - def test_yes_and_enter_keep_one_gpu(self): - ram, found = PROFILES["32GB-2x24GB"] - for answers in (None, ""): - code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], - answers=answers) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], 0) - self.assertIn("--resident-experts", cfg["args"]) - - def test_low_ram_resident_with_gpus(self): - ram, found = PROFILES["32GB-2x24GB"] - code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start", "--gpus", "0,1", - "--low-ram", "resident"]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertIn("--mmap-experts", cfg["args"]) - self.assertIn("--low-ram resident has no layer split yet", out) - - def test_low_ram_resident_alone_keeps_one_gpu_without_asking(self): - ram, found = PROFILES["32GB-2x24GB"] - code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start", - "--low-ram", "resident"], answers="") - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], 0) - self.assertFalse(any("Low-RAM mode" in q for q in asked), asked) - - def test_low_ram_on_gpus_with_a_resident_split_engine(self): - """#642: an engine that runs the resident variant on a layer split keeps the cards together, resident.""" - ram, found = PROFILES["32GB-2x24GB"] - with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): - code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], - answers="") - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertIn("--resident-experts", cfg["args"]) - self.assertFalse(any("Low-RAM mode" in q for q in asked), asked) - self.assertIn("stay in RAM", out) - code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start", - "--gpus", "0,1", "--low-ram", "resident"]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertIn("--resident-experts", cfg["args"]) - self.assertNotIn("no layer split yet", out) - - -class StartOnSeveralGpus(unittest.TestCase): - """A resident low-RAM config started on several GPUs reads the experts through the file cache (#364 #384).""" - - def setUp(self): - # the behaviour before RESIDENT_SPLIT_ENGINE (an engine from before 0.1.40); the tests of the newer engine - # patch MIN_ENGINE themselves, and the default (MIN_ENGINE = 0.1.40) is covered by test_setup_golden - p = mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) - p.start() - self.addCleanup(p.stop) - - def test_split_mmap(self): - cfg = {"args": ["--pack", "p", "--resident-experts", "--kv", "int8"]} - out = io.StringIO() - with contextlib.redirect_stdout(out): - self.assertTrue(setup.split_mmap(cfg)) - self.assertFalse(setup.split_mmap(cfg)) - self.assertFalse(setup.split_mmap({"args": ["--mmap-experts"]})) - self.assertEqual(cfg["args"], ["--pack", "p", "--mmap-experts", "--kv", "int8"]) - self.assertIn("no layer split yet", out.getvalue()) - - def offer(self, args, stdin): - found = PROFILES["32GB-2x24GB"][1] - with tempfile.TemporaryDirectory() as d: - p = Path(d) / "strata-q2_0.json" - cfg = {"args": list(args)} - with mock.patch.object(setup, "gpus", lambda: found), \ - mock.patch.object(setup, "engine_runs_on", lambda g: True): - code, out, asked = run(setup.offer_together, p, cfg, stdin is None, stdin=stdin) - return code, out, asked, json.loads(p.read_text()) - - def test_offer_together_recommends_one_gpu_for_a_resident_config(self): - code, out, asked, cfg = self.offer(["--resident-experts"], None) # --yes: the recommendation - self.assertIsNone(code, out) - self.assertNotIn("gpu", cfg) - self.assertEqual(cfg["args"], ["--resident-experts"]) - code, out, asked, cfg = self.offer(["--resident-experts"], "y") - self.assertIn("[n]", asked[0]) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["args"], ["--mmap-experts"]) # #1447: no helper cache, no --remote-expert-opt - code, out, asked, cfg = self.offer(["--mmap-experts"], None) # other configs: as before - self.assertEqual(cfg["gpu"], [0, 1]) - - def test_resident_split_engine_keeps_a_resident_config(self): - """#642: from RESIDENT_SPLIT_ENGINE a resident config is offered both cards as any other, and stays resident.""" - with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): - cfg = {"args": ["--pack", "p", "--resident-experts", "--kv", "int8"]} - self.assertFalse(setup.split_mmap(cfg)) - self.assertEqual(cfg["args"], ["--pack", "p", "--resident-experts", "--kv", "int8"]) - code, out, asked, cfg = self.offer(["--resident-experts"], None) # --yes: the recommendation - self.assertIsNone(code, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["args"], ["--resident-experts"]) - self.assertNotIn("OS file cache", out) - - def test_start_with_gpus(self): - found = PROFILES["32GB-2x24GB"][1] - with tempfile.TemporaryDirectory() as d: - exe = Path(d) / "strata.exe" - exe.write_bytes(b"") - p = Path(d) / "strata-q2_0.json" - p.write_text(json.dumps({"exe": str(exe), "args": ["--resident-experts"], "gpu": 0, "gpus_asked": True})) - call = mock.Mock(return_value=0) - with mock.patch.object(setup, "gpus", lambda: found), \ - mock.patch.object(setup, "ensure_engine_for", lambda cards, path, cfg, yes: cfg), \ - mock.patch.object(setup, "is_wsl", lambda: False), \ - mock.patch.object(setup.subprocess, "call", call): - code, out, _ = run(setup.start, p, None, [0, 1], False, True) - cfg = json.loads(p.read_text()) - self.assertIsNone(code, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["args"], ["--mmap-experts"]) # #1447: no helper cache, no --remote-expert-opt - self.assertIn("no layer split yet", out) - self.assertTrue(call.called) - - -class SmallCard(unittest.TestCase): - """S9: a card under 8 GB named with --gpus is a risk to confirm, not a stop.""" - FOUND = [card(0, "NVIDIA GeForce RTX 3090", 24.0, "86"), card(1, "NVIDIA GeForce RTX 2060", 6.0, "75")] - - def test_named_with_yes(self): - code, out, cfg, _ = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start", - "--gpus", "0,1"]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertIn("GPU 1 (NVIDIA GeForce RTX 2060) has 6 GB of VRAM", out) - self.assertIn("is used together with the others, as you chose", out) - - def test_named_and_enter_stops(self): - code, out, cfg, asked = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start", - "--gpus", "0,1"], answers="") - self.assertEqual(code, 1) - self.assertTrue(any("Use it anyway?" in q for q in asked), asked) - - def test_not_named_is_not_offered(self): - code, out, cfg, _ = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start"]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], 0) # one card: as before - - -class SplitShortCard(unittest.TestCase): - """#448: a second card too small to lend a split's prompt chunk: the first card alone recommended, the pair kept - when named.""" - FOUND = [card(0, "NVIDIA RTX PRO 4500 Blackwell", 31.8, "120"), card(1, "NVIDIA GeForce RTX 3080", 10.0, "86")] - - def test_rule(self): - self.assertEqual([g["index"] for g in setup.split_short(self.FOUND)], [1]) - self.assertEqual(setup.split_short(PROFILES["32GB-2x24GB"][1]), []) - self.assertEqual(setup.split_short(PROFILES["47GB-2x16GB"][1]), []) - eights = [card(i, "NVIDIA GeForce RTX 3070", 8.0, "86") for i in range(2)] - self.assertEqual(setup.split_short(eights), []) # neither card alone reads more - - def test_yes_takes_the_first_card(self): - code, out, cfg, _ = install(127.8, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start"]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], 0) - self.assertIn("too small to lend a split its prompt buffers", out) - - def test_named_pair_is_kept(self): - code, out, cfg, _ = install(127.8, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start", - "--gpus", "0,1"]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - - def test_offer_together_defaults_to_one(self): - with tempfile.TemporaryDirectory() as d: - p = Path(d) / "strata-q2_0.json" - with mock.patch.object(setup, "gpus", lambda: self.FOUND), \ - mock.patch.object(setup, "engine_runs_on", lambda g: True): - code, out, asked = run(setup.offer_together, p, {"args": ["--mmap-experts"]}, True) - cfg = json.loads(p.read_text()) - self.assertIsNone(code, out) - self.assertNotIn("gpu", cfg) - self.assertIn("#448", out) - - -class RamFloor(unittest.TestCase): - """S7: less RAM than the smallest model needs: a stop with --yes alone, a risk with --model.""" - FOUND = [card(0, "NVIDIA GeForce RTX 3060", 8.0, "86")] - - def test_yes_alone_stops(self): - code, out, cfg, _ = install(19.9, self.FOUND, ["--family", "qwen", "--no-start"]) - self.assertEqual(code, 1) - self.assertIn("--model NAME --yes", out) - - def test_an_explicit_model_goes_on(self): - code, out, cfg, _ = install(19.9, self.FOUND, ["--family", "coder", "--model", "IQ1_M", "--no-start"]) - self.assertEqual(code, 0, out) - self.assertIn("going on with 20 GB of RAM, as you chose", out) - - -class KvStreaming(unittest.TestCase): - """8: --kv-streaming on|off|auto (auto: the RAM test, as before).""" - RAM, FOUND = PROFILES["64GB-1x32GB"] - - def go(self, model, *flags): - return install(self.RAM, self.FOUND, ["--family", "qwen", "--model", model, "--no-start", *flags]) - - def test_off(self): - code, out, cfg, _ = self.go("IQ3_XXS", "--kv-streaming", "off") - self.assertEqual(code, 0, out) - self.assertNotIn("--kv-resident", cfg["args"]) - self.assertIn("KV streaming off, as you chose", out) - - def test_on_past_the_ram_test(self): - code, out, cfg, _ = self.go("IQ3_S", "--kv-streaming", "on") # auto leaves it off on 64 GB - self.assertEqual(code, 0, out) - self.assertEqual(arg(cfg, "--kv-resident"), "32768") - self.assertIn("Kept as you chose (--kv-streaming on)", out) - - def test_k8v4_streams(self): - code, out, cfg, _ = self.go("Q2_0", "--kv-streaming", "on", "--kv", "k8v4") - self.assertEqual(code, 0, out) - self.assertEqual(arg(cfg, "--kv-resident"), "32768") - self.assertEqual(arg(cfg, "--kv"), "k8v4") - - def test_on_where_it_cannot(self): - code, out, cfg, _ = self.go("Q2_0", "--kv-streaming", "on", "--context", "32768") - self.assertNotIn("--kv-resident", cfg["args"]) - self.assertIn("a context under 64K is not streamed", out) - - def test_budget_flag_on_another_size(self): - code, out, cfg, _ = self.go("Q2_0", "--resident-budget-gib", "30") - self.assertEqual(code, 0, out) - self.assertNotIn("--resident-budget-gib", cfg["args"]) - self.assertIn("--resident-budget-gib is for UD-Q4_K_XL", out) - - -class RulesAgreeWithTheWrittenConfig(unittest.TestCase): - """The launcher's preset diff asks setup's rules (`kv_streaming_wanted`, `low_ram_wanted`) what "auto" decides on - this PC, instead of comparing the word "auto" with a config's flags. That is only honest if those rules are - exactly what setup writes into the model's config: the same PC, the same flags, every size and every - --kv-streaming / --low-ram choice.""" - RAM64, CARDS64 = PROFILES["64GB-1x32GB"] - RAM32, CARDS32 = PROFILES["32GB-2x24GB"] - - def go(self, ram, cards, model, *flags): - return install(ram, cards, ["--family", "qwen", "--model", model, "--no-start", *flags]) - - @mock.patch.object(setup, "is_wsl", lambda: False) # #974: not WSL, as in install() - def test_the_streaming_rule_is_the_flag_setup_writes(self): - for model, ctx, kv, choice in itertools.product(("Q2_0", "IQ3_XXS", "IQ3_S"), ("32768", "131072"), - ("int8", "q4_0", "k8v4"), ("auto", "on", "off")): - code, out, cfg, _ = self.go(self.RAM64, self.CARDS64, model, "--context", ctx, "--kv", kv, - "--kv-streaming", choice) - self.assertEqual(code, 0, out) - self.assertEqual("--kv-resident" in cfg["args"], - setup.kv_streaming_wanted(model, int(ctx), kv, self.RAM64, choice), - f"{model} at {ctx} with {kv}, --kv-streaming {choice}: setup wrote {cfg['args']}") - - def test_the_low_ram_rule_is_the_flag_setup_writes(self): - pcs = [(self.RAM64, self.CARDS64), (self.RAM32, self.CARDS32)] # auto is on here, off there - for (ram, cards), model, choice in itertools.product(pcs, ("Q2_0", "IQ3_XXS", "IQ3_S"), - ("auto", "on", "off", "mmap")): - code, out, cfg, _ = self.go(ram, cards, model, "--low-ram", choice) - self.assertEqual(code, 0, out) - low = "--resident-experts" in cfg["args"] or "--mmap-experts" in cfg["args"] - self.assertEqual(low, setup.low_ram_wanted(model, ram, choice), - f"{model} on {ram:.0f} GB of RAM, --low-ram {choice}: setup wrote {cfg['args']}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_rocm_indexes.json b/tools/test_setup_rocm_indexes.json deleted file mode 100644 index a4caa18..0000000 --- a/tools/test_setup_rocm_indexes.json +++ /dev/null @@ -1,1159 +0,0 @@ -{ -"_note": "versions of the `rocm` package listed by https://rocm.nightlies.amd.com/v2//rocm/ on 2026-10-07", -"indexes": { -"gfx110X-dgpu": [ -"6.5.0rc20250610", -"7.0.0rc20250611", -"7.0.0rc20250612", -"7.0.0rc20250613", -"7.0.0rc20250614", -"7.0.0rc20250615", -"7.0.0rc20250616", -"7.0.0rc20250617", -"7.0.0rc20250618", -"7.0.0rc20250619", -"7.0.0rc20250620", -"7.0.0rc20250621", -"7.0.0rc20250622", -"7.0.0rc20250623", -"7.0.0rc20250624", -"7.0.0rc20250625", -"7.0.0rc20250626", -"7.0.0rc20250627", -"7.0.0rc20250628", -"7.0.0rc20250629", -"7.0.0rc20250630", -"7.0.0rc20250701", -"7.0.0rc20250702", -"7.0.0rc20250703", -"7.0.0rc20250704", -"7.0.0rc20250705", -"7.0.0rc20250706", -"7.0.0rc20250707", -"7.0.0rc20250708", -"7.0.0rc20250709", -"7.0.0rc20250710", -"7.0.0rc20250711", -"7.0.0rc20250712", -"7.0.0rc20250713", -"7.0.0rc20250714", -"7.0.0rc20250715", -"7.0.0rc20250716", -"7.0.0rc20250717", -"7.0.0rc20250718", -"7.0.0rc20250719", -"7.0.0rc20250720", -"7.0.0rc20250721", -"7.0.0rc20250722", -"7.0.0rc20250723", -"7.0.0rc20250724", -"7.0.0rc20250725", -"7.0.0rc20250726", -"7.0.0rc20250727", -"7.0.0rc20250728", -"7.0.0rc20250729", -"7.0.0rc20250730", -"7.0.0rc20250731", -"7.0.0rc20250801", -"7.0.0rc20250802", -"7.0.0rc20250803", -"7.0.0rc20250804", -"7.0.0rc20250805", -"7.0.0rc20250806", -"7.0.0rc20250807", -"7.0.0rc20250808", -"7.0.0rc20250809", -"7.0.0rc20250810", -"7.0.0rc20250811", -"7.0.0rc20250812", -"7.0.0rc20250813", -"7.0.0rc20250814", -"7.0.0rc20250815", -"7.0.0rc20250816", -"7.0.0rc20250817", -"7.0.0rc20250818", -"7.0.0rc20250819", -"7.0.0rc20250820", -"7.0.0rc20250821", -"7.0.0rc20250822", -"7.0.0rc20250823", -"7.0.0rc20250824", -"7.0.0rc20250825", -"7.0.0rc20250826", -"7.0.0rc20250827", -"7.0.0rc20250828", -"7.0.0rc20250829", -"7.0.0rc20250830", -"7.0.0rc20250831", -"7.0.0rc20250901", -"7.0.0rc20250902", -"7.0.0rc20250903", -"7.0.0rc20250904", -"7.0.0rc20250905", -"7.0.0rc20250906", -"7.0.0rc20250907", -"7.0.0rc20250908", -"7.0.0rc20250909", -"7.0.0rc20250910", -"7.0.0rc20250911", -"7.0.0rc20250912", -"7.0.0rc20250913", -"7.0.0rc20250915", -"7.0.0rc20250917", -"7.0.0rc20250918", -"7.0.0rc20250919", -"7.0.0rc20250920", -"7.0.0rc20250921", -"7.0.0rc20250922", -"7.10.0a20251009", -"7.10.0a20251010", -"7.10.0a20251011", -"7.10.0a20251012", -"7.10.0a20251013", -"7.10.0a20251014", -"7.10.0a20251015", -"7.10.0a20251016", -"7.10.0a20251017", -"7.10.0a20251018", -"7.10.0a20251019", -"7.10.0a20251020", -"7.10.0a20251021", -"7.10.0a20251022", -"7.10.0a20251105", -"7.10.0a20251106", -"7.10.0a20251107", -"7.10.0a20251108", -"7.10.0a20251109", -"7.10.0a20251110", -"7.10.0a20251111", -"7.10.0a20251112", -"7.10.0a20251113", -"7.10.0a20251114", -"7.10.0a20251115", -"7.10.0a20251116", -"7.10.0a20251117", -"7.10.0a20251118", -"7.10.0a20251119", -"7.10.0a20251120", -"7.9.0rc20250923", -"7.9.0rc20250924", -"7.9.0rc20250925", -"7.9.0rc20250926", -"7.9.0rc20250927", -"7.9.0rc20250928", -"7.9.0rc20250929", -"7.9.0rc20250930", -"7.9.0rc20251001", -"7.9.0rc20251002", -"7.9.0rc20251003", -"7.9.0rc20251004", -"7.9.0rc20251005", -"7.9.0rc20251007", -"7.9.0rc20251008" -], -"gfx120X-all": [ -"6.5.0rc20250610", -"7.0.0rc20250611", -"7.0.0rc20250612", -"7.0.0rc20250613", -"7.0.0rc20250614", -"7.0.0rc20250615", -"7.0.0rc20250616", -"7.0.0rc20250617", -"7.0.0rc20250618", -"7.0.0rc20250619", -"7.0.0rc20250620", -"7.0.0rc20250621", -"7.0.0rc20250622", -"7.0.0rc20250623", -"7.0.0rc20250624", -"7.0.0rc20250625", -"7.0.0rc20250626", -"7.0.0rc20250627", -"7.0.0rc20250628", -"7.0.0rc20250629", -"7.0.0rc20250630", -"7.0.0rc20250701", -"7.0.0rc20250702", -"7.0.0rc20250703", -"7.0.0rc20250704", -"7.0.0rc20250705", -"7.0.0rc20250706", -"7.0.0rc20250707", -"7.0.0rc20250708", -"7.0.0rc20250709", -"7.0.0rc20250710", -"7.0.0rc20250711", -"7.0.0rc20250712", -"7.0.0rc20250713", -"7.0.0rc20250714", -"7.0.0rc20250715", -"7.0.0rc20250716", -"7.0.0rc20250717", -"7.0.0rc20250718", -"7.0.0rc20250719", -"7.0.0rc20250720", -"7.0.0rc20250721", -"7.0.0rc20250722", -"7.0.0rc20250723", -"7.0.0rc20250724", -"7.0.0rc20250725", -"7.0.0rc20250726", -"7.0.0rc20250727", -"7.0.0rc20250728", -"7.0.0rc20250729", -"7.0.0rc20250730", -"7.0.0rc20250731", -"7.0.0rc20250801", -"7.0.0rc20250802", -"7.0.0rc20250803", -"7.0.0rc20250804", -"7.0.0rc20250805", -"7.0.0rc20250806", -"7.0.0rc20250807", -"7.0.0rc20250808", -"7.0.0rc20250809", -"7.0.0rc20250810", -"7.0.0rc20250811", -"7.0.0rc20250812", -"7.0.0rc20250813", -"7.0.0rc20250814", -"7.0.0rc20250815", -"7.0.0rc20250816", -"7.0.0rc20250817", -"7.0.0rc20250818", -"7.0.0rc20250819", -"7.0.0rc20250820", -"7.0.0rc20250821", -"7.0.0rc20250822", -"7.0.0rc20250823", -"7.0.0rc20250824", -"7.0.0rc20250825", -"7.0.0rc20250826", -"7.0.0rc20250827", -"7.0.0rc20250828", -"7.0.0rc20250829", -"7.0.0rc20250830", -"7.0.0rc20250831", -"7.0.0rc20250901", -"7.0.0rc20250902", -"7.0.0rc20250903", -"7.0.0rc20250904", -"7.0.0rc20250905", -"7.0.0rc20250906", -"7.0.0rc20250907", -"7.0.0rc20250908", -"7.0.0rc20250909", -"7.0.0rc20250910", -"7.0.0rc20250912", -"7.0.0rc20250914", -"7.0.0rc20250917", -"7.0.0rc20250918", -"7.0.0rc20250919", -"7.0.0rc20250920", -"7.0.0rc20250921", -"7.0.0rc20250922", -"7.10.0a20251009", -"7.10.0a20251010", -"7.10.0a20251011", -"7.10.0a20251012", -"7.10.0a20251013", -"7.10.0a20251014", -"7.10.0a20251015", -"7.10.0a20251016", -"7.10.0a20251017", -"7.10.0a20251018", -"7.10.0a20251019", -"7.10.0a20251020", -"7.10.0a20251021", -"7.10.0a20251022", -"7.10.0a20251023", -"7.10.0a20251024", -"7.10.0a20251026", -"7.10.0a20251027", -"7.10.0a20251028", -"7.10.0a20251029", -"7.10.0a20251030", -"7.10.0a20251031", -"7.10.0a20251101", -"7.10.0a20251102", -"7.10.0a20251103", -"7.10.0a20251104", -"7.10.0a20251105", -"7.10.0a20251106", -"7.10.0a20251107", -"7.10.0a20251108", -"7.10.0a20251109", -"7.10.0a20251110", -"7.10.0a20251111", -"7.10.0a20251112", -"7.10.0a20251113", -"7.10.0a20251114", -"7.10.0a20251115", -"7.10.0a20251116", -"7.10.0a20251117", -"7.10.0a20251118", -"7.10.0a20251119", -"7.10.0a20251120", -"7.10.0a20251121", -"7.11.0a20251122", -"7.11.0a20251123", -"7.11.0a20251124", -"7.11.0a20251125", -"7.11.0a20251126", -"7.11.0a20251127", -"7.11.0a20251128", -"7.11.0a20251129", -"7.11.0a20251130", -"7.11.0a20251201", -"7.11.0a20251202", -"7.11.0a20251203", -"7.11.0a20251204", -"7.11.0a20251205", -"7.11.0a20251206", -"7.11.0a20251207", -"7.11.0a20251208", -"7.11.0a20251209", -"7.11.0a20251210", -"7.11.0a20251211", -"7.11.0a20251212", -"7.11.0a20251213", -"7.11.0a20251214", -"7.11.0a20251215", -"7.11.0a20251216", -"7.11.0a20251217", -"7.11.0a20251218", -"7.11.0a20251219", -"7.11.0a20251220", -"7.11.0a20251221", -"7.11.0a20251222", -"7.11.0a20251223", -"7.11.0a20251224", -"7.11.0a20251225", -"7.11.0a20251226", -"7.11.0a20251227", -"7.11.0a20251228", -"7.11.0a20251229", -"7.11.0a20251230", -"7.11.0a20251231", -"7.11.0a20260101", -"7.11.0a20260102", -"7.11.0a20260103", -"7.11.0a20260104", -"7.11.0a20260105", -"7.11.0a20260106", -"7.11.0a20260107", -"7.11.0a20260108", -"7.11.0a20260109", -"7.11.0a20260110", -"7.11.0a20260111", -"7.11.0a20260112", -"7.11.0a20260113", -"7.11.0a20260114", -"7.11.0a20260115", -"7.11.0a20260116", -"7.11.0a20260117", -"7.11.0a20260118", -"7.11.0a20260119", -"7.11.0a20260120", -"7.11.0a20260121", -"7.12.0a20260122", -"7.12.0a20260123", -"7.12.0a20260124", -"7.12.0a20260125", -"7.12.0a20260126", -"7.12.0a20260127", -"7.12.0a20260128", -"7.12.0a20260129", -"7.12.0a20260130", -"7.12.0a20260131", -"7.12.0a20260201", -"7.12.0a20260202", -"7.12.0a20260203", -"7.12.0a20260204", -"7.12.0a20260205", -"7.12.0a20260206", -"7.12.0a20260207", -"7.12.0a20260208", -"7.12.0a20260209", -"7.12.0a20260210", -"7.12.0a20260211", -"7.12.0a20260212", -"7.12.0a20260213", -"7.12.0a20260214", -"7.12.0a20260215", -"7.12.0a20260216", -"7.12.0a20260217", -"7.12.0a20260218", -"7.12.0a20260219", -"7.12.0a20260220", -"7.12.0a20260221", -"7.12.0a20260222", -"7.12.0a20260223", -"7.12.0a20260224", -"7.12.0a20260225", -"7.12.0a20260226", -"7.12.0a20260227", -"7.12.0a20260228", -"7.12.0a20260301", -"7.12.0a20260302", -"7.12.0a20260303", -"7.12.0a20260304", -"7.12.0a20260305", -"7.12.0a20260306", -"7.12.0a20260307", -"7.12.0a20260308", -"7.12.0a20260309", -"7.12.0a20260310", -"7.12.0a20260311", -"7.13.0a20260312", -"7.13.0a20260313", -"7.13.0a20260314", -"7.13.0a20260315", -"7.13.0a20260316", -"7.13.0a20260317", -"7.13.0a20260318", -"7.13.0a20260319", -"7.13.0a20260320", -"7.13.0a20260321", -"7.13.0a20260322", -"7.13.0a20260323", -"7.13.0a20260324", -"7.13.0a20260325", -"7.13.0a20260326", -"7.13.0a20260327", -"7.13.0a20260328", -"7.13.0a20260329", -"7.13.0a20260330", -"7.13.0a20260331", -"7.13.0a20260401", -"7.13.0a20260402", -"7.13.0a20260403", -"7.13.0a20260404", -"7.13.0a20260405", -"7.13.0a20260406", -"7.13.0a20260407", -"7.13.0a20260408", -"7.13.0a20260409", -"7.13.0a20260410", -"7.13.0a20260411", -"7.13.0a20260412", -"7.13.0a20260413", -"7.13.0a20260414", -"7.13.0a20260415", -"7.13.0a20260416", -"7.13.0a20260417", -"7.13.0a20260418", -"7.13.0a20260419", -"7.13.0a20260420", -"7.13.0a20260421", -"7.13.0a20260422", -"7.13.0a20260423", -"7.13.0a20260424", -"7.13.0a20260425", -"7.13.0a20260426", -"7.13.0a20260427", -"7.13.0a20260428", -"7.13.0a20260429", -"7.13.0a20260430", -"7.13.0a20260501", -"7.13.0a20260502", -"7.13.0a20260503", -"7.13.0a20260504", -"7.13.0a20260505", -"7.13.0a20260506", -"7.13.0a20260507", -"7.13.0a20260508", -"7.13.0a20260509", -"7.13.0a20260510", -"7.13.0a20260511", -"7.13.0a20260512", -"7.13.0a20260513", -"7.13.0a20260514", -"7.13.0a20260515", -"7.14.0a20260516", -"7.14.0a20260517", -"7.14.0a20260518", -"7.14.0a20260519", -"7.14.0a20260520", -"7.14.0a20260521", -"7.14.0a20260522", -"7.14.0a20260523", -"7.14.0a20260524", -"7.14.0a20260525", -"7.14.0a20260526", -"7.14.0a20260527", -"7.14.0a20260528", -"7.14.0a20260529", -"7.14.0a20260530", -"7.14.0a20260531", -"7.14.0a20260601", -"7.14.0a20260602", -"7.14.0a20260603", -"7.14.0a20260604", -"7.14.0a20260605", -"7.14.0a20260606", -"7.14.0a20260607", -"7.14.0a20260608", -"7.14.0a20260609", -"7.14.0a20260610", -"7.14.0a20260611", -"7.14.0a20260612", -"7.9.0rc20250923", -"7.9.0rc20250924", -"7.9.0rc20250925", -"7.9.0rc20250926", -"7.9.0rc20250927", -"7.9.0rc20250928", -"7.9.0rc20250929", -"7.9.0rc20250930", -"7.9.0rc20251001", -"7.9.0rc20251002", -"7.9.0rc20251003", -"7.9.0rc20251004", -"7.9.0rc20251005", -"7.9.0rc20251006", -"7.9.0rc20251007", -"7.9.0rc20251008" -], -"gfx103X-all": [ -"7.13.0a20260422", -"7.13.0a20260423", -"7.13.0a20260424", -"7.13.0a20260425", -"7.13.0a20260426", -"7.13.0a20260427", -"7.13.0a20260428", -"7.13.0a20260429", -"7.13.0a20260430", -"7.13.0a20260501", -"7.13.0a20260502", -"7.13.0a20260503", -"7.13.0a20260504", -"7.13.0a20260505", -"7.13.0a20260506", -"7.13.0a20260507", -"7.13.0a20260508", -"7.13.0a20260509", -"7.13.0a20260510", -"7.13.0a20260511", -"7.13.0a20260512", -"7.13.0a20260513", -"7.13.0a20260514", -"7.13.0a20260515", -"7.14.0a20260516", -"7.14.0a20260517", -"7.14.0a20260518", -"7.14.0a20260519", -"7.14.0a20260520", -"7.14.0a20260521", -"7.14.0a20260522", -"7.14.0a20260523", -"7.14.0a20260524", -"7.14.0a20260525", -"7.14.0a20260526", -"7.14.0a20260527", -"7.14.0a20260528", -"7.14.0a20260529", -"7.14.0a20260530", -"7.14.0a20260531", -"7.14.0a20260601", -"7.14.0a20260602", -"7.14.0a20260603", -"7.14.0a20260604", -"7.14.0a20260605", -"7.14.0a20260606", -"7.14.0a20260607", -"7.14.0a20260608", -"7.14.0a20260611", -"7.14.0a20260612" -], -"gfx1151": [ -"6.5.0rc20250610", -"7.0.0rc20250611", -"7.0.0rc20250612", -"7.0.0rc20250613", -"7.0.0rc20250614", -"7.0.0rc20250615", -"7.0.0rc20250616", -"7.0.0rc20250617", -"7.0.0rc20250618", -"7.0.0rc20250619", -"7.0.0rc20250620", -"7.0.0rc20250621", -"7.0.0rc20250622", -"7.0.0rc20250623", -"7.0.0rc20250624", -"7.0.0rc20250625", -"7.0.0rc20250626", -"7.0.0rc20250627", -"7.0.0rc20250628", -"7.0.0rc20250629", -"7.0.0rc20250630", -"7.0.0rc20250701", -"7.0.0rc20250702", -"7.0.0rc20250703", -"7.0.0rc20250704", -"7.0.0rc20250705", -"7.0.0rc20250706", -"7.0.0rc20250707", -"7.0.0rc20250708", -"7.0.0rc20250709", -"7.0.0rc20250710", -"7.0.0rc20250711", -"7.0.0rc20250712", -"7.0.0rc20250713", -"7.0.0rc20250714", -"7.0.0rc20250715", -"7.0.0rc20250716", -"7.0.0rc20250717", -"7.0.0rc20250718", -"7.0.0rc20250719", -"7.0.0rc20250720", -"7.0.0rc20250721", -"7.0.0rc20250722", -"7.0.0rc20250723", -"7.0.0rc20250724", -"7.0.0rc20250725", -"7.0.0rc20250726", -"7.0.0rc20250727", -"7.0.0rc20250728", -"7.0.0rc20250729", -"7.0.0rc20250730", -"7.0.0rc20250731", -"7.0.0rc20250801", -"7.0.0rc20250802", -"7.0.0rc20250803", -"7.0.0rc20250804", -"7.0.0rc20250805", -"7.0.0rc20250806", -"7.0.0rc20250807", -"7.0.0rc20250808", -"7.0.0rc20250809", -"7.0.0rc20250810", -"7.0.0rc20250811", -"7.0.0rc20250812", -"7.0.0rc20250813", -"7.0.0rc20250814", -"7.0.0rc20250815", -"7.0.0rc20250816", -"7.0.0rc20250817", -"7.0.0rc20250818", -"7.0.0rc20250819", -"7.0.0rc20250820", -"7.0.0rc20250821", -"7.0.0rc20250822", -"7.0.0rc20250823", -"7.0.0rc20250824", -"7.0.0rc20250825", -"7.0.0rc20250826", -"7.0.0rc20250827", -"7.0.0rc20250828", -"7.0.0rc20250829", -"7.0.0rc20250830", -"7.0.0rc20250831", -"7.0.0rc20250901", -"7.0.0rc20250902", -"7.0.0rc20250903", -"7.0.0rc20250904", -"7.0.0rc20250905", -"7.0.0rc20250906", -"7.0.0rc20250907", -"7.0.0rc20250908", -"7.0.0rc20250909", -"7.0.0rc20250910", -"7.0.0rc20250911", -"7.0.0rc20250912", -"7.0.0rc20250913", -"7.0.0rc20250914", -"7.0.0rc20250915", -"7.0.0rc20250917", -"7.0.0rc20250918", -"7.0.0rc20250919", -"7.0.0rc20250920", -"7.0.0rc20250921", -"7.0.0rc20250922", -"7.10.0a20251009", -"7.10.0a20251010", -"7.10.0a20251011", -"7.10.0a20251012", -"7.10.0a20251013", -"7.10.0a20251014", -"7.10.0a20251015", -"7.10.0a20251016", -"7.10.0a20251017", -"7.10.0a20251018", -"7.10.0a20251019", -"7.10.0a20251020", -"7.10.0a20251021", -"7.10.0a20251022", -"7.10.0a20251023", -"7.10.0a20251024", -"7.10.0a20251025", -"7.10.0a20251026", -"7.10.0a20251027", -"7.10.0a20251028", -"7.10.0a20251029", -"7.10.0a20251030", -"7.10.0a20251031", -"7.10.0a20251101", -"7.10.0a20251102", -"7.10.0a20251103", -"7.10.0a20251104", -"7.10.0a20251105", -"7.10.0a20251106", -"7.10.0a20251107", -"7.10.0a20251108", -"7.10.0a20251109", -"7.10.0a20251110", -"7.10.0a20251111", -"7.10.0a20251112", -"7.10.0a20251113", -"7.10.0a20251114", -"7.10.0a20251115", -"7.10.0a20251116", -"7.10.0a20251117", -"7.10.0a20251118", -"7.10.0a20251119", -"7.10.0a20251120", -"7.10.0a20251121", -"7.11.0a20251122", -"7.11.0a20251123", -"7.11.0a20251124", -"7.11.0a20251125", -"7.11.0a20251126", -"7.11.0a20251127", -"7.11.0a20251128", -"7.11.0a20251129", -"7.11.0a20251130", -"7.11.0a20251201", -"7.11.0a20251202", -"7.11.0a20251203", -"7.11.0a20251204", -"7.11.0a20251205", -"7.11.0a20251206", -"7.11.0a20251207", -"7.11.0a20251208", -"7.11.0a20251209", -"7.11.0a20251210", -"7.11.0a20251211", -"7.11.0a20251212", -"7.11.0a20251213", -"7.11.0a20251214", -"7.11.0a20251215", -"7.11.0a20251216", -"7.11.0a20251217", -"7.11.0a20251218", -"7.11.0a20251219", -"7.11.0a20251220", -"7.11.0a20251221", -"7.11.0a20251222", -"7.11.0a20251223", -"7.11.0a20251224", -"7.11.0a20251225", -"7.11.0a20251226", -"7.11.0a20251227", -"7.11.0a20251228", -"7.11.0a20251229", -"7.11.0a20251230", -"7.11.0a20251231", -"7.11.0a20260101", -"7.11.0a20260102", -"7.11.0a20260103", -"7.11.0a20260104", -"7.11.0a20260105", -"7.11.0a20260106", -"7.11.0a20260107", -"7.11.0a20260108", -"7.11.0a20260109", -"7.11.0a20260110", -"7.11.0a20260111", -"7.11.0a20260112", -"7.11.0a20260113", -"7.11.0a20260114", -"7.11.0a20260115", -"7.11.0a20260116", -"7.11.0a20260117", -"7.11.0a20260118", -"7.11.0a20260119", -"7.11.0a20260120", -"7.11.0a20260121", -"7.12.0a20260122", -"7.12.0a20260123", -"7.12.0a20260124", -"7.12.0a20260125", -"7.12.0a20260126", -"7.12.0a20260127", -"7.12.0a20260128", -"7.12.0a20260129", -"7.12.0a20260130", -"7.12.0a20260131", -"7.12.0a20260201", -"7.12.0a20260202", -"7.12.0a20260203", -"7.12.0a20260204", -"7.12.0a20260205", -"7.12.0a20260206", -"7.12.0a20260207", -"7.12.0a20260208", -"7.12.0a20260209", -"7.12.0a20260210", -"7.12.0a20260211", -"7.12.0a20260212", -"7.12.0a20260213", -"7.12.0a20260214", -"7.12.0a20260215", -"7.12.0a20260216", -"7.12.0a20260217", -"7.12.0a20260218", -"7.12.0a20260219", -"7.12.0a20260220", -"7.12.0a20260221", -"7.12.0a20260222", -"7.12.0a20260223", -"7.12.0a20260224", -"7.12.0a20260225", -"7.12.0a20260226", -"7.12.0a20260227", -"7.12.0a20260228", -"7.12.0a20260301", -"7.12.0a20260302", -"7.12.0a20260303", -"7.12.0a20260304", -"7.12.0a20260305", -"7.12.0a20260306", -"7.12.0a20260307", -"7.12.0a20260308", -"7.12.0a20260309", -"7.12.0a20260310", -"7.12.0a20260311", -"7.13.0a20260312", -"7.13.0a20260313", -"7.13.0a20260314", -"7.13.0a20260315", -"7.13.0a20260316", -"7.13.0a20260317", -"7.13.0a20260318", -"7.13.0a20260319", -"7.13.0a20260320", -"7.13.0a20260321", -"7.13.0a20260322", -"7.13.0a20260323", -"7.13.0a20260324", -"7.13.0a20260325", -"7.13.0a20260326", -"7.13.0a20260327", -"7.13.0a20260328", -"7.13.0a20260329", -"7.13.0a20260330", -"7.13.0a20260331", -"7.13.0a20260401", -"7.13.0a20260402", -"7.13.0a20260403", -"7.13.0a20260404", -"7.13.0a20260405", -"7.13.0a20260406", -"7.13.0a20260407", -"7.13.0a20260408", -"7.13.0a20260409", -"7.13.0a20260410", -"7.13.0a20260411", -"7.13.0a20260412", -"7.13.0a20260413", -"7.13.0a20260414", -"7.13.0a20260415", -"7.13.0a20260416", -"7.13.0a20260417", -"7.13.0a20260418", -"7.13.0a20260419", -"7.13.0a20260420", -"7.13.0a20260421", -"7.13.0a20260422", -"7.13.0a20260423", -"7.13.0a20260424", -"7.13.0a20260425", -"7.13.0a20260426", -"7.13.0a20260427", -"7.13.0a20260428", -"7.13.0a20260429", -"7.13.0a20260430", -"7.13.0a20260501", -"7.13.0a20260502", -"7.13.0a20260503", -"7.13.0a20260504", -"7.13.0a20260505", -"7.13.0a20260506", -"7.13.0a20260507", -"7.13.0a20260508", -"7.13.0a20260509", -"7.13.0a20260510", -"7.13.0a20260511", -"7.13.0a20260512", -"7.13.0a20260513", -"7.13.0a20260514", -"7.13.0a20260515", -"7.14.0a20260516", -"7.14.0a20260517", -"7.14.0a20260518", -"7.14.0a20260519", -"7.14.0a20260520", -"7.14.0a20260521", -"7.14.0a20260522", -"7.14.0a20260523", -"7.14.0a20260524", -"7.14.0a20260525", -"7.14.0a20260526", -"7.14.0a20260527", -"7.14.0a20260528", -"7.14.0a20260529", -"7.14.0a20260530", -"7.14.0a20260531", -"7.14.0a20260601", -"7.14.0a20260602", -"7.14.0a20260603", -"7.14.0a20260604", -"7.14.0a20260605", -"7.14.0a20260606", -"7.14.0a20260607", -"7.14.0a20260608", -"7.14.0a20260609", -"7.14.0a20260610", -"7.14.0a20260611", -"7.14.0a20260612", -"7.9.0rc20250923", -"7.9.0rc20250924", -"7.9.0rc20250925", -"7.9.0rc20250926", -"7.9.0rc20250927", -"7.9.0rc20250928", -"7.9.0rc20250929", -"7.9.0rc20250930", -"7.9.0rc20251001", -"7.9.0rc20251002", -"7.9.0rc20251003", -"7.9.0rc20251004", -"7.9.0rc20251005", -"7.9.0rc20251006", -"7.9.0rc20251007", -"7.9.0rc20251008" -], -"gfx110X-all": [ -"7.10.0a20251023", -"7.10.0a20251024", -"7.10.0a20251025", -"7.10.0a20251026", -"7.10.0a20251027", -"7.10.0a20251028", -"7.10.0a20251030", -"7.10.0a20251031", -"7.10.0a20251101", -"7.10.0a20251102", -"7.10.0a20251103", -"7.10.0a20251104", -"7.10.0a20251121", -"7.11.0a20251122", -"7.11.0a20251123", -"7.11.0a20251124", -"7.11.0a20251125", -"7.11.0a20251126", -"7.11.0a20251127", -"7.11.0a20251128", -"7.11.0a20251129", -"7.11.0a20251130", -"7.11.0a20251201", -"7.11.0a20251202", -"7.11.0a20251203", -"7.11.0a20251204", -"7.11.0a20251205", -"7.11.0a20251206", -"7.11.0a20251207", -"7.11.0a20251208", -"7.11.0a20251209", -"7.11.0a20251210", -"7.11.0a20251211", -"7.11.0a20251212", -"7.11.0a20251213", -"7.11.0a20251214", -"7.11.0a20251215", -"7.11.0a20251216", -"7.11.0a20251217", -"7.11.0a20251218", -"7.11.0a20251219", -"7.11.0a20251220", -"7.11.0a20251221", -"7.11.0a20251222", -"7.11.0a20251223", -"7.11.0a20251224", -"7.11.0a20251225", -"7.11.0a20251226", -"7.11.0a20251227", -"7.11.0a20251228", -"7.11.0a20251229", -"7.11.0a20251230", -"7.11.0a20251231", -"7.11.0a20260101", -"7.11.0a20260102", -"7.11.0a20260103", -"7.11.0a20260104", -"7.11.0a20260105", -"7.11.0a20260106", -"7.11.0a20260107", -"7.11.0a20260108", -"7.11.0a20260109", -"7.11.0a20260110", -"7.11.0a20260111", -"7.11.0a20260112", -"7.11.0a20260113", -"7.11.0a20260114", -"7.11.0a20260115", -"7.11.0a20260116", -"7.11.0a20260117", -"7.11.0a20260118", -"7.11.0a20260119", -"7.11.0a20260120", -"7.11.0a20260121", -"7.12.0a20260122", -"7.12.0a20260123", -"7.12.0a20260124", -"7.12.0a20260125", -"7.12.0a20260126", -"7.12.0a20260127", -"7.12.0a20260128", -"7.12.0a20260129", -"7.12.0a20260130", -"7.12.0a20260131", -"7.12.0a20260201", -"7.12.0a20260202", -"7.12.0a20260203", -"7.12.0a20260204", -"7.12.0a20260205", -"7.12.0a20260206", -"7.12.0a20260207", -"7.12.0a20260208", -"7.12.0a20260209", -"7.12.0a20260210", -"7.12.0a20260211", -"7.12.0a20260212", -"7.12.0a20260213", -"7.12.0a20260214", -"7.12.0a20260215", -"7.12.0a20260216", -"7.12.0a20260217", -"7.12.0a20260218", -"7.12.0a20260219", -"7.12.0a20260220", -"7.12.0a20260221", -"7.12.0a20260222", -"7.12.0a20260223", -"7.12.0a20260224", -"7.12.0a20260225", -"7.12.0a20260226", -"7.12.0a20260227", -"7.12.0a20260228", -"7.12.0a20260301", -"7.12.0a20260302", -"7.12.0a20260303", -"7.12.0a20260304", -"7.12.0a20260305", -"7.12.0a20260306", -"7.12.0a20260307", -"7.12.0a20260308", -"7.12.0a20260309", -"7.12.0a20260310", -"7.12.0a20260311", -"7.13.0a20260312", -"7.13.0a20260313", -"7.13.0a20260314", -"7.13.0a20260315", -"7.13.0a20260316", -"7.13.0a20260317", -"7.13.0a20260318", -"7.13.0a20260319", -"7.13.0a20260320", -"7.13.0a20260321", -"7.13.0a20260322", -"7.13.0a20260323", -"7.13.0a20260324", -"7.13.0a20260325", -"7.13.0a20260326", -"7.13.0a20260327", -"7.13.0a20260328", -"7.13.0a20260329", -"7.13.0a20260330", -"7.13.0a20260331", -"7.13.0a20260401", -"7.13.0a20260402", -"7.13.0a20260403", -"7.13.0a20260404", -"7.13.0a20260405", -"7.13.0a20260406", -"7.13.0a20260407", -"7.13.0a20260408", -"7.13.0a20260409", -"7.13.0a20260410", -"7.13.0a20260411", -"7.13.0a20260412", -"7.13.0a20260413", -"7.13.0a20260414", -"7.13.0a20260415", -"7.13.0a20260416", -"7.13.0a20260417", -"7.13.0a20260418", -"7.13.0a20260419", -"7.13.0a20260420", -"7.13.0a20260421", -"7.13.0a20260422", -"7.13.0a20260423", -"7.13.0a20260424", -"7.13.0a20260425", -"7.13.0a20260426", -"7.13.0a20260427", -"7.13.0a20260428", -"7.13.0a20260429", -"7.13.0a20260430", -"7.13.0a20260501", -"7.13.0a20260502", -"7.13.0a20260503", -"7.13.0a20260504", -"7.13.0a20260505", -"7.13.0a20260506", -"7.13.0a20260507", -"7.13.0a20260508", -"7.13.0a20260509", -"7.13.0a20260510", -"7.13.0a20260511", -"7.13.0a20260512", -"7.13.0a20260513", -"7.13.0a20260514", -"7.13.0a20260515", -"7.14.0a20260516", -"7.14.0a20260517", -"7.14.0a20260518", -"7.14.0a20260519", -"7.14.0a20260520", -"7.14.0a20260521", -"7.14.0a20260522", -"7.14.0a20260523", -"7.14.0a20260524", -"7.14.0a20260525", -"7.14.0a20260526", -"7.14.0a20260527", -"7.14.0a20260528", -"7.14.0a20260529", -"7.14.0a20260530", -"7.14.0a20260531", -"7.14.0a20260601", -"7.14.0a20260602", -"7.14.0a20260603", -"7.14.0a20260604", -"7.14.0a20260605", -"7.14.0a20260606", -"7.14.0a20260607", -"7.14.0a20260608", -"7.14.0a20260609", -"7.14.0a20260610", -"7.14.0a20260611", -"7.14.0a20260612" -] -} -} \ No newline at end of file diff --git a/tools/test_setup_rocm_pins.py b/tools/test_setup_rocm_pins.py deleted file mode 100644 index 69f0d4f..0000000 --- a/tools/test_setup_rocm_pins.py +++ /dev/null @@ -1,168 +0,0 @@ -"""Tests for the per-family ROCm wheel choice of setup.py (#1103, #1267), against the version lists that AMD's TheRock -indexes really offered on 2026-10-07 (tools/test_setup_rocm_indexes.json), and for the sm_120 compiler warning that -now covers CUDA 13.2.0 / 13.2.1 only (#968). No network, no GPU. - - python -m unittest tools.test_setup_rocm_pins -""" -from __future__ import annotations - -import json -import sys -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - -LISTINGS = json.loads((ROOT / "tools" / "test_setup_rocm_indexes.json").read_text(encoding="utf-8"))["indexes"] - - -def page(family): - """The index page's html as pip sees it, from the saved version list.""" - return "" + "".join(f'rocm-{v}.tar.gz
' for v in LISTINGS[family]) + "" - - -class RocmPick(unittest.TestCase): - def setUp(self): - p = mock.patch.object(setup, "ROCM_VERSION_OVERRIDE", None) - p.start() - self.addCleanup(p.stop) - - def want(self, arch): - index = setup.ROCM_INDEXES[arch] - return setup.rocm_wanted(index, page(setup.rocm_family(index))) - - def test_every_family_gets_a_version_its_index_has(self): - for arch in setup.ROCM_INDEXES: - if setup.rocm_family(setup.ROCM_INDEXES[arch]) not in LISTINGS: - continue # the gfx1150 opt-in (#2147): no saved version list for its index yet - with self.subTest(arch=arch): - version, note = self.want(arch) - self.assertIn(version, LISTINGS[setup.rocm_family(setup.ROCM_INDEXES[arch])]) - self.assertIsNone(note, note) # the shipped pins all exist: no warning - - def test_gfx103X_has_no_7_10_but_gets_the_7_13_pin(self): # #1103 - self.assertFalse([v for v in LISTINGS["gfx103X-all"] if v.startswith("7.10")]) - self.assertEqual(self.want("gfx1030"), ("7.13.0a20260515", None)) - self.assertEqual(self.want("gfx1031"), ("7.13.0a20260515", None)) - - def test_gfx120X_and_gfx110X_keep_the_tested_version(self): - for arch in ("gfx1201", "gfx1200", "gfx1100", "gfx1101", "gfx1102"): - self.assertEqual(self.want(arch), ("7.10.0a20251120", None)) - - def test_gfx1151_is_off_the_7_10_wheel(self): # #1267 - version, note = self.want("gfx1151") - self.assertEqual((version, note), ("7.14.0a20260608", None)) - self.assertGreaterEqual(setup.rocm_vkey(version)[:2], (7, 11)) - - def test_pinned_version_gone_falls_back_to_the_same_line_with_a_warning(self): - old = setup.ROCM_FAMILY_PINS["gfx103X-all"] - with mock.patch.dict(setup.ROCM_FAMILY_PINS, {"gfx103X-all": "7.13.0a20260301"}): - version, note = setup.rocm_wanted(setup.ROCM_INDEXES["gfx1030"], page("gfx103X-all")) - self.assertEqual(version, "7.13.0a20260515") # the newest of 7.13, not of 7.14 - self.assertIn("7.13.0a20260301", note) - self.assertIn("same line", note) - self.assertEqual(old, "7.13.0a20260515") - - def test_whole_line_gone_falls_back_to_the_same_major(self): - # gfx103X-all has no 7.10 line at all: the default 7.10.0a20251120 would land on the newest 7.x there - with mock.patch.dict(setup.ROCM_FAMILY_PINS, {"gfx103X-all": "7.10.0a20251120"}): - version, note = setup.rocm_wanted(setup.ROCM_INDEXES["gfx1030"], page("gfx103X-all")) - self.assertEqual(version, "7.14.0a20260612") - self.assertIn("same major", note) - - def test_other_major_is_not_taken(self): - version, note = setup.rocm_pick(["6.5.0rc20250610"], "7.10.0a20251120") - self.assertEqual(version, "7.10.0a20251120") - self.assertIn("nothing of its major", note) - - def test_unreadable_index_keeps_the_preferred_version(self): - self.assertEqual(setup.rocm_pick([], "7.10.0a20251120"), ("7.10.0a20251120", None)) - with mock.patch.object(setup.urllib.request, "urlopen", side_effect=OSError("offline")): - self.assertEqual(setup.rocm_wanted(setup.ROCM_INDEXES["gfx1030"]), ("7.13.0a20260515", None)) - - def test_the_index_page_is_read_from_the_rocm_folder(self): - seen = [] - - class Resp: - def __enter__(self): return self - def __exit__(self, *a): return False - def read(self): return page("gfx103X-all").encode() - - def fake(req, timeout=0): - seen.append(req.full_url) - return Resp() - with mock.patch.object(setup.urllib.request, "urlopen", fake): - self.assertEqual(setup.rocm_wanted(setup.ROCM_INDEXES["gfx1030"])[0], "7.13.0a20260515") - self.assertEqual(seen, ["https://rocm.nightlies.amd.com/v2/gfx103X-all/rocm/"]) - - def test_the_override_is_exact_and_not_looked_up(self): - with mock.patch.object(setup, "ROCM_VERSION_OVERRIDE", "7.12.0a20260311"), \ - mock.patch.object(setup.urllib.request, "urlopen", side_effect=AssertionError("no lookup")): - self.assertEqual(setup.rocm_wanted(setup.ROCM_INDEXES["gfx1030"]), ("7.12.0a20260311", None)) - with mock.patch.object(setup, "ROCM_VERSION_OVERRIDE", "7.10.0a20251120"): # forced, but still warned about - version, note = setup.rocm_wanted(setup.ROCM_INDEXES["gfx1151"]) - self.assertEqual(version, "7.10.0a20251120") - self.assertIn("segfault", note) - - def test_gfx1151_on_the_7_10_wheel_warns(self): # #1267 with an override or a fallback - version, note = None, None - with mock.patch.dict(setup.ROCM_FAMILY_PINS, {"gfx1151": "7.10.0a20251120"}): - version, note = setup.rocm_wanted(setup.ROCM_INDEXES["gfx1151"], page("gfx1151")) - self.assertEqual(version, "7.10.0a20251120") - self.assertIn("segfault", note) - - def test_version_order(self): - v = setup.rocm_index_versions(page("gfx1151")) - self.assertEqual(v, sorted(v, key=setup.rocm_vkey)) - self.assertEqual(v[-1], "7.14.0a20260612") - self.assertLess(setup.rocm_vkey("7.9.0rc20251008"), setup.rocm_vkey("7.10.0a20251009")) # 7.9 before 7.10 - - -class Sm120Compiler(unittest.TestCase): - """#968: only CUDA 13.2.0 / 13.2.1 (nvcc build 51) are warned about; 13.2.2 (build 86) is accepted.""" - - def run_sm120(self, build, archs=(120,), cuda_v=(13, 2), env=None): - with mock.patch.object(setup, "nvcc_build", return_value=build), \ - mock.patch.object(setup, "find_nvcc", return_value=(None, None)), \ - mock.patch.object(setup, "warn") as warn, mock.patch.object(setup, "ok"), \ - mock.patch.dict(setup.os.environ, env or {}): - got = setup.sm120_nvcc("nvcc", cuda_v, list(archs)) - return got, warn - - def test_13_2_0_and_13_2_1_warn(self): - for build in (51, 78, None): # None: a build that cannot be read stays suspect - got, warn = self.run_sm120(build) - self.assertEqual(got, ("nvcc", (13, 2))) - warn.assert_called_once() - self.assertIn("13.2.0", warn.call_args[0][0]) - - def test_13_2_2_is_accepted_silently(self): - for build in (86, 90): - got, warn = self.run_sm120(build) - self.assertEqual(got, ("nvcc", (13, 2))) - warn.assert_not_called() - - def test_13_2_2_keeps_the_newest_toolkit_not_an_older_one(self): - with mock.patch.object(setup, "nvcc_build", return_value=86), \ - mock.patch.object(setup, "find_nvcc", side_effect=AssertionError("must not look for an older one")): - self.assertEqual(setup.sm120_nvcc("nvcc", (13, 2), [120]), ("nvcc", (13, 2))) - - def test_not_sm120_or_not_13_2_is_untouched(self): - for archs, v in (((86,), (13, 2)), ((120,), (13, 0)), ((120,), (13, 3))): - got, warn = self.run_sm120(51, archs, v) - self.assertEqual(got, ("nvcc", v)) - warn.assert_not_called() - - def test_build_number_is_read_from_nvcc_output(self): - text = "nvcc: NVIDIA (R) Cuda compiler driver\nCuda compilation tools, release 13.2, V13.2.86\nBuild cuda_13.2.r13.2/compiler.123_0\n" - with mock.patch.object(setup, "out", return_value=text): - self.assertEqual(setup.nvcc_build("nvcc"), 86) - with mock.patch.object(setup, "out", return_value=""): - self.assertIsNone(setup.nvcc_build("nvcc")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_rope.py b/tools/test_setup_rope.py deleted file mode 100644 index 85b47f9..0000000 --- a/tools/test_setup_rope.py +++ /dev/null @@ -1,121 +0,0 @@ -"""Tests for setup.py's automatic rope configuration (§4 + §6): the factor derives from the FINAL context -actually served - RAM reductions first, then final / trained 262144 clamped at 1 - explicit ---rope-scaling/--rope-scale choices win verbatim, an explicit none is refused past the trained range, and -nothing turns on by itself inside it. Pure functions - no GPU, no downloads, no prompts. - - python -m unittest tools.test_setup_rope -""" -from __future__ import annotations - -import sys -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -class DerivedFactor(unittest.TestCase): - """The formula itself: max(1.0, final / trained).""" - - def test_the_task_table(self): - self.assertEqual(setup.derived_factor(131072), 1.0) # below the trained range: clamped at 1 - self.assertEqual(setup.derived_factor(262144), 1.0) # exactly the trained range: 1 - self.assertEqual(setup.derived_factor(393216), 1.5) # 384K - self.assertEqual(setup.derived_factor(524288), 2.0) # 512K - - def test_free_form_contexts_get_the_exact_ratio(self): - # /262144 = /2**18 is exact in binary floating point, so no dust - self.assertEqual(setup.derived_factor(600000), 600000 / 262144) - self.assertGreater(setup.derived_factor(600000), 2.0) - - def test_the_clamp_is_what_keeps_128k_at_one(self): - self.assertEqual(setup.derived_factor(131072), 1.0) # NOT the raw 0.5 - - -class ResolveRope(unittest.TestCase): - # ---- the automatic flow the docs promise (an omitted flag, --yes or the interactive default) - def test_omitted_384k_gets_yarn_and_1_5(self): - self.assertEqual(setup.resolve_rope(393216, None, None), ("yarn", 1.5)) - - def test_omitted_512k_gets_yarn_and_2(self): - self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) - - def test_deterministic_for_yes(self): - # --yes never prompts, so the resolution must be a pure function of its inputs - for _ in range(3): - self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) - - def test_omitted_method_with_an_explicit_factor(self): - # --rope-scale alone still expresses the intent to extend: the method defaults, the factor is kept - self.assertEqual(setup.resolve_rope(393216, None, 1.8), ("yarn", 1.8)) - - # ---- explicit selections are respected, verbatim - def test_explicit_method_gets_the_derived_factor(self): - self.assertEqual(setup.resolve_rope(524288, "linear", None), ("linear", 2.0)) - - def test_explicit_method_and_factor_are_kept_verbatim(self): - self.assertEqual(setup.resolve_rope(393216, "linear", 2.0), ("linear", 2.0)) - self.assertEqual(setup.resolve_rope(524288, "yarn", 1.5), ("yarn", 1.5)) - - def test_an_explicit_override_survives_a_context_reduction(self): - # §4: the RAM check reduced the final context to 128K - a user-supplied factor is NOT recalculated - self.assertEqual(setup.resolve_rope(131072, "yarn", 2.0), ("yarn", 2.0)) - self.assertEqual(setup.resolve_rope(131072, "linear", 1.75), ("linear", 1.75)) - - # ---- an explicit none past the trained range is refused with an explanation, not overridden - def test_explicit_none_past_trained_is_refused(self): - with self.assertRaises(ValueError) as cm: - setup.resolve_rope(524288, "none", None) - self.assertIn("262144", str(cm.exception)) - self.assertIn("yarn", str(cm.exception)) # the message names the way out - - def test_explicit_none_within_trained_is_the_stock_model(self): - self.assertEqual(setup.resolve_rope(131072, "none", None), (None, None)) - - # ---- inside the trained range nothing turns on by itself; a chosen method gets factor 1 - def test_omitted_within_trained_adds_nothing(self): - self.assertEqual(setup.resolve_rope(262144, None, None), (None, None)) - self.assertEqual(setup.resolve_rope(131072, None, None), (None, None)) - - def test_a_scale_alone_within_trained_is_rejected(self): - with self.assertRaises(ValueError): - setup.resolve_rope(131072, None, 2.0) - - def test_a_chosen_method_within_trained_gets_factor_1(self): - # no more unconditional factor 2: 1 = the trained angles, no automatic expansion - self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 1.0)) - self.assertEqual(setup.resolve_rope(262144, "linear", None), ("linear", 1.0)) - - # ---- §4 coordination: the RAM reduction lands BEFORE the rope config, so the factor matches the - # context actually served - the 512K-on-IQ3_S-with-under-90-GB case from the task, end to end - def test_512k_on_a_small_ram_machine_resolves_to_128k_factor_1(self): - # asked 524288 with --rope-scaling yarn and no factor; the RAM check brings the final context to 131072 - self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 1.0)) - - def test_no_reduction_384k_and_512k_resolve_as_documented(self): - self.assertEqual(setup.resolve_rope(393216, "yarn", None), ("yarn", 1.5)) - self.assertEqual(setup.resolve_rope(524288, "yarn", None), ("yarn", 2.0)) - - # ---- the short-context item's own table: no factor-2 fallback inside the trained window, for either - # method, with the explicit override column kept verbatim - def test_the_short_context_table(self): - cases = [ - (131072, None, "yarn", 1.0), # --context 131072 --rope-scaling yarn - (262144, None, "yarn", 1.0), # --context 262144 --rope-scaling yarn - (393216, None, "yarn", 1.5), - (524288, None, "yarn", 2.0), - (131072, 2.0, "yarn", 2.0), # --rope-scale 2 is kept inside the window - ] - for ctx, scale, method, want in cases: - self.assertEqual(setup.resolve_rope(ctx, method, scale), (method, want), f"ctx {ctx}") - - def test_linear_gets_the_same_rule_as_yarn(self): - # the old fallback applied to both methods, so the fix must too - self.assertEqual(setup.resolve_rope(131072, "linear", None), ("linear", 1.0)) - self.assertEqual(setup.resolve_rope(393216, "linear", None), ("linear", 1.5)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_shard_check.py b/tools/test_setup_shard_check.py deleted file mode 100644 index d502bda..0000000 --- a/tools/test_setup_shard_check.py +++ /dev/null @@ -1,54 +0,0 @@ -"""setup.check_shards: a metadata-only GGUF shard that ends at its header (no alignment padding, #2346) is whole; -a shard whose tensor data runs past its end is still refused.""" -import struct -import sys -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -def _str(s): - b = s.encode() - return struct.pack(" bytes: - return b"\x7fELF....tail_role_token=0 vram_elastic=0 engine=" + version.encode() + b"\n...." if version else b"old binary" - - -class StaleBinary(unittest.TestCase): - def test_reads_the_compiled_in_version(self): - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "source_version", lambda: "0.1.43"): - exe = Path(d) / "strata" - exe.write_bytes(binary("0.1.42")) - self.assertEqual(setup.binary_engine_version(exe), "0.1.42") - self.assertTrue(setup.stale_binary(exe)) - exe.write_bytes(binary("0.1.43")) - self.assertFalse(setup.stale_binary(exe)) - - def test_four_part_version_and_unknowns(self): - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "source_version", lambda: "0.1.43.1"): - exe = Path(d) / "strata" - exe.write_bytes(binary("0.1.43.1")) - self.assertFalse(setup.stale_binary(exe)) - exe.write_bytes(binary("0.1.43")) - self.assertTrue(setup.stale_binary(exe)) - exe.write_bytes(binary(None)) # a binary that carries no version: not judged - self.assertFalse(setup.stale_binary(exe)) - self.assertFalse(setup.stale_binary(Path(d) / "missing")) - - -class BuildEngineStamp(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - self.eng = self.root / "engine" - self.eng.mkdir() - (self.eng / setup.EXE).write_bytes(binary("0.1.42")) - self.old_stamp = {"source": "local", "version": "0.1.42", "archs": [86], "vision": "none", - "cuda_dirs": [], "src": "oldhash", "vision_src": None} - (self.eng / "BUILD.json").write_text(json.dumps(self.old_stamp)) - self.built = binary("0.1.43") # what the fake compile leaves in the build folder - self.compiles = 0 - patches = [mock.patch.object(setup, "ROOT", self.root), - mock.patch.object(setup, "source_hash", lambda parts: "newhash"), - mock.patch.object(setup, "source_version", lambda: "0.1.43"), - mock.patch.object(setup, "install_build_tools", lambda gpu, yes: ("nvcc", None)), - mock.patch.object(setup, "toolkit_root_defs", lambda nvcc: []), - mock.patch.object(setup, "host_compiler_defs", lambda cuda: []), - mock.patch.object(setup, "engine_defs", lambda archs, tk=13: []), - mock.patch.object(setup, "isa_floor_defs", lambda *a: []), - mock.patch.object(setup, "cpu_floor", lambda avx2: ""), - mock.patch.object(setup, "cpu_info", lambda: ("cpu", True)), - mock.patch.object(setup, "cmake_build", self.fake_build), - mock.patch.object(setup, "say", lambda *a, **k: None), - mock.patch.object(setup, "ok", lambda *a, **k: None)] - for p in patches: - p.start() - self.addCleanup(p.stop) - - def fake_build(self, src, bdir, target, defs, vcvars, bat): - self.compiles += 1 - self.defs = list(defs) - bdir.mkdir(parents=True, exist_ok=True) - (bdir / setup.EXE).write_bytes(self.built) - - def stamp(self): - return json.loads((self.eng / "BUILD.json").read_text()) - - def test_a_good_build_is_stamped(self): - setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) - self.assertEqual(self.compiles, 1) - self.assertEqual(self.stamp()["src"], "newhash") - self.assertEqual(self.stamp()["version"], "0.1.43") - self.assertEqual((self.eng / setup.EXE).read_bytes(), self.built) - - def test_the_q6k_expert_kernels_are_pinned_on(self): - """PR #2515: a build/ folder first configured while STRATA_Q6K_EXPERTS defaulted to OFF keeps it in CMakeCache.txt; - the configure line names it, so Qwen3.6 UD-Q4_K_XL (Q4_K gate/up, Q6_K down) still loads.""" - setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) - self.assertIn("-DSTRATA_Q6K_EXPERTS=ON", self.defs) - self.assertNotIn("-DSTRATA_Q6K_EXPERTS=OFF", self.defs) - self.assertIn("-DSTRATA_MMQ_KQUANTS=ON", self.defs) # flipped OFF -> ON in the same commit (465cd61d) - - def test_a_build_that_leaves_the_old_binary_is_not_stamped_or_installed(self): - self.built = binary("0.1.42") # the build "succeeded" without producing the new engine - with self.assertRaises(SystemExit): - setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) - self.assertEqual(self.stamp(), self.old_stamp) # still the old hash: the next update compiles again - self.assertEqual((self.eng / setup.EXE).read_bytes(), binary("0.1.42")) - - def test_a_poisoned_stamp_is_compiled_again(self): - """The state #2054 found: the new source hash and version in BUILD.json, the old binary beside it.""" - (self.eng / "BUILD.json").write_text(json.dumps({**self.old_stamp, "version": "0.1.43", "src": "newhash"})) - setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) - self.assertEqual(self.compiles, 1) - self.assertEqual((self.eng / setup.EXE).read_bytes(), self.built) - - def test_a_healthy_install_is_left_alone(self): - (self.eng / setup.EXE).write_bytes(binary("0.1.43")) - (self.eng / "BUILD.json").write_text(json.dumps({**self.old_stamp, "version": "0.1.43", "src": "newhash"})) - setup.build_engine(GPU, "none", True, Path("llama"), toolkit=13) - self.assertEqual(self.compiles, 0) - - -class UpdateInstalledEngine(unittest.TestCase): - def test_a_poisoned_stamp_makes_the_update_compile(self): - with tempfile.TemporaryDirectory() as d: - root = Path(d) - eng = root / "engine" - eng.mkdir() - (eng / setup.EXE).write_bytes(binary("0.1.42")) - (eng / "BUILD.json").write_text(json.dumps({"source": "local", "version": "0.1.43", "archs": [86], - "vision": "none", "src": "newhash"})) - built = [] - with mock.patch.object(setup, "ROOT", root), \ - mock.patch.object(setup, "source_hash", lambda parts: "newhash"), \ - mock.patch.object(setup, "source_version", lambda: "0.1.43"), \ - mock.patch.object(setup, "update_engine_gpu", lambda tk: dict(GPU)), \ - mock.patch.object(setup, "get_llama_cpp", lambda: Path("llama")), \ - mock.patch.object(setup, "build_engine", lambda *a, **k: built.append(a)), \ - mock.patch.object(setup, "say", lambda *a, **k: None): - setup.update_installed_engine("http://x", 13) - self.assertEqual(len(built), 1) - built.clear() - (eng / setup.EXE).write_bytes(binary("0.1.43")) - setup.update_installed_engine("http://x", 13) - self.assertEqual(built, []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_start_gpus_amd.py b/tools/test_setup_start_gpus_amd.py deleted file mode 100644 index d428fe8..0000000 --- a/tools/test_setup_start_gpus_amd.py +++ /dev/null @@ -1,40 +0,0 @@ -"""#1594: --gpus when starting an installed model on a PC with AMD cards and no NVIDIA ones names the AMD cards (as -setup lists them) instead of failing for want of an NVIDIA GPU. - - python -m unittest tools.test_setup_start_gpus_amd -v -""" -import sys -import unittest -from pathlib import Path -from unittest import mock - -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -import setup # noqa: E402 - - -def amd(index, arch="gfx1201"): - return {"index": index, "name": f"Radeon {index}", "arch": arch, "vram_gb": 32.0} - - -class StartGpusAmd(unittest.TestCase): - def run_start_gpus(self, text, cards, nvidia=()): - with mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "gpus", return_value=list(nvidia)), \ - mock.patch.object(setup, "amd_gpus", return_value=cards): - return setup.start_gpus(text) - - def test_amd_numbers_are_taken_as_setup_lists_them(self): - self.assertEqual(self.run_start_gpus("1,0", [amd(0), amd(1)]), [1, 0]) - - def test_all_still_means_every_supported_amd_card(self): - self.assertEqual(sorted(self.run_start_gpus("all", [amd(0), amd(1)])), [0, 1]) - - def test_a_card_that_cannot_be_used_is_named(self): - with self.assertRaises(SystemExit): - self.run_start_gpus("1,0", [amd(0), amd(1, "gfx1010")]) - - def test_nothing_named_is_none(self): - self.assertIsNone(self.run_start_gpus("", [amd(0)])) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_strix_halo.py b/tools/test_setup_strix_halo.py deleted file mode 100644 index b6dcd36..0000000 --- a/tools/test_setup_strix_halo.py +++ /dev/null @@ -1,561 +0,0 @@ -"""Tests for setup.py's recognition of AMD Strix Halo (Ryzen AI Max, Radeon 8060S / 8050S / 8040S, gfx1151): the exact -arch check (never a prefix: gfx1150 / gfx1152 are other chips), the PCI ids and marketing names, the unified-memory -sizing, which card setup picks beside a discrete one, and the Windows engine zip (a zip without gfx1151 code is never used). - -The Linux fixture is Aurora's real answer (the maintainers' Strix Halo box, read-only): - KFD node 1: gfx_target_version 110501, simd_count 80, vendor_id 4098, device_id 5510 (0x1586), drm_render_minor 128 - /sys/class/drm/card1/device: vendor 0x1002, device 0x1586, mem_info_vram_total 2147483648 (a 2 GiB BIOS carve-out), - mem_info_gtt_total 120259084288 (112 GiB: ttm.pages_limit=29360128), no product_name - lspci -nn: c6:00.0 Display controller [0380]: AMD/ATI Strix Halo [Radeon Graphics / Radeon 8050S Graphics / - Radeon 8060S Graphics] [1002:1586] (rev c1); MemTotal 127098456 kB -The other chips are synthetic (their KFD gfx_target_version and pci.ids ids). No GPU, no ROCm, no downloads. - - python -m unittest tools.test_setup_strix_halo -""" -from __future__ import annotations - -import hashlib -import io -import json -import re -import sys -import tempfile -import unittest -import zipfile -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - -AURORA_RAM_GB = 127098456 * 1024 / 2 ** 30 # /proc/meminfo MemTotal on Aurora: 121.2 GiB -GIB = 1 << 30 - - -def fake_gpu(root: Path, node: int, ver: int, simd: int, minor: int, pci_id: int, vram: int, gtt: int, - product: str | None = None, card: int | None = None) -> None: - """One KFD GPU node + its drm device, laid out as the kernel does (see the module docstring).""" - n = root / "class/kfd/kfd/topology/nodes" / str(node) - n.mkdir(parents=True, exist_ok=True) - (n / "properties").write_text(f"cpu_cores_count 0\nsimd_count {simd}\nmem_banks_count 1\n" - f"gfx_target_version {ver}\nvendor_id 4098\ndevice_id {pci_id}\n" - f"drm_render_minor {minor}\nlocal_mem_size 0\n") - d = root / f"class/drm/renderD{minor}/device" - d.mkdir(parents=True, exist_ok=True) - for name, val in (("vendor", "0x1002"), ("device", f"0x{pci_id:04x}"), ("mem_info_vram_total", str(vram)), - ("mem_info_gtt_total", str(gtt))): - (d / name).write_text(val + "\n") - if product: - (d / "product_name").write_text(product + "\n") - if card is not None: # /sys/class/drm/card/device (what amd_pci_devices reads) - c = root / f"class/drm/card{card}/device" - c.mkdir(parents=True, exist_ok=True) - for name in ("vendor", "device", "mem_info_vram_total", "mem_info_gtt_total"): - (c / name).write_text((d / name).read_text()) - - -def cpu_node(root: Path, node: int = 0) -> None: - n = root / "class/kfd/kfd/topology/nodes" / str(node) - n.mkdir(parents=True, exist_ok=True) - (n / "properties").write_text("cpu_cores_count 32\nsimd_count 0\ngfx_target_version 0\nvendor_id 0\ndevice_id 0\n") - - -class LinuxBase(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = Path(self.tmp.name) - self.win = setup.WIN - setup.WIN = False - p = mock.patch.object(setup, "ram_gb", return_value=AURORA_RAM_GB) - p.start() - self.addCleanup(p.stop) - - def tearDown(self): - setup.WIN = self.win - self.tmp.cleanup() - - def aurora(self, node=1, minor=128, card=1): - fake_gpu(self.root, node, 110501, 80, minor, 0x1586, 2 * GIB, 120259084288, None, card) - - -class ExactArch(unittest.TestCase): - def test_gfx1151_is_exact(self): - self.assertTrue(setup.gfx_arch_is("gfx1151", "gfx1151")) - self.assertTrue(setup.gfx_arch_is("gfx1151:sramecc-:xnack-", "gfx1151")) # gcnArchName - for other in ("gfx1150", "gfx1152", "gfx115", "gfx11510", "gfx1103", "gfx1100", "gfx1201", "gfx1030", "", None): - self.assertFalse(setup.gfx_arch_is(other, "gfx1151"), other) - self.assertFalse(setup.is_strix_halo({"arch": other}), other) - self.assertFalse(setup.gfx_arch_is("gfx1151", "gfx115")) # no prefix match either way - self.assertFalse(setup.is_strix_halo({})) - - def test_matches_the_engines_header(self): - """include/strata/kernels/gfx_arch.hpp is the reference: gfx1151 has the WMMA kernels and the gfx1151 defaults; - gfx1103 (Radeon 780M/760M, 0.1.44) shares the gfx11 WMMA kernels; gfx1152 is outside the list.""" - hpp = (ROOT / "include/strata/kernels/gfx_arch.hpp").read_text(encoding="utf-8") - wmma = re.search(r"gfx_arch_is_gfx11_wmma.*?\n}", hpp, re.S).group(0) - listed = set(re.findall(r'"(gfx\d+)"', wmma)) - self.assertIn("gfx1151", listed) - self.assertIn("gfx1103", listed) # 0.1.44: the 780M runs the gfx11 WMMA kernels (decode x1.53) - self.assertNotIn("gfx1152", listed) - self.assertIn('gfx_arch_is(gcn, "gfx1151")', hpp) - self.assertEqual(setup.STRIX_HALO_ARCH, "gfx1151") - - def test_arch_lists(self): - self.assertIn("gfx1151", setup.AMD_ARCHS) - self.assertIn("gfx1151", setup.ROCM_INDEXES) - self.assertTrue(setup.ROCM_INDEXES["gfx1151"].endswith("/gfx1151/")) - for a in ("gfx1150", "gfx1152", "gfx1103"): # never supported by accident - self.assertNotIn(a, setup.AMD_ARCHS) - self.assertIn("docs/STRIX_HALO.md", setup.AMD_CARDS) - -# gfx1151 arch defaults that setup does not copy to gfx1103 / gfx1150: HCD_EXACT copies the gfx1151 hipBLASLt table's -# solutions, TOPK_REG_MIN_BLOCKS (#1943: the top-k register-kernel line at 4096 blocks, the crossover with the -# cooperative scan) was measured on gfx1151 only -_NOT_COPIED = ("STRATA_HCD_EXACT", "STRATA_TOPK_REG_MIN_BLOCKS") - - - -class Gfx1103Switches(unittest.TestCase): - def test_is_the_gfx1151_defaults_less_hcd_exact(self): - """GFX1103_SWITCHES is the gfx1151 arch-default set (src/core/arch_defaults.cpp) minus STRATA_HCD_EXACT, which - copies the gfx1151 hipBLASLt table's solutions 1176 / 1177 and so does not apply beside a gfx1103 table. The - engine keeps gfx1103 out of its own arch defaults, so setup writes this set.""" - src = (ROOT / "src/core/arch_defaults.cpp").read_text(encoding="utf-8") - tail = src.split("gfx_arch_is_gfx1151(gcn_arch)) return t;", 1)[1] - block = tail.rsplit("t = {", 1)[1].split("};", 1)[0] # the gfx1151 switch table - gfx1151 = dict(re.findall(r'\{"(STRATA_[A-Z0-9_]+)",\s*"([^"]+)"\}', block)) - self.assertIn("STRATA_HCD_EXACT", gfx1151) # the parse found the gfx1151 block - self.assertEqual(setup.GFX1103_SWITCHES, - {k: v for k, v in gfx1151.items() if k not in _NOT_COPIED}) - self.assertNotIn("STRATA_HCD_EXACT", setup.GFX1103_SWITCHES) - for k in setup.GFX1103_SWITCHES: # setup's own: a re-run refreshes them - self.assertIn(k, setup.SETUP_ENV) - - -class Gfx1150Switches(unittest.TestCase): - def test_is_the_gfx1151_defaults_less_hcd_exact(self): - """GFX1150_SWITCHES is the gfx1151 arch-default set (src/core/arch_defaults.cpp) minus STRATA_HCD_EXACT, which - copies the gfx1151 hipBLASLt table's solutions 1176 / 1177 and so does not apply beside a gfx1150 table. The - engine keeps gfx1150 out of its own arch defaults (src/core/arch_defaults_test.cpp), so setup writes this set.""" - src = (ROOT / "src/core/arch_defaults.cpp").read_text(encoding="utf-8") - tail = src.split("gfx_arch_is_gfx1151(gcn_arch)) return t;", 1)[1] - block = tail.rsplit("t = {", 1)[1].split("};", 1)[0] # the gfx1151 switch table - gfx1151 = dict(re.findall(r'\{"(STRATA_[A-Z0-9_]+)",\s*"([^"]+)"\}', block)) - self.assertIn("STRATA_HCD_EXACT", gfx1151) # the parse found the gfx1151 block - self.assertEqual(setup.GFX1150_SWITCHES, - {k: v for k, v in gfx1151.items() if k not in _NOT_COPIED}) - self.assertNotIn("STRATA_HCD_EXACT", setup.GFX1150_SWITCHES) - for k in setup.GFX1150_SWITCHES: # setup's own: a re-run refreshes them - self.assertIn(k, setup.SETUP_ENV) - self.assertIn('arch_default_env("gfx1150").empty()', - (ROOT / "src/core/arch_defaults_test.cpp").read_text(encoding="utf-8")) - - -class PciIds(unittest.TestCase): - def test_strix_halo_id(self): - # pci.ids: one id for every Strix Halo part (8060S, 8050S, 8040S share it; they differ by CU count) - self.assertEqual(setup.STRIX_HALO_PCI_IDS, {0x1586}) - self.assertEqual(setup.AMD_IGPU_PCI[0x1586], "gfx1151") - - def test_other_igpus_are_not_strix_halo(self): - for did, arch in ((0x150E, "gfx1150"), (0x1114, "gfx1152"), (0x1902, "gfx1152"), (0x15BF, "gfx1103"), - (0x15C8, "gfx1103"), (0x164F, "gfx1103"), (0x1900, "gfx1103"), (0x1901, "gfx1103")): - self.assertEqual(setup.AMD_IGPU_PCI[did], arch) - self.assertNotIn(did, setup.STRIX_HALO_PCI_IDS) - self.assertEqual([a for a in setup.AMD_IGPU_PCI.values() if a == "gfx1151"], ["gfx1151"]) - - def test_windows_id_then_name(self): - f = setup.win_amd_arch - self.assertEqual(f(0x1586, ""), "gfx1151") - self.assertEqual(f(0x1586, "AMD Radeon(TM) Graphics"), "gfx1151") # the generic name Windows may show - for name in ("AMD Radeon(TM) 8060S Graphics", "AMD Radeon(TM) 8050S Graphics", "AMD Radeon(TM) 8040S Graphics"): - self.assertEqual(f(None, name), "gfx1151", name) # an id we do not know: by name - self.assertEqual(f(0x150E, "AMD Radeon(TM) 890M Graphics"), "gfx1150") - self.assertEqual(f(None, "AMD Radeon(TM) 880M Graphics"), "gfx1150") - self.assertEqual(f(None, "AMD Radeon(TM) 860M Graphics"), "gfx1152") - self.assertEqual(f(None, "AMD Radeon(TM) 840M Graphics"), "gfx1152") - self.assertEqual(f(0x15BF, "AMD Radeon(TM) 780M Graphics"), "gfx1103") - self.assertEqual(f(None, "AMD Radeon(TM) 760M Graphics"), "gfx1103") - # the discrete cards keep their own arch - self.assertEqual(f(0x744C, "AMD Radeon RX 7900 XTX"), "gfx1100") - self.assertEqual(f(None, "AMD Radeon RX 7900 XTX"), "gfx1100") - self.assertEqual(f(0x7550, "AMD Radeon RX 9070 XT"), "gfx1201") - self.assertEqual(f(None, "AMD Radeon RX 7600M XT"), "gfx1102") # not the 780M rule - self.assertEqual(f(None, "AMD Radeon RX 6800M"), "") - - -class AuroraFixture(LinuxBase): - def test_aurora(self): - cpu_node(self.root, 0) - self.aurora() - g = setup.amd_gpus(str(self.root)) - self.assertEqual(len(g), 1) - g = g[0] - self.assertEqual((g["index"], g["arch"], g["pci_id"]), (0, "gfx1151", 0x1586)) - self.assertEqual(g["name"], "AMD Radeon 8060S (Ryzen AI Max, Strix Halo, gfx1151)") # 80 SIMDs = 40 CUs - self.assertIsNone(setup.amd_problem(g)) - self.assertTrue(g["uma"] and setup.is_strix_halo(g)) - self.assertAlmostEqual(g["dedicated_gb"], 2.0) # the BIOS carve-out - self.assertAlmostEqual(g["shared_gb"], 112.0) # GTT, below RAM - 6 - self.assertAlmostEqual(g["vram_gb"], 114.0) - self.assertAlmostEqual(setup.low_ram_vram(g), 2.0) # the shared pool is the RAM itself - self.assertIn("unified memory", setup.amd_mem_text(g)) - - def test_marketing_name_by_cu_count(self): - for simd, name in ((80, "8060S"), (64, "8050S"), (32, "8040S")): - root = Path(tempfile.mkdtemp(dir=self.root)) - fake_gpu(root, 0, 110501, simd, 128, 0x1586, 2 * GIB, 112 * GIB) - g = setup.amd_gpus(str(root))[0] - self.assertIn(name, g["name"]) - self.assertEqual(g["arch"], "gfx1151") - root = Path(tempfile.mkdtemp(dir=self.root)) - fake_gpu(root, 0, 110501, 48, 128, 0x1586, 2 * GIB, 112 * GIB) # an unknown CU count - self.assertEqual(setup.amd_gpus(str(root))[0]["name"], setup.AMD_NAMES["gfx1151"]) - - def test_name_from_sysfs_is_kept(self): - fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 2 * GIB, 120259084288, "AMD Radeon 8060S") - self.assertEqual(setup.amd_gpus(str(self.root))[0]["name"], "AMD Radeon 8060S") - - def test_pci_scan(self): - self.aurora() - d = setup.amd_pci_devices(str(self.root)) - self.assertEqual([(x["pci_id"], x["arch"]) for x in d], [(0x1586, "gfx1151")]) - self.assertAlmostEqual(d[0]["gtt_gb"], 112.0) - self.assertIn(d[0]["pci_id"], setup.STRIX_HALO_PCI_IDS) - - def test_gtt_never_exceeds_the_ram(self): - fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 512 << 20, 200 * GIB) # a bogus 200 GiB GTT - g = setup.amd_gpus(str(self.root))[0] - self.assertAlmostEqual(g["shared_gb"], AURORA_RAM_GB - setup.UMA_OS_LEFT_GB) - - def test_no_gtt_file_means_half_the_ram(self): - fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 2 * GIB, 0) - g = setup.amd_gpus(str(self.root))[0] - self.assertAlmostEqual(g["shared_gb"], AURORA_RAM_GB / 2) - - def test_big_carve_out(self): - fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 96 * GIB, 24 * GIB) # 96 GB carve-out, 32 GB left - with mock.patch.object(setup, "ram_gb", return_value=30.0): - g = setup.amd_gpus(str(self.root))[0] - self.assertAlmostEqual(g["dedicated_gb"], 96.0) - self.assertAlmostEqual(g["vram_gb"], 96.0 + 24.0) - self.assertAlmostEqual(setup.low_ram_vram(g), 96.0) # that memory is extra to the RAM - notes = setup.strix_halo_notes(g, 30.0) - self.assertTrue(any(n.startswith("!") and "carve-out" in n for n in notes)) - - def test_small_carve_out(self): - fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 512 << 20, 60 * GIB) # 512 MB carve-out - g = setup.amd_gpus(str(self.root))[0] - self.assertAlmostEqual(g["dedicated_gb"], 0.5) - - -class OtherChips(LinuxBase): - """Synthetic KFD nodes: gfx_target_version as the kernel reports it.""" - - def one(self, ver, pci, vram, gtt=0): - root = Path(tempfile.mkdtemp(dir=self.root)) - fake_gpu(root, 0, ver, 64, 128, pci, vram, gtt) - return setup.amd_gpus(str(root))[0] - - def test_strix_point(self): - g = self.one(110500, 0x150E, 512 << 20, 60 * GIB) - self.assertEqual(g["arch"], "gfx1150") - self.assertFalse(setup.is_strix_halo(g) or g.get("uma")) - self.assertIn("gfx1150", setup.amd_problem(g)) - self.assertIn("not Strix Halo", setup.amd_problem(g)) - self.assertIn("890M", g["name"]) - - def test_krackan(self): - g = self.one(110502, 0x1114, 512 << 20, 30 * GIB) - self.assertEqual(g["arch"], "gfx1152") - self.assertFalse(g.get("uma")) - self.assertIn("gfx1152", setup.amd_problem(g)) - self.assertIn("860M", g["name"]) - - def test_phoenix_hawk_point(self): - g = self.one(110003, 0x15BF, 512 << 20, 30 * GIB) - self.assertEqual(g["arch"], "gfx1103") - self.assertFalse(g.get("uma")) - self.assertIn("gfx1103", setup.amd_problem(g)) - self.assertIn("780M", g["name"]) - - def test_discrete_cards(self): - for ver, arch, pci, vram in ((110000, "gfx1100", 0x744C, 24), (110001, "gfx1101", 0x747E, 16), - (110002, "gfx1102", 0x7480, 8), (120001, "gfx1201", 0x7550, 16), - (100300, "gfx1030", 0x73BF, 16)): - g = self.one(ver, pci, vram * GIB, 32 * GIB) - self.assertEqual(g["arch"], arch) - self.assertFalse(g.get("uma"), arch) - self.assertFalse(setup.is_strix_halo(g), arch) - self.assertAlmostEqual(g["vram_gb"], vram) # a card's VRAM is not changed - self.assertEqual(setup.low_ram_vram(g), vram) - self.assertIsNone(setup.amd_problem(g), arch) - - -class DualGpu(LinuxBase): - def test_strix_halo_with_a_discrete_card(self): - cpu_node(self.root, 0) - fake_gpu(self.root, 1, 110501, 80, 128, 0x1586, 2 * GIB, 112 * GIB, None, 1) - fake_gpu(self.root, 2, 110000, 192, 129, 0x744C, 24 * GIB, 16 * GIB, "AMD Radeon RX 7900 XTX", 2) - g = setup.amd_gpus(str(self.root)) - self.assertEqual([(x["index"], x["arch"]) for x in g], [(0, "gfx1151"), (1, "gfx1100")]) - self.assertTrue(g[0]["uma"] and not g[1].get("uma")) - self.assertTrue(g[0]["vram_gb"] > g[1]["vram_gb"]) # 114 GB of unified memory vs 24 - self.assertEqual(min(g, key=setup.amd_rank)["arch"], "gfx1100") # the card with its own memory - self.assertEqual([x["arch"] for x in setup.amd_parse_gpus("all", g)], ["gfx1100", "gfx1151"]) - self.assertEqual([x["arch"] for x in setup.amd_parse_gpus("0,1", g)], ["gfx1151", "gfx1100"]) - self.assertEqual(sorted(a for a in {x["arch"] for x in g}), ["gfx1100", "gfx1151"]) # compiled for both if split - # two TheRock families: a split needs a system ROCm (rocm_root says so); one card does not - self.assertNotEqual(setup.ROCM_INDEXES["gfx1100"], setup.ROCM_INDEXES["gfx1151"]) - - def test_strix_halo_with_strix_point_is_impossible_but_not_confused(self): - cpu_node(self.root, 0) - fake_gpu(self.root, 1, 110500, 32, 128, 0x150E, 512 << 20, 30 * GIB) - fake_gpu(self.root, 2, 110501, 80, 129, 0x1586, 2 * GIB, 112 * GIB) - g = setup.amd_gpus(str(self.root)) - self.assertEqual([x["arch"] for x in g], ["gfx1150", "gfx1151"]) - self.assertEqual([bool(setup.amd_problem(x)) for x in g], [True, False]) - self.assertEqual([bool(x.get("uma")) for x in g], [False, True]) - usable = [x for x in g if setup.amd_problem(x) is None] - self.assertEqual(min(usable, key=setup.amd_rank)["index"], 1) - - def test_two_strix_halo_ranked_by_index(self): - fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 2 * GIB, 112 * GIB) - fake_gpu(self.root, 1, 110501, 80, 129, 0x1586, 2 * GIB, 112 * GIB) - g = setup.amd_gpus(str(self.root)) - self.assertEqual(min(g, key=setup.amd_rank)["index"], 0) - - -class WindowsDetection(unittest.TestCase): - def setUp(self): - self.win = setup.WIN - setup.WIN = True - p = mock.patch.object(setup, "ram_gb", return_value=96.0) - p.start() - self.addCleanup(p.stop) - self.addCleanup(lambda: setattr(setup, "WIN", self.win)) - - def adapters(self): - return ([{"name": "AMD Radeon(TM) 8060S Graphics", "pnp": r"PCI\VEN_1002&DEV_1586&SUBSYS_1C3E1D05&REV_C1\4&2", - "ram": 4294967295}], - [{"DriverDesc": "AMD Radeon(TM) 8060S Graphics", - "MatchingDeviceId": r"PCI\VEN_1002&DEV_1586&REV_C1", "HardwareInformation.qwMemorySize": 4 * GIB, - "DriverVersion": "32.0.21013.1000"}]) - - def test_strix_halo(self): - ad, reg = self.adapters() - g = setup.amd_gpus_windows(ad, reg) - self.assertEqual(len(g), 1) - self.assertEqual((g[0]["arch"], g[0]["pci_id"]), ("gfx1151", 0x1586)) - self.assertIsNone(setup.amd_problem(g[0])) - self.assertTrue(g[0]["uma"]) - self.assertAlmostEqual(g[0]["dedicated_gb"], 4.0) # the registry's carve-out - self.assertAlmostEqual(g[0]["shared_gb"], 48.0) # Windows: half the RAM - self.assertAlmostEqual(g[0]["vram_gb"], 52.0) - self.assertEqual(g[0]["name"], "AMD Radeon(TM) 8060S Graphics") - - def test_strix_halo_and_a_7900_xtx(self): - ad, reg = self.adapters() - ad.append({"name": "AMD Radeon RX 7900 XTX", "pnp": r"PCI\VEN_1002&DEV_744C&SUBSYS_1&REV_C8\4&3", "ram": 0}) - reg.append({"DriverDesc": "AMD Radeon RX 7900 XTX", "MatchingDeviceId": r"PCI\VEN_1002&DEV_744C&REV_C8", - "HardwareInformation.qwMemorySize": 24 * GIB, "DriverVersion": "32.0.21013.1000"}) - g = setup.amd_gpus_windows(ad, reg) - self.assertEqual([x["arch"] for x in g], ["gfx1151", "gfx1100"]) - self.assertTrue(g[0]["uma"] and not g[1].get("uma")) - self.assertEqual(min(g, key=setup.amd_rank)["arch"], "gfx1100") - - def test_other_integrated_radeons(self): - for did, name, arch in ((0x150E, "AMD Radeon(TM) 890M Graphics", "gfx1150"), - (0x1114, "AMD Radeon(TM) 860M Graphics", "gfx1152"), - (0x15BF, "AMD Radeon(TM) 780M Graphics", "gfx1103")): - ad = [{"name": name, "pnp": rf"PCI\VEN_1002&DEV_{did:04X}&REV_C1\4&2", "ram": 512 << 20}] - g = setup.amd_gpus_windows(ad, [])[0] - self.assertEqual(g["arch"], arch) - self.assertFalse(g.get("uma")) - self.assertIsNotNone(setup.amd_problem(g)) - - def test_hip_listing_of_strix_halo(self): - """Once the HIP engine is installed the cards are numbered as HIP lists them; the carve-out still comes from the - registry, and an APU's HIP figure never lowers the GPU's memory.""" - ad, reg = self.adapters() - text = "device 0: AMD Radeon(TM) 8060S Graphics\n arch gfx1151, 64.0 GiB\ndevice 1: AMD Radeon RX 7900 XTX\n arch gfx1100, 24.0 GiB\n" - hip = setup.hip_devices(text=text) - self.assertEqual([x["arch"] for x in hip], ["gfx1151", "gfx1100"]) - with mock.patch.object(setup, "hip_devices", return_value=hip), \ - mock.patch.object(setup, "amd_gpus_windows", return_value=setup.amd_gpus_windows(ad, reg)): - g = setup.amd_gpus_win() - self.assertTrue(g[0]["uma"]) - self.assertAlmostEqual(g[0]["dedicated_gb"], 4.0) - self.assertGreaterEqual(g[0]["vram_gb"], 64.0) - self.assertFalse(g[1].get("uma")) - self.assertAlmostEqual(g[1]["vram_gb"], 24.0) - - -class WindowsZip(unittest.TestCase): - """get_prebuilt_hip never installs a zip with no code for the card; for a Strix Halo it says why and what to do.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.root = Path(self.tmp.name) - self.warnings: list[str] = [] - for p in (mock.patch.object(setup, "ROOT", self.root), mock.patch.object(setup, "warn", self.warnings.append), - mock.patch.object(setup, "say", lambda *a, **k: None), mock.patch.object(setup, "ok", lambda *a, **k: None), - mock.patch.object(setup, "download", self.fake_download), - mock.patch.object(setup, "engine_digest", self.fake_digest), - mock.patch.object(setup.urllib.request, "urlopen", lambda *a, **k: io.BytesIO(b"")), - mock.patch.object(setup, "hip_runtime_beside_exe", lambda eng: None)): - p.start() - self.addCleanup(p.stop) - self.archs = ["gfx1100", "gfx1101", "gfx1102", "gfx1200", "gfx1201", "gfx1030"] # the 0.1.39 zip - - def fake_download(self, url, dest, label=""): - with zipfile.ZipFile(dest, "w") as z: - z.writestr("BUILD.json", json.dumps({"source": "prebuilt", "backend": "hip", "platform": "windows-x64", - "version": ".".join(map(str, setup.MIN_ENGINE)), "archs": self.archs, "lib_dirs": []})) - z.writestr(setup.EXE, "x") - - - def fake_digest(self, asset, base): - """The size and SHA-256 of whatever the mocked download just wrote. - - The engine archive is checked against a published digest before it is unpacked, so a test that - mocks the download has to say what the hash is or it never reaches the part it is about. This - hashes the real bytes the fake download produced, so the check still runs. - """ - p = self.root / "engine" / asset - data = p.read_bytes() if p.exists() else b"" - return len(data), hashlib.sha256(data).hexdigest() - - def halo(self): - return {"index": 0, "name": setup.AMD_NAMES["gfx1151"], "vram_gb": 52.0, "arch": "gfx1151", "uma": True, - "dedicated_gb": 4.0, "shared_gb": 48.0, "vendor": "amd", "driver": "amd"} - - def test_zip_without_gfx1151_is_refused_with_the_reason(self): - self.assertIsNone(setup.get_prebuilt_hip("https://example.invalid/", self.halo())) - self.assertEqual(len(self.warnings), 1) - msg = self.warnings[0] - self.assertIn("no gfx1151 code", msg) - self.assertIn("docs/STRIX_HALO.md", msg) - self.assertIn("build_windows.bat", msg) - self.assertFalse((self.root / "engine" / "strata-windows-x64-hip.zip").exists()) # dropped - self.assertFalse((self.root / "engine" / setup.EXE).exists()) # nothing installed - - def test_zip_with_gfx1151_is_installed(self): - self.archs = self.archs + ["gfx1151"] - eng = setup.get_prebuilt_hip("https://example.invalid/", self.halo()) - self.assertEqual(eng, self.root / "engine") - self.assertEqual(self.warnings, []) - meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) - self.assertIn("gfx1151", meta["archs"]) - - def test_a_7900_xtx_still_takes_the_old_zip(self): - g = {"index": 0, "name": "x", "vram_gb": 24.0, "arch": "gfx1100", "vendor": "amd", "driver": "amd"} - self.assertIsNotNone(setup.get_prebuilt_hip("https://example.invalid/", g)) - - def test_windows_build_script_lists_gfx1151(self): - bat = (ROOT / "tools/hip/build_windows.bat").read_text(encoding="utf-8") - m = re.search(r'if not defined STRATA_HIP_ARCHS set "STRATA_HIP_ARCHS=([^"]+)"', bat) - self.assertIn("gfx1151", m.group(1).split(";")) - self.assertTrue({"gfx1100", "gfx1101", "gfx1102", "gfx1200", "gfx1201", "gfx1030"} <= set(m.group(1).split(";"))) - - -class Recommendation(unittest.TestCase): - def halo(self, carve=2.0): - return {"arch": "gfx1151", "uma": True, "dedicated_gb": carve, "shared_gb": 100.0, "vram_gb": carve + 100.0} - - def test_ud_iq4_xs_with_enough_memory(self): - self.assertEqual((setup.STRIX_HALO_FAMILY, setup.STRIX_HALO_MODEL), ("unsloth", "UD-IQ4_XS")) - self.assertIn(setup.STRIX_HALO_MODEL, setup.MODELS) - self.assertIn(setup.STRIX_HALO_FAMILY, setup.FAMILIES) - self.assertTrue(setup.strix_halo_recommends(self.halo(), AURORA_RAM_GB)) - self.assertTrue(setup.strix_halo_recommends(self.halo(), 128.0)) - self.assertTrue(setup.strix_halo_recommends(self.halo(32.0), 60.0)) # 32 GB carve-out + 60 GB RAM - self.assertFalse(setup.strix_halo_recommends(self.halo(), 62.0)) # a 64 GB box: no recommendation - self.assertFalse(setup.strix_halo_recommends(self.halo(), 30.0)) - self.assertFalse(setup.strix_halo_recommends({"arch": "gfx1100", "vram_gb": 24.0}, 256.0)) - self.assertFalse(setup.strix_halo_recommends({"arch": "gfx1150", "vram_gb": 0.5}, 256.0)) - - def test_the_recommended_model_is_a_regular_choice_on_amd(self): - m = setup.MODELS[setup.STRIX_HALO_MODEL] - self.assertFalse(m.get("nvidia_only")) - self.assertFalse(m.get("experimental")) - - def test_notes_are_recommendations(self): - win = setup.WIN - try: - setup.WIN = False - g = {**self.halo(), "shared_gb": 60.0, "vram_gb": 62.0} - notes = setup.strix_halo_notes(g, AURORA_RAM_GB) - joined = "\n".join(notes) - self.assertIn("docs/STRIX_HALO.md", joined) - self.assertIn("UD-IQ4_XS", joined) - self.assertTrue(any(n.startswith("!") and "ttm.pages_limit" in n for n in notes)) # a small GTT: a warning - self.assertIn("changes no host setting", joined) - big = {**self.halo(), "shared_gb": 112.0, "vram_gb": 114.0} - self.assertFalse(any(n.startswith("!") for n in setup.strix_halo_notes(big, AURORA_RAM_GB))) - finally: - setup.WIN = win - - def test_hipblaslt_table_for_gfx1151(self): - t = setup.hipblaslt_table("gfx1151", [], 100401) - self.assertIsNotNone(t) - self.assertEqual(t.name, "gfx1151-hipblaslt-100401.txt") - - -class LowRamUsesTheCarveOutOnly(unittest.TestCase): - def test_apu_memory_is_not_double_counted(self): - halo = {"arch": "gfx1151", "uma": True, "dedicated_gb": 2.0, "shared_gb": 112.0, "vram_gb": 114.0, "index": 0} - card = {"arch": "gfx1100", "vram_gb": 24.0, "index": 0} - self.assertEqual(setup.low_ram_vram(halo), 2.0) - self.assertEqual(setup.low_ram_vram(card), 24.0) - # a 32 GB-RAM Strix Halo: the smallest model is not "made to fit" by counting the GPU's shared memory as extra - self.assertFalse(setup.low_ram_fits("IQ1_M", 24.0, setup.low_ram_vram(halo))) - self.assertTrue(setup.low_ram_fits("IQ1_M", 24.0, 40.0)) # a 40 GB dedicated card does - - -class IgpuTextIsArchExact(unittest.TestCase): - """The owner's rule: setup never takes one AMD iGPU for another. gfx1103 (Radeon 780M / 760M) gets its own text, - never the Strix Halo (gfx1151) lines; gfx1151 keeps its.""" - - def gpu(self, arch, name): - return {"arch": arch, "name": name, "uma": True, "dedicated_gb": 2.0, "shared_gb": 30.0, "vram_gb": 32.0} - - def test_gfx1103_never_gets_strix_halo_text(self): - for win in (False, True): - with mock.patch.object(setup, "WIN", win): - text = chr(10).join(setup.igpu_notes(self.gpu("gfx1103", "AMD Radeon 780M Graphics"), 61.0)) - self.assertIn("gfx1103", text) - self.assertIn("STRATA_EXPERIMENTAL_GFX1103=1", text) - self.assertIn("RADEON_780M.md", text) - for bad in ("gfx1151", "Ryzen AI Max", "STRIX_HALO", "Recommended model"): - self.assertNotIn(bad, text) - self.assertNotIn("Strix Halo (gfx1151", text) - self.assertNotIn("compiled here for gfx1151", text) - - def test_gfx1151_keeps_strix_halo_text(self): - with mock.patch.object(setup, "WIN", False): - text = chr(10).join(setup.igpu_notes(self.gpu("gfx1151", "AMD Radeon 8060S"), 121.0)) - self.assertIn("Strix Halo (gfx1151, Ryzen AI Max)", text) - self.assertIn("compiled here for gfx1151", text) - self.assertIn("docs/STRIX_HALO.md", text) - self.assertNotIn("gfx1103", text) - - def test_other_chips_get_nothing(self): - for a in ("gfx1150", "gfx1152", "gfx1100", "gfx1201"): - self.assertEqual(setup.igpu_notes(self.gpu(a, "x"), 64.0), []) - - def test_no_strix_halo_model_recommendation_for_gfx1103(self): - g = self.gpu("gfx1103", "AMD Radeon 780M Graphics") - self.assertFalse(setup.strix_halo_recommends(g, 128.0)) - self.assertTrue(setup.strix_halo_recommends(self.gpu("gfx1151", "x"), 128.0)) - - def test_setup_prints_notes_through_the_exact_helper(self): - src = Path(setup.__file__).read_text(encoding="utf-8") - self.assertIn("igpu_notes(gpu, ram_gb())", src) - self.assertNotIn("strix_halo_notes(gpu, ram_gb())", src) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_sycl.py b/tools/test_setup_sycl.py deleted file mode 100644 index 1c993a6..0000000 --- a/tools/test_setup_sycl.py +++ /dev/null @@ -1,228 +0,0 @@ -"""Tests for setup.py --backend sycl, the experimental Intel Arc engine (sycl/, PR #423): it warns, stops with a clear -message on Windows, and on Linux hands the run to sycl/setup_intel.py without its --backend flag. The CUDA / HIP -paths never see it. No GPU, no network. - - python -m unittest tools.test_setup_sycl -""" -from __future__ import annotations - -import contextlib -import io -import re -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -def run(argv, win): - out = io.StringIO() - with mock.patch.object(setup, "WIN", win), mock.patch.object(setup.subprocess, "call", return_value=0) as call, \ - contextlib.redirect_stdout(out): - try: - rc = setup.sycl_setup(argv) - except SystemExit as e: - rc = ("exit", e.code) - return rc, out.getvalue(), call - - -class SyclBackend(unittest.TestCase): - def test_windows_stops_with_the_docs_pointer(self): - rc, out, call = run(["--backend", "sycl"], win=True) - self.assertEqual(rc, ("exit", 1)) - self.assertIn("supported since 0.1.40.2", out) - self.assertIn("docs/INTEL_ARC.md", out) - call.assert_not_called() - - def test_linux_hands_over_to_setup_intel_without_the_backend_flag(self): - rc, out, call = run(["--model", "IQ2_XS", "--backend", "sycl", "--port", "8085"], win=False) - self.assertEqual(rc, 0) - self.assertIn("supported since 0.1.40.2", out) - self.assertIn("built from source", out) - cmd = call.call_args[0][0] - self.assertTrue(cmd[1].endswith(str(Path("sycl") / "setup_intel.py"))) - self.assertEqual(cmd[2:], ["--model", "IQ2_XS", "--port", "8085"]) - - def test_backend_equals_form_is_dropped_too(self): - _, _, call = run(["--backend=sycl", "--check"], win=False) - self.assertEqual(call.call_args[0][0][2:], ["--check"]) - - def test_the_parser_accepts_sycl(self): - src = (ROOT / "setup.py").read_text(encoding="utf-8") - self.assertRegex(src, r'"--backend", choices=\["cuda", "hip", "sycl"\]') - - def test_setup_intel_finds_the_setup_functions_it_replaces(self): - """sycl/setup_intel.py swaps these steps; setup.py must still have them (it stops with a message otherwise).""" - src = (ROOT / "sycl" / "setup_intel.py").read_text(encoding="utf-8") - names = re.search(r'for name in \(([^)]*)\):', src).group(1) - for name in re.findall(r'"(\w+)"', names): - self.assertTrue(callable(getattr(setup, name, None)), name) - - def test_setup_intel_replacements_take_every_argument_of_the_function_they_replace(self): - """#870: setup.py grew write_run_script's fourth argument and the port's replacement still took three, so - setup died with a TypeError after the download. Every `S. = ` in setup_intel.py must accept - all the parameters of setup. (or take *args / **kwargs).""" - import ast - import inspect - tree = ast.parse((ROOT / "sycl" / "setup_intel.py").read_text(encoding="utf-8")) - defs = {n.name: n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)} - checked = 0 - for n in ast.walk(tree): - if not (isinstance(n, ast.Assign) and len(n.targets) == 1 and isinstance(n.targets[0], ast.Attribute) - and isinstance(n.targets[0].value, ast.Name) and n.targets[0].value.id == "S"): - continue - name = n.targets[0].attr - fn = n.value if isinstance(n.value, ast.Lambda) else defs.get(getattr(n.value, "id", "")) - orig = getattr(setup, name, None) - if fn is None or not callable(orig): - continue - a = fn.args - if a.vararg is not None and a.kwarg is not None: - checked += 1 - continue - have = {x.arg for x in a.posonlyargs + a.args + a.kwonlyargs} - for param in inspect.signature(orig).parameters.values(): - if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD): - continue - self.assertIn(param.name, have, f"setup_intel's {name} lacks setup.{name}'s `{param.name}`") - checked += 1 - self.assertGreaterEqual(checked, 8) - - def test_arc_pro_b60_is_known_under_both_pci_ids(self): - src = (ROOT / "sycl" / "setup_intel.py").read_text(encoding="utf-8") - self.assertIn('"e211": ("Arc Pro B60", 24.0)', src) - self.assertIn('"e221": ("Arc Pro B60", 24.0)', src) - - -class CMakeOption(unittest.TestCase): - def test_sycl_is_off_by_default_and_exclusive(self): - src = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8-sig") - self.assertIn('option(STRATA_ENABLE_SYCL "EXPERIMENTAL', src) - self.assertRegex(src, r'option\(STRATA_ENABLE_SYCL "[^"]*" OFF\)') - self.assertIn("add_subdirectory(sycl)", src) - - -class SyclVersion(unittest.TestCase): - def setUp(self): - from sycl import setup_intel - self.mod = setup_intel - - def test_version_matches_the_source_and_satisfies_native_models(self): - version = self.mod.sycl_version() - self.assertNotEqual(version, "0") - self.assertEqual(version, setup.source_version()) - numbers = tuple(int(x) for x in version.split(".")) - for model in ("UD-IQ4_XS", "UD-Q4_K_XL"): - with self.subTest(model=model): - self.assertGreaterEqual(numbers, setup.MODELS[model].get("engine", setup.UNSLOTH_ENGINE)) - - def test_version_follows_a_source_hotfix_with_a_variable_sycl_project(self): - with tempfile.TemporaryDirectory() as d: - root = Path(d) - (root / "CMakeLists.txt").write_text("project(strata VERSION 0.1.41.2 LANGUAGES CXX)\n", encoding="utf-8") - (root / "sycl").mkdir() - (root / "sycl" / "CMakeLists.txt").write_text( - "set(STRATA_SYCL_VERSION 0.1.40.2)\n" - "project(strata_sycl VERSION ${STRATA_SYCL_VERSION} LANGUAGES C CXX)\n", encoding="utf-8") - with mock.patch.object(self.mod, "ROOT", root), mock.patch.object(setup, "ROOT", root): - self.assertEqual(self.mod.sycl_version(), "0.1.41.2") - - -class IntelIds(unittest.TestCase): - """sycl/setup_intel.py names a card by its PCI device id. The Arc Pro B60s measured on 2x B60 (`lspci -nn` 8086:e211, - bmg-g21) must not fall through to "Intel GPU e211 (xe)" with a guessed VRAM size.""" - - @staticmethod - def table(): - import importlib.util - spec = importlib.util.spec_from_file_location("setup_intel", ROOT / "sycl" / "setup_intel.py") - mod = importlib.util.module_from_spec(spec) - spec.loader.exec_module(mod) - return mod.INTEL_ARC - - def test_b60_e211_is_named_with_its_vram(self): - self.assertEqual(self.table()["e211"], ("Arc Pro B60", 24.0)) - - def test_the_ids_that_were_listed_before_are_kept(self): - t = self.table() - self.assertEqual(t["e223"][0], "Arc Pro B70") - self.assertEqual(t["e221"][0], "Arc Pro B60") - - -class ToSycl(unittest.TestCase): - """The config sycl/setup_intel.py writes: an explicit --vram-reserve-mib is kept, the B-series streams its experts, - the A-series (i915) cannot (a single pinned host allocation above a few GB fails there) and loads them into RAM.""" - - @staticmethod - def mod(): - import importlib.util - spec = importlib.util.spec_from_file_location("setup_intel", ROOT / "sycl" / "setup_intel.py") - m = importlib.util.module_from_spec(spec) - spec.loader.exec_module(m) - return m - - def cfg(self, m, extra=()): - base = m.MOUNT - return {"exe": "x", "cwd": "y", "args": ["--pack", str(base / "d" / "pack"), "--native", str(base / "d" / "a.gguf"), - "--expert-cache", "auto", "--prefill", "auto", "--max-context", "32768", - "--kv", "int8", *extra]} - - def test_b_series_streams_and_defaults_the_reserve(self): - m = self.mod() - c = m.to_sycl(self.cfg(m), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe") - self.assertIn("--stream-experts", c["args"]) - self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "1024") - self.assertNotIn("STRATA_VERIFY_NO_HOST", c.get("env", {})) - - def test_xe_ranks_the_experts_with_the_sycl_profile_and_i915_keeps_the_shipped_one(self): - m = self.mod() - shipped = str(m.MOUNT / "data" / "expert-profile.bin") - other = str(m.MOUNT / "mine" / "learned.bin") - c = m.to_sycl(self.cfg(m, ["--expert-profile", shipped]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe") - self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("expert-profile-sycl.bin")) - c = m.to_sycl(self.cfg(m, ["--expert-profile", other]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe") - self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("learned.bin")) # the user's own file stays - c = m.to_sycl(self.cfg(m, ["--expert-profile", shipped]), m.ROOT / "build-sycl" / "strata", 64.0, {}, 8.0, "i915") - self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("expert-profile.bin")) # the CPU computes the misses there - - def test_an_explicit_reserve_is_kept_on_both_drivers(self): - m = self.mod() - for vram, drv in ((32.0, "xe"), (8.0, "i915")): - c = m.to_sycl(self.cfg(m, ["--vram-reserve-mib", "500"]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, vram, drv) - self.assertEqual(c["args"].count("--vram-reserve-mib"), 1) - self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "500") - - def test_a_series_loads_experts_into_ram_and_leaves_no_host_off(self): - m = self.mod() - c = m.to_sycl(self.cfg(m), m.ROOT / "build-sycl" / "strata", 64.0, {}, 8.0, "i915") - self.assertNotIn("--stream-experts", c["args"]) - self.assertEqual(c["args"][c["args"].index("--ple-io") + 1], "ram") - self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "300") - self.assertEqual(c["env"]["STRATA_VERIFY_NO_HOST"], "0") - self.assertEqual(c["env"]["STRATA_SYCL_BIN"], "build-sycl/strata") - - def test_split_short_rule(self): - # #1980: 2x B60 24 GB - IQ3_XXS (42.9 GB) was refused under NO_HOST=1, IQ2_XS (35.5 GB) loads fully - m = self.mod() - self.assertTrue(m.split_likely_short(42.9, [24.0, 24.0])) - self.assertFalse(m.split_likely_short(35.5, [24.0, 24.0])) - self.assertFalse(m.split_likely_short(50.3, [32.0, 32.0])) # IQ3_S on 2x B70: 79% - self.assertTrue(m.split_likely_short(77.0, [32.0, 32.0])) - self.assertFalse(m.split_likely_short(0, [24.0])) - self.assertFalse(m.split_likely_short(40.0, [])) - - def test_small_card_rule(self): - m = self.mod() - self.assertTrue(m.small_card(8.0, "i915")) - self.assertTrue(m.small_card(24.0, "i915")) - self.assertTrue(m.small_card(10.0, "xe")) - self.assertFalse(m.small_card(32.0, "xe")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py deleted file mode 100644 index 52a2a29..0000000 --- a/tools/test_setup_unsloth.py +++ /dev/null @@ -1,860 +0,0 @@ -"""Tests for setup.py's Unsloth choices (docs/UNSLOTH_Q4.md): UD-IQ4_XS (regular from 0.1.39) and the experimental -UD-Q4_K_XL: the four pinned shards with -their sizes and SHA-256, the RAM budget from the PC's RAM, the pack with --compat-bf16 (never experts.bin), the -engine version it needs, one GPU, no images. Mocked - no GPU, no downloads, nothing written outside a temp folder. - - python -m unittest tools.test_setup_unsloth -""" -from __future__ import annotations - -import contextlib -import hashlib -import io -import json -import sys -import tempfile -import types -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - -M = "UD-Q4_K_XL" -REV = "38bb39ee97821de2c9009abb7e93950eec396e66" - - -def budget_mode(): - """The RAM-budget mode whatever the RAM (MODEL-UPDATE Phase 2 writes it only where the experts do not fit): for the - tests of the budget's own paths on PCs that would now keep every expert in RAM (as in sergqwer's fork).""" - return mock.patch.object(setup, "unsloth_budget", lambda *a, **k: True) - - -class Pins(unittest.TestCase): - def test_the_four_shards(self): - fam = setup.FAMILIES["unsloth"] - names = [fam["file"].format(q=M, i=i) for i in range(1, fam["shards"] + 1)] - self.assertEqual(names, list(setup.UNSLOTH_SHARDS)) - self.assertEqual(sum(b for b, _ in setup.UNSLOTH_SHARDS.values()), 111334654784) - for _, sha in setup.UNSLOTH_SHARDS.values(): - self.assertRegex(sha, r"^[0-9a-f]{64}$") - self.assertEqual(fam["hf"].format(q=M), - f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-Q4_K_XL/") - self.assertEqual(setup.MODELS[M]["families"], ("unsloth",)) # no other family lists it - self.assertFalse(setup.MODELS[M].get("experimental")) # MODEL-UPDATE Phase 2: official - self.assertFalse(fam.get("experimental")) - self.assertEqual(list(setup.FAMILIES)[0], "qwen") # not the default choice - - def test_not_in_the_other_families(self): - for f in ("qwen", "swift", "coder"): - self.assertNotIn(M, [m for m in setup.MODELS if f in setup.MODELS[m].get("families", ("qwen", "swift"))]) - - -class Budget(unittest.TestCase): - def test_ram_less_24(self): - self.assertEqual(setup.resident_budget_gib(M, 63.7), 40) # this PC (64 GB): the measured setting - self.assertEqual(setup.resident_budget_gib(M, 47.8), 24) - self.assertEqual(setup.resident_budget_gib(M, 96), 71) # at most all of the experts (77 GB = 71.7 GiB) - self.assertEqual(setup.resident_budget_gib(M, 256), 71) - self.assertEqual(setup.resident_budget_gib(M, 20), 8) # the floor - self.assertEqual(setup.resident_budget_gib(M, 63.7, 1.7), 38) # a KV cache streamed to RAM comes out of it - - -def quiet(fn, *args): - """-> (exit code or None, printed text).""" - out = io.StringIO() - code = None - with contextlib.redirect_stdout(out): - try: - code = fn(*args) - except SystemExit as e: - code = e.code - return code, out.getvalue() - - -class Sha256(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.f = Path(self.tmp.name) / "x-00002-of-00004.gguf" - self.f.write_bytes(b"strata" * 1000) - self.sha = hashlib.sha256(self.f.read_bytes()).hexdigest() - - def tearDown(self): - self.tmp.cleanup() - - def test_good_file_marked_once(self): - code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha) - self.assertIsNone(code, out) - self.assertIn(f"sha256 {self.sha}", self.f.with_name(self.f.name + ".done").read_text()) - with mock.patch("hashlib.sha256", side_effect=AssertionError("hashed again")): - code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha) # the mark says it was checked - self.assertIsNone(code, out) - - def test_a_download_mark_alone_is_not_enough(self): - setup.mark(self.f) # the download's finish mark (a date) - with mock.patch("hashlib.sha256", wraps=hashlib.sha256) as h: - code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha) - self.assertIsNone(code, out) - self.assertTrue(h.called) - - def test_wrong_hash_deletes_it(self): - setup.mark(self.f) - code, out = quiet(setup.verify_sha256, self.f, 6000, "0" * 64) - self.assertEqual(code, 1) - self.assertIn("wrong SHA-256", out) - self.assertFalse(self.f.exists()) - self.assertFalse(self.f.with_name(self.f.name + ".done").exists()) # downloaded again next time - - def test_wrong_size(self): - code, out = quiet(setup.verify_sha256, self.f, 6001, self.sha) - self.assertEqual(code, 1) - self.assertIn("6,000 bytes, not 6,001", out) - self.assertTrue(self.f.exists()) - - -class Config(unittest.TestCase): - def test_choices_from_config(self): - with tempfile.TemporaryDirectory() as t: - for name, family, model in (("strata-unsloth-ud-q4_k_xl.json", "unsloth", M), - ("strata-swift-iq3_xxs.json", "swift", "IQ3_XXS"), - ("strata-iq3_s.json", "qwen", "IQ3_S"), - ("strata-coder-iq1_m.json", "coder", "IQ1_M")): - p = Path(t) / name - p.write_text(json.dumps({"args": ["--max-context", "8192"]})) - ch = setup.choices_from_config(p) - self.assertEqual((ch["family"], ch["model"]), (family, model), name) - - -class FakeGGUF: - """gguf_reader.GGUFFile: shard 2 holds the PLE table.""" - def __init__(self, path): - names = ["per_layer_token_embd.weight"] if "00002-of" in str(path) else ["blk.0.ffn_up_exps.weight"] - self.tensors = [types.SimpleNamespace(name=n) for n in names] - - -class Base(unittest.TestCase): - """setup.main() for the Unsloth choice, every outside effect mocked.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.t = Path(self.tmp.name) - (self.t / "data" / "mtp" / "rt").mkdir(parents=True) - (self.t / "data" / "mtp" / "rt" / "experts.bin").write_bytes(b"") - self.downloads, self.runs, self.verified = [], [], [] - - def tearDown(self): - self.tmp.cleanup() - - def main(self, argv, ram=63.7, version="0.1.32", n_gpus=1, model=True, amd=(), free=500.0, m=M, answers=None, - family=True, vram=11.9): - """answers: None = --yes; else {words of a question: its answer} (Enter for the others), and every question - asked is kept in self.asked. family=False: no --family (the first menu is shown).""" - self.asked = [] - - def fake_input(prompt=""): - if answers is None: - raise AssertionError(f"asked {prompt!r}") - self.asked.append(prompt) - return next((v for k, v in answers.items() if k in prompt), "") - - eng = self.t / "engine" - eng.mkdir(exist_ok=True) - (eng / "BUILD.json").write_text(json.dumps({"version": version, "source": "local"})) - found = [{"index": i, "name": "NVIDIA GeForce RTX 5070", "vram_gb": vram, "arch": "120", "driver": "580.97"} - for i in range(n_gpus)] - - def fake_download(url, dst, what=None): - self.downloads.append(url) - dst.parent.mkdir(parents=True, exist_ok=True) - dst.write_bytes(b"") - setup.mark(dst) - - def fake_run(cmd, *a, **k): - self.runs.append([str(x) for x in cmd]) - - patches = [ - mock.patch.object(setup, "ROOT", self.t), - mock.patch.object(setup, "GPU_PICK", None), - mock.patch.object(setup, "data_folder", lambda d: (self.t / "data", [])), - mock.patch.object(setup, "installed_configs", lambda: []), - mock.patch.object(setup, "gpus", lambda: found), - mock.patch.object(setup, "amd_gpus", lambda *a: list(amd)), - mock.patch.object(setup, "ram_gb", lambda: ram), - mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, True)), - mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU - mock.patch.object(setup, "page_file_gb", lambda: 16.0), - mock.patch.object(setup, "free_gb", lambda p: free), - mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: not the test PC's disk - mock.patch.object(setup, "is_wsl", lambda: False), # #974: the tests are not run inside WSL - mock.patch.object(setup, "pip_install", lambda *a, **k: None), - mock.patch.object(setup, "get_llama_cpp", lambda: self.t / "llama.cpp"), - mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), - mock.patch.object(setup, "download", fake_download), - mock.patch.object(setup, "check_shards", lambda shards: None), - mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), - mock.patch.object(setup, "run", fake_run), - mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), - mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: self.t / f"start-{tag}.bat"), - mock.patch.object(setup, "saved_calibration", lambda cfg: None), - mock.patch.object(setup, "start", mock.Mock(side_effect=AssertionError("started"))), - mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}), - mock.patch.object(sys, "argv", ["setup.py", *(["--family", "unsloth"] if family else []), - *(["--model", m] if model else []), - *(["--yes"] if answers is None else []), "--no-start", - "--models-dir", str(self.t / "models"), *argv]), - mock.patch("builtins.input", fake_input), - ] - with contextlib.ExitStack() as st: - for p in patches: - st.enter_context(p) - code, out = quiet(setup.main) - cfg = self.t / f"strata-unsloth-{m.lower()}.json" - return code, out, (json.loads(cfg.read_text()) if cfg.exists() else None) - -class Main(Base): - """UD-Q4_K_XL.""" - - def test_install(self): - code, out, cfg = self.main(["--context", "8192"]) - self.assertEqual(code, 0, out) - self.assertNotIn("EXPERIMENTAL", out) - base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-Q4_K_XL/" - self.assertEqual(self.downloads, [base + n for n in setup.UNSLOTH_SHARDS]) # no image encoder - self.assertEqual([v[0] for v in self.verified], list(setup.UNSLOTH_SHARDS)) - self.assertEqual([v[1:] for v in self.verified], list(setup.UNSLOTH_SHARDS.values())) - packs = [r for r in self.runs if r[1].endswith("iq_pack.py")] - self.assertEqual(len(packs), 1, self.runs) - self.assertIn("--compat-bf16", packs[0]) - self.assertNotIn("--experts-bin", packs[0]) - self.assertTrue(packs[0][packs[0].index("--gguf") + 1].endswith("UD-Q4_K_XL-00001-of-00004.gguf")) - args = cfg["args"] - self.assertEqual(args[args.index("--resident-budget-gib") + 1], "40") - self.assertTrue(args[args.index("--native") + 1].endswith("-00001-of-00004.gguf")) - for flag in ("--ple-gguf", "--mmap-experts", "--resident-experts", "--vision", "--control-vector-scaled", - "--kv-resident"): - self.assertNotIn(flag, args) - self.assertEqual(args[args.index("--max-context") + 1], "8192") - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-q4_k_xl") - self.assertNotIn("vision", cfg) - - def test_recommended_context_on_12_gb(self): - code, out, cfg = self.main([]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["args"][cfg["args"].index("--max-context") + 1], "8192") - - @budget_mode() - def test_more_ram_bigger_budget(self): - code, out, cfg = self.main(["--context", "8192"], ram=95.8) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "71") - - def test_kv_streaming_comes_out_of_the_budget(self): - code, out, cfg = self.main(["--context", "131072"]) - self.assertEqual(code, 0, out) - args = cfg["args"] - self.assertIn("--kv-resident", args) - kv_gb = 131072 * 13 * 1056 / 1e9 - self.assertEqual(args[args.index("--resident-budget-gib") + 1], str(40 - int(-(-kv_gb // 1)))) - - def test_old_engine_stops_before_the_download(self): - code, out, cfg = self.main(["--context", "8192"], version="0.1.31") - self.assertEqual(code, 1) - self.assertIn("needs engine 0.1.32 or newer; this one is 0.1.31", out) - self.assertEqual(self.downloads, []) - self.assertIsNone(cfg) - - def test_too_little_ram(self): - code, out, cfg = self.main(["--context", "8192"], ram=31.9, model=False) # --yes alone: still a stop - self.assertEqual(code, 1) - self.assertIn("needs 48 GB of RAM or more", out) - self.assertIn("--model UD-IQ4_XS --yes", out) # the way to insist (0.1.39: the family's default size) - self.assertEqual(self.downloads, []) - - def test_amd_is_not_asked(self): - """#429 is closed by MODEL-UPDATE Phase 2: UD-Q4_K_XL ran on an R9700 (quality yardstick, decode and prompt - numbers in docs/QUANTS.md), so AMD is no longer asked before the download.""" - r9700 = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201", - "driver": "amdgpu"}] - with mock.patch.object(setup, "get_prebuilt_hip", lambda *a, **k: self.t / "engine"), mock.patch.object(setup, "build_engine_hip", lambda *a, **k: self.t / "engine"): - code, out, cfg = self.main(["--context", "8192", "--backend", "hip", "--vision", "no"], amd=r9700) - self.assertNotIn("has not been run on AMD cards yet", out) - self.assertIn("RAM budget: 40 GiB of UD-Q4_K_XL's experts", out) - - def test_resumed_download_needs_room_for_the_rest_only(self): - """#425: the disk check counts the finished shards and .part files already there (sizes scaled down: a - 2 MB "model" with 1.5 MB on the disk, 8 GB of other room needed, 8.001 GB free).""" - d = self.t / "models" / "unsloth-UD-Q4_K_XL" - d.mkdir(parents=True) - (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) - with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.002}): - code, out, cfg = self.main(["--context", "8192"], free=8.001) - self.assertNotIn("not enough free disk space", out) - self.assertEqual(code, 0, out) - for f in d.iterdir(): # the first run "downloaded" them - f.unlink() - import shutil - shutil.rmtree(self.t / "data" / "mtp", ignore_errors=True) # #897: a draft layer already there needs less room - (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) - with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.003}): # 1.5 MB still missing: no room - code, out, cfg = self.main(["--context", "8192"], free=8.001) - self.assertEqual(code, 1) - self.assertIn("not enough free disk space", out) - - def test_too_little_ram_with_an_explicit_model_installs(self): - """S6 (the owner's rule): --model with --yes is the consent; the risk is said.""" - code, out, cfg = self.main(["--context", "8192"], ram=31.9) - self.assertEqual(code, 0, out) - self.assertIn("needs 48 GB of RAM or more; this PC has 32 GB", out) - self.assertIn("installing UD-Q4_K_XL with 32 GB of RAM, as you chose", out) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "8") - - def test_budget_flag(self): - """S4: --resident-budget-gib N is kept; more than the recommendation says what it risks.""" - code, out, cfg = self.main(["--context", "8192", "--resident-budget-gib", "48"]) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "48") - self.assertIn("more than setup recommends for this PC (40 GiB", out) - self.assertIn("Kept as you chose", out) - code, out, cfg = self.main(["--context", "8192", "--resident-budget-gib", "32.5"]) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "32.5") - self.assertNotIn("more than setup recommends", out) - - def test_budget_flag_with_kv_streaming_is_kept(self): - code, out, cfg = self.main(["--context", "131072", "--resident-budget-gib", "40"]) - self.assertEqual(code, 0, out) - args = cfg["args"] - self.assertIn("--kv-resident", args) - self.assertEqual(args[args.index("--resident-budget-gib") + 1], "40") # not 38: the user's number - self.assertIn("come on top of your 40 GiB RAM budget", out) - - def test_budget_flag_needs_a_positive_number(self): - with contextlib.redirect_stderr(io.StringIO()): - code, out, cfg = self.main(["--context", "8192", "--resident-budget-gib", "0"]) - self.assertEqual(code, 2) # argparse: N > 0 - self.assertIsNone(cfg) - - def test_one_gpu_and_images_with_a_warning(self): - """#967: images are allowed with UD-Q4_K_XL (tested end to end since MODEL-UPDATE).""" - code, out, cfg = self.main(["--context", "8192", "--vision", "yes", "--low-ram", "on"], n_gpus=2) - self.assertEqual(code, 0, out) - self.assertIn("(NVIDIA GeForce RTX 5070, 12 GB) only (--gpus 0,1 shares it across", out) - self.assertNotIn("images are not available", out) - self.assertIn("images: on", out) - self.assertNotIn("are untested", out) # MODEL-UPDATE: run end to end (CUDA, HIP) - self.assertIn("--low-ram on does not apply", out) - self.assertNotIn("layer_split", cfg) - self.assertIn("--vision", cfg["args"]) - self.assertTrue(cfg["vision"]["model"].endswith("UD-Q4_K_XL-00001-of-00004.gguf")) - self.assertNotIn("--mmap-experts", cfg["args"]) - self.assertFalse(any("--experts-bin" in r for r in self.runs)) - - @budget_mode() - @mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split - def test_split_when_the_ram_holds_it(self): - # #498: 165 GiB and --gpus 0,1: the split without the RAM budget (the engine refuses the pair) - code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1"], n_gpus=2, ram=165.0) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["layer_split"], "auto") - for flag in ("--resident-budget-gib", "--mmap-experts", "--resident-experts"): - self.assertNotIn(flag, cfg["args"]) - self.assertIn("as you chose (--gpus): no RAM budget", out) - self.assertIn("OS file cache", out) - self.assertNotIn("RAM budget: ", out) - - @budget_mode() - @mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split - def test_split_without_the_ram_is_a_warning_not_a_wall(self): - # #737: below the worst-case estimate (a 128 GB PC ran it) the split is still the user's call - need = setup.unsloth_split_need_gb() - self.assertAlmostEqual(need, setup.MODELS[M]["download_gb"] + setup.UNSLOTH_RAM_LEFT_GB) - code, out, cfg = self.main(["--context", "8192"], n_gpus=2, ram=127.8) # no --gpus: stays on one GPU - self.assertEqual(code, 0, out) - self.assertIn("uses them together anyway", out) - self.assertNotIn("layer_split", cfg) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "71") # all of them - code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1"], n_gpus=2, ram=127.8) # asked for by name - self.assertEqual(code, 0, out) - self.assertIn("worst case", out) - self.assertIn("as you chose (--gpus), with 128 GB of RAM", out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertNotIn("--resident-budget-gib", cfg["args"]) - - @budget_mode() - @mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split - def test_an_explicit_budget_keeps_one_gpu(self): - code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--resident-budget-gib", "60"], n_gpus=2, - ram=165.0) - self.assertEqual(code, 0, out) - self.assertIn("--resident-budget-gib has no layer split", out) - self.assertNotIn("layer_split", cfg) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "60") - - def test_split_keeps_the_budget(self): - """#642: with a resident-split engine the cards asked for keep the RAM budget, at any RAM.""" - with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): - code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1"], n_gpus=2) # 64 GB: no 135 GB asked - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["layer_split"], "auto") - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "40") - for flag in ("--mmap-experts", "--resident-experts"): - self.assertNotIn(flag, cfg["args"]) - self.assertIn("as you chose (--gpus), with its RAM budget", out) - self.assertIn("RAM budget: 40 GiB", out) - self.assertNotIn("worst case", out) - code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--resident-budget-gib", "30"], n_gpus=2) - self.assertEqual(code, 0, out) # an explicit budget too - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "30") - self.assertNotIn("has no layer split", out) - - def test_asked_with_the_budget_one_gpu_by_default(self): - """#642: asked as before (one GPU recommended); "2" takes both cards with the budget.""" - with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): - code, out, cfg = self.main(["--context", "8192"], n_gpus=2, answers={}) # Enter: one GPU - self.assertEqual(code, 0, out) - self.assertTrue(any(f"{M}: which GPUs?" in q and "[1]" in q for q in self.asked), self.asked) - self.assertNotIn("layer_split", cfg) - self.assertIn("--resident-budget-gib", cfg["args"]) - code, out, cfg = self.main(["--context", "8192"], n_gpus=2, answers={"which GPUs?": "2"}) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertIn("--resident-budget-gib", cfg["args"]) - - @budget_mode() - def test_yes_alone_keeps_one_gpu(self): - code, out, cfg = self.main(["--context", "8192"], n_gpus=2, ram=165.0) - self.assertEqual(code, 0, out) - self.assertIn("runs on one GPU: using", out) - self.assertIn("--gpus 0,1 shares it", out) - self.assertNotIn("layer_split", cfg) - self.assertIn("--resident-budget-gib", cfg["args"]) - - -X = "UD-IQ4_XS" - - -class IQ4XS(Base): - """#621: Unsloth's UD-IQ4_XS, a regular (not experimental) choice from 0.1.39 - three pinned shards, the same - RAM-budget setup as UD-Q4_K_XL (the pack with --compat-bf16, never experts.bin, one GPU), engine 0.1.38 or newer, - no AMD question; images are asked like the 2-3-bit models' (off by default).""" - - def test_pins(self): - fam = setup.FAMILIES["unsloth"] - names = [setup.model_file(fam, X, i) for i in range(1, setup.model_shards(fam, X) + 1)] - self.assertEqual(names, list(setup.UNSLOTH_IQ4_XS_SHARDS)) - self.assertEqual(sum(b for b, _ in setup.UNSLOTH_IQ4_XS_SHARDS.values()), 93682584224) - for n, (size, sha) in setup.UNSLOTH_IQ4_XS_SHARDS.items(): - self.assertRegex(sha, r"^[0-9a-f]{64}$") - self.assertEqual(fam["sha256"][n], (size, sha)) - for n in setup.UNSLOTH_SHARDS: # UD-Q4_K_XL's are still there - self.assertEqual(fam["sha256"][n], setup.UNSLOTH_SHARDS[n]) - self.assertAlmostEqual(setup.MODELS[X]["download_gb"], 93682584224 / 1e9, places=1) - self.assertEqual(setup.MODELS[X]["families"], ("unsloth",)) - self.assertEqual([m for m in setup.MODELS if "unsloth" in setup.MODELS[m].get("families", ())], - [X, M, "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"]) - self.assertIsNone(setup.gguf_unsupported(names[0])) # #444: a file setup runs now - self.assertEqual(setup.gguf_choice(names[0]), ("unsloth", X)) - self.assertEqual(setup.budget_model({"args": ["--native", "/m/" + names[0]]}), X) - self.assertEqual(setup.budget_model({"args": ["--native", "/m/" + list(setup.UNSLOTH_SHARDS)[0]]}), M) - self.assertEqual(setup.budget_model({"args": []}), M) - - def test_budget(self): - self.assertEqual(setup.resident_budget_gib(X, 63.7), 40) - self.assertEqual(setup.resident_budget_gib(X, 95.8), 55) # at most all of them (59.5 GB) - self.assertAlmostEqual(setup.unsloth_split_need_gb(X), 93.7 + setup.UNSLOTH_RAM_LEFT_GB) - - def test_install(self): - code, out, cfg = self.main(["--context", "8192"], version="0.1.38", m=X) - self.assertEqual(code, 0, out) - self.assertNotIn("is EXPERIMENTAL", out) # (the menu still lists UD-Q4_K_XL) - base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-IQ4_XS/" - self.assertEqual(self.downloads, [base + n for n in setup.UNSLOTH_IQ4_XS_SHARDS]) - self.assertEqual(self.verified, [(n, *v) for n, v in setup.UNSLOTH_IQ4_XS_SHARDS.items()]) - packs = [r for r in self.runs if r[1].endswith("iq_pack.py")] - self.assertEqual(len(packs), 1, self.runs) - self.assertIn("--compat-bf16", packs[0]) - self.assertNotIn("--experts-bin", packs[0]) - self.assertTrue(packs[0][packs[0].index("--gguf") + 1].endswith("UD-IQ4_XS-00001-of-00003.gguf")) - args = cfg["args"] - self.assertEqual(args[args.index("--resident-budget-gib") + 1], "40") - self.assertTrue(args[args.index("--native") + 1].endswith("UD-IQ4_XS-00001-of-00003.gguf")) - for flag in ("--ple-gguf", "--mmap-experts", "--resident-experts", "--vision"): - self.assertNotIn(flag, args) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-iq4_xs") - pack = self.t / "data" / "packs" / "unsloth-ud-iq4_xs" # its own pack and tokenizer - self.assertEqual(packs[0][packs[0].index("--out") + 1], str(pack)) - self.assertEqual(args[args.index("--pack") + 1], str(pack)) - self.assertEqual(cfg["tokenizer"], str(pack / "tokenizer")) - self.assertNotIn("vision", cfg) # images: asked, off by default - with tempfile.TemporaryDirectory() as t: # a start reads the choice back - p = Path(t) / "strata-unsloth-ud-iq4_xs.json" - p.write_text(json.dumps(cfg)) - ch = setup.choices_from_config(p) - self.assertEqual((ch["family"], ch["model"]), ("unsloth", X)) - - def test_family_default_and_menus(self): - """The first menu lists the Unsloth family without [experimental]; its size menu lists the five files by size, - UD-IQ4_XS first (the default on 64 GB, Enter), none marked EXPERIMENTAL; --model names are unchanged.""" - code, out, cfg = self.main(["--context", "8192", "--vision", "no"], version="0.1.38", model=False, - family=False, answers={"Which model": "4"}, m=M) - self.assertEqual(code, 0, out) - fam_line = next(ln for ln in out.splitlines() if ln.startswith(" 4) ")) - self.assertIn("Qwen3.8-Flash-Next (Unsloth)", fam_line) - self.assertIn("UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL or Q8_0 (94 to 188 GB downloads)", fam_line) - self.assertNotIn("[experimental]", fam_line) # (GLM 5.3 Flash's line has it) - size_lines = [ln for ln in out.splitlines() - if any(ln.startswith(f" {i}) {m} ") for i in range(1, 6) for m in setup.MODELS)] - self.assertEqual(len(size_lines), 5, out) - for i, (line, m) in enumerate(zip(size_lines, (X, M, "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0")), 1): - self.assertTrue(line.startswith(f" {i}) {m} "), line) - self.assertNotIn("EXPERIMENTAL", line) - self.assertTrue(any("Which size" in q and "[2]" in q for q in self.asked), self.asked) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-q4_k_xl") - code, out, cfg = self.main(["--context", "8192"], version="0.1.38", model=False, m=M) # --yes: same default - self.assertEqual(code, 0, out) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-q4_k_xl") - for m, name in ((M, "qwen3.8-flash-next-unsloth-ud-q4_k_xl"), (X, "qwen3.8-flash-next-unsloth-ud-iq4_xs")): - code, out, cfg = self.main(["--context", "8192"], version="0.1.38", m=m) # --model by name - self.assertEqual((code, cfg["model_name"]), (0, name), out) - - def test_images(self): - """Images on: the original model's image encoder (the same base model), the vision flags in the config.""" - code, out, cfg = self.main(["--context", "8192", "--vision", "yes"], version="0.1.38", m=X) - self.assertEqual(code, 0, out) - self.assertNotIn("images are not available", out) - self.assertIn("images: on", out) - self.assertEqual(self.downloads[-1], setup.hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") - + "mmproj-Qwen3.8-Flash-Next-BF16.gguf") - self.assertIn("--vision", cfg["args"]) - self.assertTrue(cfg["vision"]["model"].endswith("UD-IQ4_XS-00001-of-00003.gguf")) - self.assertIn("--resident-budget-gib", cfg["args"]) - - def test_check_verdict(self): - code, out, _ = self.main(["--check"], m=X) - self.assertEqual(code, 0, out) - line = next(ln for ln in out.splitlines() if ln.strip().startswith(X)) - self.assertIn("fits with 40 GiB of its experts in RAM", line) - self.assertNotIn("EXPERIMENTAL", line) - self.assertNotIn("EXPERIMENTAL", next(ln for ln in out.splitlines() if ln.strip().startswith(M))) - - def test_check_below_every_floor(self): - # #977: 4 GB fits no size; the RAM line is not [ok] and the verdict says so - code, out, _ = self.main(["--check"], ram=4.0, m=X) - self.assertEqual(code, 1, out) - self.assertNotIn("[ok] RAM", out) - self.assertIn("[!] RAM: 4 GB (less than", out) - self.assertIn("This PC cannot run PolyStrata yet", out) - self.assertNotIn("This PC can run PolyStrata", out) - # 16 GB fits no size of Qwen3.8-Flash-Next, and it fits sizes of the smaller models - code, out, _ = self.main(["--check"], ram=16.0, m=X) - self.assertEqual(code, 0, out) - self.assertIn("[!] RAM: 16 GB (less than", out) - self.assertIn("This PC can run PolyStrata", out) - - def test_engine_0138(self): - code, out, cfg = self.main(["--context", "8192"], version="0.1.37", m=X) - self.assertEqual(code, 1) - self.assertIn("needs engine 0.1.38 or newer; this one is 0.1.37", out) - self.assertEqual(self.downloads, []) - - def test_amd_is_not_asked(self): - r9700 = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201", - "driver": "amdgpu"}] - with mock.patch.object(setup, "get_prebuilt_hip", lambda *a, **k: self.t / "engine"), \ - mock.patch.object(setup, "build_engine_hip", lambda *a, **k: self.t / "engine"): # Linux compiles it - code, out, cfg = self.main(["--context", "8192", "--backend", "hip"], version="0.1.38", amd=r9700, m=X) - self.assertNotIn("has not been run on AMD cards yet", out) - self.assertIn("RAM budget: 40 GiB of UD-IQ4_XS's experts", out) - - -class StrixHaloCache(Base): - """#1715: on a unified-memory APU the expert cache and the RAM budget are the same RAM: setup writes a cache size - that leaves the OS room, not `--expert-cache auto` (it OOM-killed a 128 GB Strix Halo with the desktop open).""" - - HALO = [{"index": 0, "name": "AMD Radeon 8060S", "vram_gb": 2.0, "arch": "gfx1151", "driver": "amdgpu", - "uma": True, "dedicated_gb": 2.0, "shared_gb": 112.0}] - - def run_halo(self, ram, argv=("--context", "8192"), amd=None): - with mock.patch.object(setup, "get_prebuilt_hip", lambda *a, **k: self.t / "engine"), mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "build_engine_hip", lambda *a, **k: self.t / "engine"): - return self.main([*argv, "--backend", "hip"], version="0.1.41", amd=self.HALO if amd is None else amd, - ram=ram, m="UD-IQ4_XS") - - def test_cache_is_a_number_that_leaves_room(self): - code, out, cfg = self.run_halo(124.0) - self.assertEqual(code, 0, out) - args = cfg["args"] - self.assertEqual(args[args.index("--resident-budget-gib") + 1], "55") - slots = int(args[args.index("--expert-cache") + 1]) - # 124 - 24 (left) - 55 (budget) = 45 GiB of 1.1 x the average expert (59.5 GB / 24576) - self.assertEqual(slots, int(45 / (59.5e9 / setup.UMA_EXPERTS * 1.1 / 2**30))) - self.assertTrue(0 < slots < setup.UMA_EXPERTS) - self.assertIn("expert cache: %d slots (not auto)" % slots, out) - - def test_never_more_than_all_the_experts(self): - self.assertEqual(setup.uma_expert_cache("UD-IQ4_XS", 512.0, 55), setup.UMA_EXPERTS) - - def test_no_room_keeps_auto_and_says_so(self): - self.assertIsNone(setup.uma_expert_cache("UD-IQ4_XS", 64.0, 40)) - code, out, cfg = self.run_halo(64.0, ("--context", "8192", "--resident-budget-gib", "40")) - self.assertEqual(code, 0, out) - args = cfg["args"] - self.assertEqual(args[args.index("--expert-cache") + 1], "auto") - self.assertIn("leaves almost none for the expert cache", out) - - def test_a_discrete_card_keeps_auto(self): - r9700 = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201", - "driver": "amdgpu"}] - code, out, cfg = self.run_halo(124.0, amd=r9700) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["args"][cfg["args"].index("--expert-cache") + 1], "auto") - - -class LayerSplit(unittest.TestCase): - """#498: UD-Q4_K_XL across GPUs - asked at setup (one GPU by default), and a start with --gpus no longer keeps - the RAM budget the engine refused with a split (it exited with code 2). #642: from RESIDENT_SPLIT_ENGINE the - budget is kept on the split.""" - - def setUp(self): - # the behaviour before RESIDENT_SPLIT_ENGINE (an engine from before 0.1.40); the tests of the newer engine - # patch MIN_ENGINE themselves - p = mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) - p.start() - self.addCleanup(p.stop) - sys.path.insert(0, str(ROOT / "tools")) - from test_setup_golden import card - self.found = [card(i, "NVIDIA GeForce RTX 3090", 24.0, "86") for i in range(2)] - - @budget_mode() - def test_asked_one_gpu_by_default(self): - from test_setup_golden import install - argv = ["--family", "unsloth", "--model", M, "--context", "32768", "--no-start"] - code, out, cfg, asked = install(165.0, self.found, argv, answers={"which GPUs?": "1", "Which GPUs?": "1"}) - self.assertEqual(code, 0, out) - self.assertTrue(any(f"{M}: which GPUs?" in q and "[1]" in q for q in asked), asked) - self.assertEqual(cfg["gpu"], 0) - self.assertIn("--resident-budget-gib", cfg["args"]) - code, out, cfg, asked = install(165.0, self.found, argv, answers={f"{M}: which GPUs?": "2"}) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["layer_split"], "auto") - self.assertNotIn("--resident-budget-gib", cfg["args"]) - - def start(self, ram, gpu=(0, 1), offered=None): - from test_setup_risk import run - with tempfile.TemporaryDirectory() as d: - exe = Path(d) / "strata.exe" - exe.write_bytes(b"") - p = Path(d) / "strata-unsloth-ud-q4_k_xl.json" - before = {"exe": str(exe), "args": ["--pack", "p", "--resident-budget-gib", "40", "--kv", "int8"], - "gpu": 0, "gpus_asked": offered is None} - p.write_text(json.dumps(before)) - call = mock.Mock(return_value=0) - with mock.patch.object(setup, "gpus", lambda: self.found), \ - mock.patch.object(setup, "ram_gb", lambda: ram), \ - mock.patch.object(setup, "engine_runs_on", lambda g: True), \ - mock.patch.object(setup, "ensure_engine_for", lambda cards, path, cfg, yes: cfg), \ - mock.patch.object(setup, "is_wsl", lambda: False), \ - mock.patch.object(setup.subprocess, "call", call): - code, out, asked = run(setup.start, p, None, list(gpu) if gpu else None, False, offered is None, - stdin=offered) - return code, out, json.loads(p.read_text()), call.called - - def test_start_with_gpus_drops_the_budget(self): - code, out, cfg, started = self.start(165.0) - self.assertIsNone(code, out) - self.assertTrue(started) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["args"], ["--pack", "p", "--kv", "int8"]) # #1447: no helper cache - self.assertIn("no RAM budget", out) - - def test_start_with_gpus_without_the_ram_is_asked(self): - # #737: a warning and a question (default no), not a wall; --gpus with --yes is the consent - code, out, cfg, started = self.start(63.7, offered="n") # asked: "n" stops, nothing saved - self.assertEqual(code, 1) - self.assertFalse(started) - self.assertIn("cannot share its RAM budget across GPUs", out) - self.assertIn("--gpu N", out) - self.assertEqual(cfg["gpu"], 0) - self.assertIn("--resident-budget-gib", cfg["args"]) - code, out, cfg, started = self.start(63.7) # --gpus + --yes: goes on, no budget - self.assertIsNone(code, out) - self.assertTrue(started) - self.assertIn("cannot share its RAM budget across GPUs", out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertNotIn("--resident-budget-gib", cfg["args"]) - - def test_offered_at_a_start(self): - code, out, cfg, _ = self.start(165.0, gpu=None, offered="") # Enter: one GPU (the default here) - self.assertIsNone(code, out) - self.assertEqual(cfg["gpu"], 0) - self.assertIn("--resident-budget-gib", cfg["args"]) - self.assertIn("about twice as fast in #498", out) - code, out, cfg, _ = self.start(165.0, gpu=None, offered="y") - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertNotIn("--resident-budget-gib", cfg["args"]) - code, out, cfg, _ = self.start(63.7, gpu=None, offered="y") # not offered: the RAM does not hold it - self.assertEqual(cfg["gpu"], 0) - self.assertNotIn("Use both", out) - - def test_resident_split_engine_keeps_the_budget(self): - """#642: a start with --gpus keeps the budget at any RAM; offered both cards (Enter: one, as before).""" - with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): - for ram in (165.0, 63.7): - code, out, cfg, started = self.start(ram) - self.assertIsNone(code, out) - self.assertTrue(started) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["args"], ["--pack", "p", "--resident-budget-gib", "40", "--kv", "int8"]) - self.assertNotIn("no RAM budget", out) - self.assertNotIn("cannot share its RAM budget", out) - code, out, cfg, _ = self.start(63.7, gpu=None, offered="") # offered at 64 GB too; Enter: one GPU - self.assertIsNone(code, out) - self.assertIn("On both it keeps the budget", out) - self.assertIn("staying on one GPU", out) - self.assertEqual(cfg["gpu"], 0) - code, out, cfg, _ = self.start(63.7, gpu=None, offered="y") - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertIn("--resident-budget-gib", cfg["args"]) - - -Q5, Q6, Q8 = "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0" - - -class Resident(Base): - """MODEL-UPDATE Phase 2 (sergqwer's fork, 0.1.42-nvfp4.2): every expert of an Unsloth file in RAM (a pinned arena, no - --resident-budget-gib) where they fit with UNSLOTH_RESIDENT_BESIDE_GB more; the budget below that, when asked for, - and on a unified-memory APU.""" - - def test_the_rule(self): - self.assertEqual(setup.UNSLOTH_RESIDENT_BESIDE_GB, 16) - need = {m: setup.MODELS[m]["arena_gb"] / 1.073741824 + 16 for m in (X, M, Q5, Q6, Q8)} - self.assertEqual({m: round(v, 1) for m, v in need.items()}, - {X: 71.4, M: 87.7, Q5: 107.6, Q6: 117.7, Q8: 135.5}) - for m in (X, M, Q5, Q6, Q8): # "ram_gb" of the bigger files is that need, so below it setup asks - if m in (Q5, Q6, Q8): - self.assertEqual(setup.MODELS[m]["ram_gb"], int(-(-need[m] // 1))) - for ram, budget in ((63.7, {X, M, Q5, Q6, Q8}), (80.0, {M, Q5, Q6, Q8}), (95.8, {Q5, Q6, Q8}), - (127.8, {Q8}), (191.0, set())): - for m in (X, M, Q5, Q6, Q8): - self.assertEqual(setup.unsloth_budget(m, ram), m in budget, (m, ram)) - self.assertTrue(setup.unsloth_budget(X, 124.0, {"uma": True})) # #1715: measured on discrete cards only - self.assertTrue(setup.unsloth_budget(M, 127.2, None, 40)) # --resident-budget-gib: asked for - self.assertFalse(setup.unsloth_budget(M, 127.2, {"uma": False})) - - def test_install_at_128_gb(self): - for m, ver in ((M, "0.1.32"), (X, "0.1.38"), (Q5, "0.1.44")): - with self.subTest(m): - code, out, cfg = self.main(["--context", "131072"], ram=127.8, version=ver, m=m) - self.assertEqual(code, 0, out) - args = cfg["args"] - for flag in ("--resident-budget-gib", "--mmap-experts", "--resident-experts", "--low-ram"): - self.assertNotIn(flag, args) - self.assertIn(f"of {m}'s experts in RAM (they and 16 GiB more fit", out) - self.assertNotIn("RAM budget:", out) - self.assertEqual(args[args.index("--max-context") + 1], "131072") - - def test_64_gb_keeps_the_budget(self): - for m, ver in ((M, "0.1.32"), (X, "0.1.38")): - with self.subTest(m): - code, out, cfg = self.main(["--context", "8192"], ram=63.7, version=ver, m=m) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "40") - self.assertIn(f"RAM budget: 40 GiB of {m}'s experts in RAM", out) - - def test_an_asked_budget_is_kept(self): - code, out, cfg = self.main(["--context", "8192", "--resident-budget-gib", "40"], ram=127.8) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "40") - self.assertNotIn(f"of {M}'s experts in RAM (they and", out) - - def test_the_menu_and_check_say_so(self): - code, out, _ = self.main(["--check"], ram=127.8) - for m, verdict in ((X, "fits (all of its experts in RAM)"), (M, "fits (all of its experts in RAM)"), - (Q5, "fits (all of its experts in RAM)"), (Q8, "slow here: 104 GiB of its 119 GiB")): - line = next(ln for ln in out.splitlines() if ln.strip().startswith(m + " ")) - self.assertIn(verdict, line) - - def test_default_is_ud_q4_k_xl_where_it_fits(self): - """0.1.44 (owner): UD-Q4_K_XL and UD-IQ4_XS are the recommended sizes; the default is UD-Q4_K_XL when the RAM fits - it (any PC from 48 GB), else UD-IQ4_XS. A larger file stays a choice, never the default.""" - for ram in (63.7, 95.8, 127.8, 191.0): - with self.subTest(ram): - code, out, cfg = self.main(["--context", "8192"], ram=ram, version="0.1.44", model=False, m=M) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-q4_k_xl") - - def test_the_menu_marks_both_recommended_sizes(self): - names = [m for m in setup.MODELS if "unsloth" in setup.MODELS[m].get("families", ())] - self.assertEqual([m for m in names if setup.size_tag("unsloth", m)], ["UD-IQ4_XS", "UD-Q4_K_XL"]) - self.assertEqual(setup.recommended_size("unsloth", names, 63.7), "UD-Q4_K_XL") - self.assertEqual(setup.recommended_size("unsloth", names, 191.0), "UD-Q4_K_XL") - self.assertEqual(setup.recommended_size("unsloth", names, 40.0), "UD-IQ4_XS") # nothing fits: the 4-bit i-quant - - def test_two_gpus_split_with_every_expert_in_ram(self): - """Where the experts fit, two cards are the GGUF models' layer split (no budget question, no #498 note).""" - code, out, cfg = self.main(["--context", "8192"], n_gpus=2, ram=127.8) - self.assertEqual(code, 0, out) - self.assertEqual(cfg["gpu"], [0, 1]) - self.assertEqual(cfg["layer_split"], "auto") - self.assertNotIn("--resident-budget-gib", cfg["args"]) - self.assertNotIn("which GPUs?", out) - - -class BigFiles(Base): - """MODEL-UPDATE: UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 - six pinned shards each (sizes and SHA-256 from the Hub), the same - GGUF-in-place setup as UD-Q4_K_XL (--compat-bf16 pack, every expert in RAM where it fits); below the all-in-RAM need - setup asks first (default no) and says how much is read from the SSD.""" - - def test_pins(self): - fam = setup.FAMILIES["unsloth"] - for m, total in ((Q5, 158286406650), (Q6, 169165382688), (Q8, 188225033248)): - names = [setup.model_file(fam, m, i) for i in range(1, setup.model_shards(fam, m) + 1)] - self.assertEqual(len(names), 6) - self.assertEqual(sum(setup.UNSLOTH_BIG_SHARDS[n][0] for n in names), total) - for n in names: - self.assertRegex(fam["sha256"][n][1], r"^[0-9a-f]{64}$") - self.assertIsNone(setup.gguf_unsupported(names[0])) - self.assertEqual(setup.gguf_choice(names[0]), ("unsloth", m)) - self.assertEqual(setup.budget_model({"args": ["--native", "/m/" + names[0]]}), m) - self.assertAlmostEqual(setup.MODELS[m]["download_gb"], total / 1e9, places=1) - for i in (2, 3): # the head and the PLE table: the same bytes in all three - self.assertEqual(len({setup.UNSLOTH_BIG_SHARDS[setup.model_file(fam, m, i)] for m in (Q5, Q6, Q8)}), 1) - - def test_install_q8_at_192_gb(self): - code, out, cfg = self.main(["--context", "32768"], ram=191.0, version="0.1.44", m=Q8) - self.assertEqual(code, 0, out) - base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/Q8_0/" - names = [setup.model_file(setup.FAMILIES["unsloth"], Q8, i) for i in range(1, 7)] - self.assertEqual(self.downloads, [base + n for n in names]) - self.assertEqual([v[0] for v in self.verified], names) - packs = [r for r in self.runs if r[1].endswith("iq_pack.py")] - self.assertIn("--compat-bf16", packs[0]) - args = cfg["args"] - self.assertNotIn("--resident-budget-gib", args) - self.assertTrue(args[args.index("--native") + 1].endswith("Q8_0-00001-of-00006.gguf")) - self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-q8_0") - - def test_q8_below_its_ram_is_asked(self): - code, out, cfg = self.main(["--context", "8192"], ram=127.8, version="0.1.44", m=Q8, - answers={"Install it anyway": "n"}) - self.assertEqual(code, 1, out) - self.assertIn("Q8_0 needs 136 GB of RAM or more; this PC has 128 GB", out) - self.assertEqual(self.downloads, []) - code, out, cfg = self.main(["--context", "8192"], ram=127.8, version="0.1.44", m=Q8) # --model + --yes - self.assertEqual(code, 0, out) - self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "104") - - def test_q5_q6_need_the_q6k_engine(self): - for m in (Q5, Q6): - code, out, cfg = self.main(["--context", "8192"], ram=191.0, version="0.1.43", m=m) - self.assertEqual(code, 1) - self.assertIn(f"{m} needs engine 0.1.44 or newer; this one is 0.1.43", out) - self.assertEqual(self.downloads, []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_update.py b/tools/test_setup_update.py deleted file mode 100644 index 89b29c0..0000000 --- a/tools/test_setup_update.py +++ /dev/null @@ -1,208 +0,0 @@ -"""Tests for `setup.py --update` (#475, UPDATE.bat / update.sh): it refreshes what a start would - the Python packages, -the engine, each model's config and draft subset - and never starts the model. Every outside effect is mocked: no -GPU, no downloads, nothing written outside a temp folder. - - python -m unittest tools.test_setup_update -""" -from __future__ import annotations - -import contextlib -import io -import json -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT)) -import setup # noqa: E402 - - -class Update(unittest.TestCase): - def config(self, d: Path, **extra) -> Path: - rt = d / "mtp" / "rt" - rt.mkdir(parents=True) - p = d / "strata-iq3_s.json" - p.write_text(json.dumps({"model_name": "Qwen IQ3_S", "exe": str(d / "engine" / setup.EXE), - "args": ["--native", "x", "--mtp", str(rt)], **extra}), encoding="utf-8") - return p - - def run_update(self, have, argv=()): - a = mock.Mock(**{"build": False, "prebuilt": "URL", **dict(argv)}) - out = io.StringIO() - with mock.patch.object(setup, "pip_install") as pip, \ - mock.patch.object(setup, "update_installed_engine") as eng, \ - mock.patch.object(setup, "refresh_draft_vocab") as dv, \ - mock.patch.object(setup, "start") as start, \ - mock.patch("subprocess.call") as call, \ - contextlib.redirect_stdout(out): - rc = setup.update_install(have, a) - return rc, pip, eng, dv, start, call, out.getvalue() - - def test_refreshes_without_starting(self): - with tempfile.TemporaryDirectory() as d: - p = self.config(Path(d), draft_vocab="en") - rc, pip, eng, dv, start, call, out = self.run_update([p]) - self.assertEqual(rc, 0) - pip.assert_called_once() - eng.assert_called_once_with("URL") - dv.assert_called_once() - self.assertEqual(dv.call_args[0][1], "en") # the model's own subset is kept - start.assert_not_called() - call.assert_not_called() - self.assertIn("PolyStrata is updated", out) - - def test_build_keeps_the_compiled_engine_path(self): - with tempfile.TemporaryDirectory() as d: - p = self.config(Path(d)) - rc, pip, eng, dv, *_ = self.run_update([p], {"build": True}) - self.assertEqual(rc, 0) - eng.assert_not_called() - self.assertEqual(dv.call_args[0][1], "cjk") - - def test_nothing_installed(self): - rc, pip, eng, dv, start, call, out = self.run_update([]) - self.assertEqual(rc, 0) - for m in (pip, eng, dv, start, call): - m.assert_not_called() - self.assertIn("START-HERE.bat", out) - - def test_a_json_that_is_no_model_config_is_skipped(self): - """#549: a strata-*.json without "args" (not written by setup) stopped update.sh with KeyError: 'args'.""" - with tempfile.TemporaryDirectory() as d: - p = self.config(Path(d)) - other = Path(d) / "strata-notes.json" - other.write_text(json.dumps({"note": "mine"}), encoding="utf-8") - broken = Path(d) / "strata-cut.json" - broken.write_text("{\"args\": [", encoding="utf-8") - rc, pip, eng, dv, start, call, out = self.run_update([other, broken, p]) - self.assertEqual(rc, 0, out) - self.assertIn('skipped strata-notes.json (no "exe" or "args"): it is not a PolyStrata model config', out) - self.assertIn("skipped strata-cut.json (not valid JSON)", out) - dv.assert_called_once() # the real model is still refreshed - self.assertIn("Qwen IQ3_S: up to date", out) - self.assertIn("PolyStrata is updated", out) - - def test_installed_configs_lists_only_model_configs(self): - with tempfile.TemporaryDirectory() as d: - p = self.config(Path(d)) - (Path(d) / "strata-notes.json").write_text("{}", encoding="utf-8") - with mock.patch.object(setup, "ROOT", Path(d)), contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(setup.installed_configs(), [p]) - - def test_main_update_never_starts(self): - with tempfile.TemporaryDirectory() as d: - p = self.config(Path(d)) - with mock.patch.object(sys, "argv", ["setup.py", "--update"]), \ - mock.patch.object(setup, "data_folder", return_value=(Path(d), [])), \ - mock.patch.object(setup, "installed_configs", return_value=[p]), \ - mock.patch.object(setup, "update_install", return_value=0) as up, \ - mock.patch.object(setup, "start") as start, \ - contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(setup.main(), 0) - up.assert_called_once() - start.assert_not_called() - - -class SettingsLine(unittest.TestCase): - """#564: a start prints the settings it uses (the engine options without the model's paths, and the server's - fields), so a change made by hand to strata-.json shows without reading the log.""" - - CFG = {"exe": "x", "host": "0.0.0.0", "port": 8081, "api_key": "secret", "gpu": [0, 1], "fit_max_tokens": True, - "args": ["--native", "E:\\PolyStrata\\packs\\iq3_s", "--mtp", "/s/mtp/rt", "m.gguf", "--kv", "int8", - "--kv-resident", "32768", "--spec-min-p", "0.5", "--vram-reserve-mib", "2048", "--mmap-experts", - "--prefill", "auto"]} - - def test_summary(self): - s = setup.settings_summary(self.CFG) - self.assertEqual(s, "--kv int8 --kv-resident 32768 --spec-min-p 0.5 --vram-reserve-mib 2048 --mmap-experts " - "--prefill auto; server 0.0.0.0:8081, api key set, gpu 0,1, fit_max_tokens true") - self.assertNotIn("secret", s) - self.assertIn("127.0.0.1:9000", setup.settings_summary({"args": []}, 9000)) - - def test_a_start_prints_it(self): - with tempfile.TemporaryDirectory() as d: - exe = Path(d) / "strata.exe" - exe.write_bytes(b"") - p = Path(d) / "strata-iq3_s.json" - args = [x for x in self.CFG["args"] if x != "m.gguf"] # no model file here - p.write_text(json.dumps({**self.CFG, "exe": str(exe), "gpu": 0, "args": args}), encoding="utf-8") - out = io.StringIO() - with mock.patch.object(setup, "gpus", lambda: []), \ - mock.patch.object(setup, "refresh_draft_vocab"), \ - mock.patch.object(setup, "is_wsl", lambda: False), \ - mock.patch.object(setup.subprocess, "call", return_value=0), \ - contextlib.redirect_stdout(out): - setup.start(p, None, open_browser=False, yes=True) - text = " ".join(out.getvalue().split()) - self.assertIn("Settings (strata-iq3_s.json): --kv int8 --kv-resident 32768", text) - self.assertIn("--vram-reserve-mib 2048", text) - - -class TailSkip(unittest.TestCase): - """A Qwen3.6 config from before its family got "tail_skip" gets --tail-skip on update, once the engine knows it.""" - - def upgraded(self, name, version, args=()): - with tempfile.TemporaryDirectory() as d: - eng = Path(d) / "engine-poly" - eng.mkdir() - (eng / "BUILD.json").write_text(json.dumps({"version": version}), encoding="utf-8") - p = Path(d) / "strata-x.json" - cfg = {"model_name": name, "exe": str(eng / setup.POLY_EXE), "args": ["--model", "m.gguf", *args]} - p.write_text(json.dumps(cfg), encoding="utf-8") - with contextlib.redirect_stdout(io.StringIO()): - setup.poly_tail_skip(cfg, p) - return json.loads(p.read_text(encoding="utf-8"))["args"] - - def test_qwen36_gets_it(self): - self.assertEqual(self.upgraded("qwen3.6-35b-a3b-ud-q2_k_xl", "0.1.42")[-2:], ["--tail-skip", "6"]) - - def test_an_older_engine_or_another_family_does_not(self): - for name, version in (("qwen3.6-35b-a3b-ud-q3_k_m", "0.1.41"), ("ornith-1.5-35b-a3b-apex-i-compact", "0.1.42"), - ("gemma-4-26b-a4b-ud-q3_k_m", "0.1.42")): - with self.subTest(name=name, version=version): - self.assertNotIn("--tail-skip", self.upgraded(name, version)) - - def test_a_value_the_user_set_stays(self): - args = self.upgraded("qwen3.6-35b-a3b-ud-q3_k_m", "0.1.42", ["--tail-skip", "0"]) - self.assertEqual(args.count("--tail-skip"), 1) - self.assertEqual(args[-1], "0") - - -class KvWhole(unittest.TestCase): - """A strata-poly config whose engine is the AMD build gets --kv-whole on update (issue #13); a CUDA one does not.""" - - def upgraded(self, backend, args=()): - with tempfile.TemporaryDirectory() as d: - eng = Path(d) / "engine-poly" - eng.mkdir() - meta = {"version": "0.1.42", **({"backend": backend} if backend else {})} - (eng / "BUILD.json").write_text(json.dumps(meta), encoding="utf-8") - p = Path(d) / "strata-x.json" - cfg = {"model_name": "qwen3.6-35b-a3b-ud-q2_k_xl", "exe": str(eng / setup.POLY_EXE), - "args": ["--model", "m.gguf", *args]} - p.write_text(json.dumps(cfg), encoding="utf-8") - with contextlib.redirect_stdout(io.StringIO()): - setup.poly_kv_whole(cfg, p) - return json.loads(p.read_text(encoding="utf-8"))["args"] - - def test_an_amd_engine_gets_it(self): - self.assertEqual(self.upgraded("hip")[-1], "--kv-whole") - - def test_a_cuda_engine_does_not(self): - self.assertNotIn("--kv-whole", self.upgraded(None)) - - def test_once(self): - self.assertEqual(self.upgraded("hip", ["--kv-whole"]).count("--kv-whole"), 1) - - def test_no_build_stamp_is_left_alone(self): - with tempfile.TemporaryDirectory() as d: - cfg = {"exe": str(Path(d) / "engine-poly" / setup.POLY_EXE), "args": ["--model", "m.gguf"]} - setup.poly_kv_whole(cfg) - self.assertNotIn("--kv-whole", cfg["args"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_setup_update_gpu.py b/tools/test_setup_update_gpu.py deleted file mode 100644 index 52a7539..0000000 --- a/tools/test_setup_update_gpu.py +++ /dev/null @@ -1,53 +0,0 @@ -"""#1485: the card an engine update compiles for is one the installed models use (and CUDA 13 can compile for), not -the card with the most VRAM - a Tesla V100 beside two RTX 4090s made ./update.sh build for sm_70 with CUDA 13. - - python -m unittest tools.test_setup_update_gpu -v -""" -import json -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -import setup # noqa: E402 - -V100 = {"index": 1, "name": "Tesla V100-PCIE-32GB", "vram_gb": 32.0, "arch": "70", "driver": "580"} -R4090 = lambda i: {"index": i, "name": "RTX 4090", "vram_gb": 24.0, "arch": "89", "driver": "580"} # noqa: E731 - - -class UpdateEngineGpu(unittest.TestCase): - def pick(self, found, configs, toolkit=13, pinned=None): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - paths = [] - for n, cfg in enumerate(configs): - p = Path(tmp.name) / f"strata-{n}.json" - p.write_text(json.dumps(cfg)) - paths.append(p) - with mock.patch.object(setup, "gpus", return_value=found), \ - mock.patch.object(setup, "installed_configs", return_value=paths), \ - mock.patch.object(setup, "GPU_PICK", pinned): - return setup.update_engine_gpu(toolkit) - - def test_the_models_cards_not_the_biggest_one(self): - g = self.pick([R4090(0), V100, R4090(2)], [{"exe": "x", "args": [], "gpu": [0, 2]}]) - self.assertEqual(g["arch"], "89") - self.assertEqual(g["count"], 3) - - def test_a_card_cuda_13_cannot_compile_for_is_left_out_without_a_config(self): - self.assertEqual(self.pick([R4090(0), V100], [])["index"], 0) - - def test_the_cuda_12_engine_may_take_the_volta(self): - self.assertEqual(self.pick([R4090(0), V100], [], toolkit=12)["index"], 1) - - def test_only_a_volta_is_still_taken(self): - self.assertEqual(self.pick([V100], [])["index"], 1) - - def test_no_nvidia_card(self): - self.assertIsNone(self.pick([], [])) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py deleted file mode 100644 index dbbb604..0000000 --- a/tools/test_strata_mcp.py +++ /dev/null @@ -1,671 +0,0 @@ -"""tools/test_strata_mcp.py - tests for tools/strata_mcp.py (PolyStrata's MCP server), standard library only. - - python -m unittest tools/test_strata_mcp.py -v - -Setup and the model server are fakes (a temporary PolyStrata folder with a stand-in setup.py and serve/server.py), so -nothing is downloaded and no GPU is used: the JSON-RPC handshake, argument checks, install / start / stop with real -background processes, status against a fake HTTP server, and that the built-in model table still matches setup.py. -""" -from __future__ import annotations - -import io -import json -import os -import socket -import subprocess -import sys -import tempfile -import threading -import time -import unittest -from unittest import mock -from http.server import BaseHTTPRequestHandler, HTTPServer -from pathlib import Path - -HERE = Path(__file__).resolve().parent -sys.path.insert(0, str(HERE)) -import strata_mcp as M # noqa: E402 - -FAKE_SETUP = r''' -import json, sys, time -from pathlib import Path -def main(): - root = Path(__file__).resolve().parent - (root / "setup-args.json").write_text(json.dumps(sys.argv[1:])) - print("PolyStrata - fake setup", flush=True) - print("\n=== Step 1: checking your PC ===", flush=True) - print(" [ok] GPU: fake", flush=True) - print("\n=== Step 5: downloading Qwen3.8-Flash-Next Q2_0 ===", flush=True) - for pct in (10, 20, 30): - print(f"\r model.gguf: {pct * 0.5:.2f} / 50.00 GB ({pct}%) ", end="", flush=True) - print(flush=True) - if (root / "slow").exists(): - end = time.time() + 30 - while not (root / "go").exists() and time.time() < end: - time.sleep(0.1) - if (root / "fail").exists(): - print("\n [X] not enough free disk space", flush=True) - print(" use --models-dir on a bigger drive", flush=True) - sys.exit(1) - a = sys.argv - model = a[a.index("--model") + 1].lower() - cfg = {"exe": sys.executable, "args": ["--max-context", a[a.index("--context") + 1]], "port": 8080, - "model_name": "qwen3.8-flash-next-" + model, "log": str(root / f"strata-{model}.log")} - (root / f"strata-{model}.json").write_text(json.dumps(cfg)) - print("All set.", flush=True) - - -if __name__ == "__main__": - main() -''' - -FAKE_SERVER = r''' -import json, os, signal, sys, time -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -a = sys.argv -port = int(a[a.index("--port") + 1]) -cfg = json.loads(Path(a[a.index("--config") + 1]).read_text()) -root = Path(__file__).resolve().parent.parent -print("loading the model (fake) ...", flush=True) -if cfg.get("crash"): - print("engine failed: out of memory (fake)", flush=True) - sys.exit(3) -time.sleep(cfg.get("delay", 0)) -state = {"loaded": True} -class H(BaseHTTPRequestHandler): - def log_message(self, *x): - pass - def js(self, code, obj): - b = json.dumps(obj).encode() - self.send_response(code) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(b))) - self.end_headers() - self.wfile.write(b) - def do_GET(self): - p = self.path.split("?")[0] - if p == "/health": - self.js(200, {"status": "ok", "service": "strata", "model": cfg["model_name"], "max_context": 32768, - "images": False, "api_key": False, "loaded": state["loaded"]}) - elif p == "/status": - self.js(200, {"busy": bool(cfg.get("busy")), "queued": 0}) - elif p == "/v1/status": - self.js(200, {"service": "strata", "engine": "0.1.32", "uptime_s": 5, "activity": {"requests": 0}, - "machine": {"gpu": {"name": "Fake GPU", "used_mib": 11000, "total_mib": 12227}, - "ram": {"used_gib": 40.0, "total_gib": 63.1}}}) - else: - self.js(404, {"error": {"message": "not found"}}) - def do_POST(self): - n = int(self.headers.get("Content-Length") or 0) - body = json.loads(self.rfile.read(n) or b"{}") - p = self.path.split("?")[0] - if p == "/unload": - state["loaded"] = False - with open(root / "unloaded.txt", "a") as f: - f.write(str(port) + "\n") - self.js(200, {"status": "unloaded"}) - elif p == "/v1/chat/completions": - with open(root / "bench-request.json", "w") as f: - json.dump(body, f) - self.js(200, {"model": cfg["model_name"], "choices": [{"message": {"content": "x"}, "finish_reason": "length"}], - "usage": {"prompt_tokens": 30, "completion_tokens": body.get("max_tokens", 1)}, - "timings": {"predicted_per_second": 61.5, "prompt_per_second": 400.0}}) - else: - self.js(404, {}) -httpd = ThreadingHTTPServer(("127.0.0.1", port), H) -def term(*_): - print("[strata] stopped (fake)", flush=True) - os._exit(0) -signal.signal(signal.SIGTERM, term) -print(f"ready: http://127.0.0.1:{port}/v1", flush=True) -httpd.serve_forever() -''' - - -def free_port() -> int: - s = socket.socket() - s.bind(("127.0.0.1", 0)) - p = s.getsockname()[1] - s.close() - return p - - -def wait_for(cond, seconds=30.0): - end = time.time() + seconds - while time.time() < end: - if cond(): - return True - time.sleep(0.1) - return cond() - - -FAKE_HW = {"os": "TestOS 1", "ram_gb": 64.0, "cpu": {"name": "Fake CPU", "cores": 12, "avx2": True, "avx512": True}, - "gpus": [{"index": 0, "name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.9, "arch": "120", "vendor": "nvidia", - "problem": None, "usable": True}]} - - -class FakeRoot(unittest.TestCase): - """A temporary PolyStrata folder: fake setup.py and serve/server.py, its own settings file (data folder).""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - base = Path(self.tmp.name) - self.root = base / "PolyStrata" - (self.root / "serve").mkdir(parents=True) - (self.root / "setup.py").write_text(FAKE_SETUP) - (self.root / "serve" / "server.py").write_text(FAKE_SERVER) - self.env_backup = {k: os.environ.get(k) for k in ("APPDATA", "XDG_CONFIG_HOME")} - os.environ["APPDATA"] = os.environ["XDG_CONFIG_HOME"] = str(base / "config") - self.strata = M.Strata(self.root) - self.strata.python_override = sys.executable - self.strata.health_timeout = 1.0 - self.strata._hardware = lambda: dict(FAKE_HW) - self.strata.disk_free = lambda p: 1000.0 - self.tools = M.Tools(self.strata) - self.extra = [] - - def tearDown(self): - for p in self.extra: - if p.poll() is None: - p.kill() - p.wait(10) - srv = self.strata.state("server") - if srv and M.proc_alive(srv.get("pid"), srv.get("ident")): - M.proc_kill_tree(srv["pid"], srv["ident"]) - M.wait_gone(srv["pid"], srv["ident"], 10) - job = self.strata.state("install") - if job and M.proc_alive(job.get("pid"), job.get("ident")): - M.proc_kill_tree(job["pid"], job["ident"]) - M.wait_gone(job["pid"], job["ident"], 10) - for p in self.strata.children: - try: - p.wait(5) - except subprocess.TimeoutExpired: - pass - for k, v in self.env_backup.items(): - if v is None: - os.environ.pop(k, None) - else: - os.environ[k] = v - for _ in range(20): # Windows: a log may still be closing - try: - self.tmp.cleanup() - break - except OSError: - time.sleep(0.25) - - def call(self, name, args=None): - """A tools/call through the JSON-RPC layer: (result dict, isError).""" - srv = M.McpServer(self.strata, io.BytesIO()) - r = srv.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/call", - "params": {"name": name, "arguments": args or {}}}) - res = r["result"] - return json.loads(res["content"][0]["text"]), res["isError"] - - def write_config(self, tag="q2_0", port=8080, **extra): - cfg = {"exe": sys.executable, "args": ["--max-context", "32768"], "port": port, - "model_name": f"qwen3.8-flash-next-{tag}", "log": str(self.root / f"strata-{tag}.log"), **extra} - (self.root / f"strata-{tag}.json").write_text(json.dumps(cfg)) - (self.root / f"strata-{tag}.log").write_text("engine line 1\nengine line 2\n") - return cfg - - -# ------------------------------------------------------------------------------------------------ the protocol -class Protocol(FakeRoot): - def run_lines(self, msgs): - inp = io.BytesIO(("\n".join(m if isinstance(m, str) else json.dumps(m) for m in msgs) + "\n").encode()) - out = io.BytesIO() - M.McpServer(self.strata, out).serve(inp) - return {m.get("id"): m for m in (json.loads(x) for x in out.getvalue().decode().splitlines())} - - def test_handshake_list_call(self): - r = self.run_lines([ - {"jsonrpc": "2.0", "id": 1, "method": "initialize", - "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "1"}}}, - {"jsonrpc": "2.0", "method": "notifications/initialized"}, - {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, - {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "strata_models", "arguments": {}}}, - {"jsonrpc": "2.0", "id": 4, "method": "ping"}, - ]) - init = r[1]["result"] - self.assertEqual(init["protocolVersion"], "2025-06-18") - self.assertIn("tools", init["capabilities"]) - self.assertEqual(init["serverInfo"]["name"], "strata") - names = [t["name"] for t in r[2]["result"]["tools"]] - self.assertEqual(names, ["strata_status", "strata_models", "strata_install", "strata_start", "strata_stop", - "strata_logs", "strata_benchmark", "strata_connect_info"]) - for t in r[2]["result"]["tools"]: - self.assertEqual(t["inputSchema"]["type"], "object") - self.assertFalse(t["inputSchema"]["additionalProperties"]) - self.assertGreater(len(t["description"]), 60) - call = r[3]["result"] - self.assertFalse(call["isError"]) - self.assertIn("families", call["structuredContent"]) - self.assertEqual(json.loads(call["content"][0]["text"])["recommendation"]["model"], "IQ3_XXS") - self.assertEqual(r[4]["result"], {}) - self.assertNotIn(None, r) # the notification got no answer - - def test_older_protocol_and_errors(self): - r = self.run_lines([ - {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}, - "{not json", - {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "rm_rf", "arguments": {}}}, - {"jsonrpc": "2.0", "id": 3, "method": "no/such"}, - {"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "strata_logs", "arguments": []}}, - ]) - self.assertEqual(r[1]["result"]["protocolVersion"], "2024-11-05") - self.assertEqual(r[None]["error"]["code"], -32700) - self.assertEqual(r[2]["error"]["code"], -32602) - self.assertEqual(r[3]["error"]["code"], -32601) - self.assertTrue(r[4]["result"]["isError"]) - self.assertNotIn("structuredContent", r[4]["result"]) # 2024-11-05 has no structured results - - def test_real_stdio_process(self): - """The script itself over a pipe: stdout carries only JSON-RPC lines.""" - msgs = [{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}, - {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, - {"jsonrpc": "2.0", "id": 3, "method": "tools/call", - "params": {"name": "strata_logs", "arguments": {"source": "setup"}}}] - p = subprocess.run([sys.executable, str(HERE / "strata_mcp.py"), "--root", str(self.root)], - input="\n".join(json.dumps(m) for m in msgs) + "\n", capture_output=True, text=True, - timeout=60, env=dict(os.environ)) - lines = [json.loads(x) for x in p.stdout.splitlines()] - self.assertEqual(sorted(m["id"] for m in lines), [1, 2, 3]) - self.assertEqual(len(next(m for m in lines if m["id"] == 2)["result"]["tools"]), 8) - self.assertIn("ready", p.stderr) - - def test_not_a_strata_folder(self): - p = subprocess.run([sys.executable, str(HERE / "strata_mcp.py"), "--root", self.tmp.name], input="", - capture_output=True, text=True, timeout=60) - self.assertEqual(p.returncode, 2) - - -# ------------------------------------------------------------------------------------------------ validation -class Validation(FakeRoot): - def assertRejected(self, tool, args, text): - res, err = self.call(tool, args) - self.assertTrue(err, f"{tool} {args} was accepted: {res}") - self.assertIn(text, res["error"]) - - def test_install_arguments(self): - self.assertRejected("strata_install", {"model": "Q9_X"}, "model must be one of") - self.assertRejected("strata_install", {"family": "llama"}, "family must be one of") - self.assertRejected("strata_install", {"context": 12345}, "context must be one of") - self.assertRejected("strata_install", {"gpus": "0;rm -rf /"}, "gpus=") - self.assertRejected("strata_install", {"gpus": "0 && calc"}, "gpus=") - self.assertRejected("strata_install", {"gpu": -1}, "between") - self.assertRejected("strata_install", {"gpu": "1; calc"}, "whole number") - self.assertRejected("strata_install", {"gpu": 0, "gpus": "0,1"}, "not both") - self.assertRejected("strata_install", {"port": 80}, "between") - self.assertRejected("strata_install", {"backend": "rocm"}, "backend must be one of") - self.assertRejected("strata_install", {"command": "setup.py --build"}, "unknown argument") - res, err = self.call("strata_install", {"family": "swift", "model": "IQ3_S"}) - self.assertFalse(err, res) # Swift 1.5 got its IQ3_S (same shard layout as its IQ2_XS) - self.assertIn("--family swift --model IQ3_S", res["plan"]["setup_command"]) - res, err = self.call("strata_install", {"family": "unsloth", "model": "UD-Q4_K_XL", "vision": "yes"}) - self.assertFalse(err, res) # #967: images are allowed with UD-Q4_K_XL (setup warns) - self.assertEqual(res["plan"]["images"], "yes") - self.assertRejected("strata_install", {"vision": "yes\nrm"}, "control characters") - - def test_amd_vision_follows_setups_rules(self): - """#990: --vision cpu is allowed with the AMD backend on Linux (setup.hip_vision); a GPU encoder is not.""" - with mock.patch.object(M, "WIN", False): - self.assertRejected("strata_install", {"backend": "hip", "vision": "yes"}, "no GPU image encoder") - self.assertRejected("strata_install", {"backend": "hip", "vision": "gpu"}, "vision=cpu") - res, err = self.call("strata_install", {"backend": "hip", "vision": "cpu"}) - self.assertFalse(err, res) - self.assertEqual(res["plan"]["images"], "cpu") - self.assertIn("--vision cpu", res["plan"]["setup_command"]) - res, err = self.call("strata_install", {"backend": "hip", "vision": "no"}) - self.assertFalse(err, res) - with mock.patch.object(M, "WIN", True): - self.assertRejected("strata_install", {"backend": "hip", "vision": "cpu"}, "Linux") - - def test_data_dir_paths(self): - self.assertRejected("strata_install", {"data_dir": "models"}, "absolute") - self.assertRejected("strata_install", {"data_dir": str(self.root.parent / "x" / ".." / "PolyStrata-x")}, "'..'") - self.assertRejected("strata_install", {"data_dir": str(self.root.parent / "Documents")}, "named PolyStrata") - self.assertRejected("strata_install", {"data_dir": str(self.root.parent / "nope" / "PolyStrata-data")}, - "does not exist") - self.assertRejected("strata_install", {"data_dir": "\\\\server\\share\\PolyStrata-data"}, "network") - sysdir = (os.environ.get("SystemRoot", "C:\\Windows") + "\\PolyStrata-data") if M.WIN else "/etc/PolyStrata-data" - self.assertRejected("strata_install", {"data_dir": sysdir}, "system folder") - ok = [self.root.parent / "PolyStrata-data", self.root / "models-here", self.root.parent / "PolyStrata-big"] - for d in ok: - self.assertEqual(M.norm(self.tools.check_data_dir(str(d))), M.norm(d)) - - def test_other_tools_arguments(self): - self.assertRejected("strata_start", {"model": "../../etc/passwd"}, "not valid") - self.assertRejected("strata_start", {"model": "q2_0"}, "no model is installed") - self.write_config("q2_0") - self.assertRejected("strata_start", {"model": "iq3_s"}, "no installed model 'iq3_s'") - self.assertRejected("strata_start", {"wait_seconds": 100000}, "between") - self.assertRejected("strata_logs", {"lines": 0}, "between") - self.assertRejected("strata_logs", {"source": "/etc/passwd"}, "source must be one of") - self.assertRejected("strata_benchmark", {"max_tokens": 100000}, "between") - self.assertRejected("strata_stop", {"force": "yes"}, "true or false") - - def test_engine_log_outside_is_not_read(self): - self.write_config("q2_0", log=str(Path(self.tmp.name).parent / "elsewhere.log")) - res, err = self.call("strata_logs", {"source": "engine", "model": "q2_0"}) - self.assertTrue(err) - self.assertIn("outside the PolyStrata folder", res["error"]) - self.write_config("q2_0") - res, err = self.call("strata_logs", {"source": "engine"}) - self.assertFalse(err) - self.assertEqual(res["lines"], ["engine line 1", "engine line 2"]) - - -# ------------------------------------------------------------------------------------------------ install -class Install(FakeRoot): - def wait_job(self): - self.assertTrue(wait_for(lambda: not self.strata.install_job()["running"], 60)) - - def test_plan_then_install(self): - res, err = self.call("strata_install", {}) - self.assertFalse(err) - self.assertIn("Nothing was done yet", res["summary"]) - self.assertEqual((res["plan"]["family"], res["plan"]["model"], res["plan"]["context"]), ("qwen", "IQ3_XXS", 32768)) - self.assertFalse((self.root / "setup-args.json").exists()) - self.assertIsNone(self.strata.install_job()) - - res, err = self.call("strata_install", {"model": "Q2_0", "context": 65536, "vision": "no", "confirm": True}) - self.assertFalse(err, res) - self.assertIn("started in the background", res["summary"]) - self.wait_job() - args = json.loads((self.root / "setup-args.json").read_text()) - self.assertEqual(args[:2], ["--yes", "--no-start"]) - for pair in (["--family", "qwen"], ["--model", "Q2_0"], ["--context", "65536"], ["--vision", "no"]): - i = args.index(pair[0]) - self.assertEqual(args[i:i + 2], pair) - res, err = self.call("strata_install", {}) - self.assertEqual(res["install"]["result"], "installed") - self.assertEqual(res["install"]["exit_code"], 0) - self.assertEqual(res["next"], "strata_start") - st, _ = self.call("strata_status", {"hardware": False}) - self.assertEqual([m["model"] for m in st["installed"]["models"]], ["q2_0"]) - - def test_glm_plan(self): - """GLM 5.3 Flash: its one size, no images, and the context it was measured with whatever the card.""" - card = {**FAKE_HW["gpus"][0], "vram_gb": 31.5} - self.strata._hardware = lambda: {**FAKE_HW, "ram_gb": 128.0, "gpus": [card]} - res, err = self.call("strata_install", {"family": "glm"}) - self.assertFalse(err, res) - p = res["plan"] - self.assertEqual((p["family"], p["model"], p["context"], p["images"]), ("glm", "3.0BIT", 32768, "no")) - self.assertIn("--family glm --model 3.0BIT --context 32768 --vision no", p["setup_command"]) - self.assertNotIn("--experimental-speed-projection", p["setup_command"]) - res, err = self.call("strata_install", {"family": "glm", "vision": "yes"}) - self.assertTrue(err) - self.assertIn("images are not available", res["error"]) - - def test_a_family_with_sizes_of_its_own(self): - """Qwen3.6, Ornith 1.5 and Gemma 4: three sizes each, two families' of the same names; a 32 GB PC with an - 8 GB card.""" - card = {**FAKE_HW["gpus"][0], "vram_gb": 8.0} - self.strata._hardware = lambda: {**FAKE_HW, "ram_gb": 32.0, "gpus": [card]} - res, err = self.call("strata_install", {"family": "gemma4"}) - self.assertFalse(err, res) - p = res["plan"] - self.assertEqual((p["family"], p["model"], p["context"], p["download_gb"], p["ram"]), - ("gemma4", "UD-Q3_K_M", 32768, 13.2, "fits")) - self.assertIn("--family gemma4 --model UD-Q3_K_M --context 32768 --vision no", p["setup_command"]) - res, err = self.call("strata_install", {"model": "APEX-I-COMPACT"}) - self.assertFalse(err, res) - self.assertEqual((res["plan"]["family"], res["plan"]["download_gb"]), ("ornith", 17.4)) - res, err = self.call("strata_install", {"model": "UD-Q3_K_M"}) - self.assertTrue(err) - self.assertIn("give family too (qwen36 or gemma4)", res["error"]) - res, err = self.call("strata_install", {"model": "UD-Q4_K_XL"}) # Unsloth's, as before Tiel had one - self.assertFalse(err, res) - self.assertEqual(res["plan"]["family"], "unsloth") - res, err = self.call("strata_install", {"family": "tiel"}) - self.assertFalse(err, res) - self.assertEqual((res["plan"]["model"], res["plan"]["download_gb"], res["plan"]["ram"]), - ("UD-Q3_K_XL", 17.2, "fits")) - res, err = self.call("strata_install", {"family": "qwen", "model": "UD-Q3_K_M"}) - self.assertTrue(err) - self.assertIn("Qwen3.8-Flash-Next has no UD-Q3_K_M", res["error"]) - res, err = self.call("strata_models", {}) - self.assertFalse(err, res) - by = {f["family"]: f["sizes"] for f in res["families"]} - self.assertEqual([(x["model"], x["download_gb"], x["on_this_pc"], x["id"]) for x in by["qwen36"]], - [("UD-Q3_K_M", 17.1, "fits", "qwen36-ud-q3_k_m"), - ("UD-Q2_K_XL", 12.6, "fits", "qwen36-ud-q2_k_xl"), - ("UD-Q4_K_M", 22.7, "fits", "qwen36-ud-q4_k_m")]) - self.assertEqual((by["gemma4"][0]["download_gb"], by["gemma4"][0]["images"]), (13.2, True)) - self.assertFalse(next(f for f in res["families"] if f["family"] == "glm")["images"]) # GLM reads none - - def test_progress_while_running_and_cancel(self): - (self.root / "slow").write_text("") - res, err = self.call("strata_install", {"family": "coder", "confirm": True}) - self.assertFalse(err, res) - self.assertTrue(wait_for(lambda: (self.strata.install_job() or {}).get("download") is not None, 30)) - res, err = self.call("strata_install", {"model": "IQ3_S", "confirm": True}) # a second call: progress only - self.assertFalse(err) - self.assertIn("an install is running", res["summary"]) - self.assertEqual(res["install"]["step"], "5/7: downloading Qwen3.8-Flash-Next Q2_0") - self.assertEqual(res["install"]["download"]["percent"], 30) - res, err = self.call("strata_start", {}) - self.assertTrue(err) - self.assertIn("install is still running", res["error"]) - res, err = self.call("strata_install", {"cancel": True}) - self.assertIn("stopped", res["summary"]) - self.assertFalse(self.strata.install_job()["running"]) - - def test_failure_is_reported(self): - (self.root / "fail").write_text("") - self.call("strata_install", {"model": "Q2_0", "confirm": True}) - self.wait_job() - res, _ = self.call("strata_install", {}) - self.assertEqual(res["install"]["result"], "failed") - self.assertIn("not enough free disk space - use --models-dir on a bigger drive", res["install"]["error"]) - - def test_disk_space_is_checked(self): - self.strata.disk_free = lambda p: 10.0 - res, err = self.call("strata_install", {"model": "Q2_0"}) - self.assertIn("not enough free disk space", res["plan"]["disk_short"]) - res, err = self.call("strata_install", {"model": "Q2_0", "confirm": True}) - self.assertTrue(err) - self.assertIsNone(self.strata.install_job()) - - -# ------------------------------------------------------------------------------------------------ start / stop / status -class StartStop(FakeRoot): - def test_start_status_bench_stop(self): - port = free_port() - self.write_config("q2_0", port=port, delay=1.5) - res, err = self.call("strata_start", {"wait_seconds": 30}) - self.assertFalse(err, res) - self.assertIn("PolyStrata is running", res["summary"]) - pid = res["server"]["pid"] - - st, _ = self.call("strata_status", {"hardware": False}) - self.assertIn(f"running on port {port}", st["summary"]) - srv = st["running"][0] - self.assertEqual(srv["engine_version"], "0.1.32") - self.assertEqual(srv["gpu"]["total_mib"], 12227) - self.assertIn("this MCP server", srv["started_by"]) - - res, err = self.call("strata_start", {}) # already running: nothing new - self.assertIn("already running", res["summary"]) - - b, err = self.call("strata_benchmark", {"max_tokens": 64}) - self.assertFalse(err, b) - self.assertEqual(b["output_tok_s"], 61.5) - sent = json.loads((self.root / "bench-request.json").read_text()) - self.assertEqual((sent["temperature"], sent["max_tokens"], sent["reasoning_effort"]), (0, 64, "none")) - - c, _ = self.call("strata_connect_info", {}) - self.assertEqual(c["openai_base_url"], f"http://127.0.0.1:{port}/v1") - - logs, _ = self.call("strata_logs", {"source": "server"}) - self.assertTrue(any(line.startswith("ready:") for line in logs["lines"])) - - res, err = self.call("strata_stop", {}) - self.assertFalse(err, res) - self.assertIn("PolyStrata stopped", res["summary"]) - self.assertEqual(res["engine_unloaded"], "unloaded") - self.assertEqual((self.root / "unloaded.txt").read_text().split(), [str(port)]) - ident = M.proc_identity(pid) - self.assertIsNone(ident) - st, _ = self.call("strata_status", {"hardware": False}) - self.assertEqual(st["running"], []) - res, _ = self.call("strata_stop", {}) - self.assertEqual(res["summary"], "PolyStrata is not running") - - def test_start_reports_a_crash(self): - self.write_config("q2_0", port=free_port(), crash=True) - res, err = self.call("strata_start", {"wait_seconds": 30}) - self.assertTrue(err) - self.assertIn("out of memory (fake)", res["error"]) - self.assertEqual(self.strata.state("server"), {}) - - def test_loading_then_ready(self): - port = free_port() - self.write_config("q2_0", port=port, delay=3) - res, err = self.call("strata_start", {"wait_seconds": 0}) - self.assertIn("loading", res["summary"]) - st, _ = self.call("strata_status", {"hardware": False}) - self.assertIn("loading", st["summary"]) - self.assertTrue(wait_for(lambda: self.strata.probe(port) is not None, 30)) - - def test_stop_while_busy_needs_force(self): - port = free_port() - self.write_config("q2_0", port=port, busy=True) - self.call("strata_start", {"wait_seconds": 30}) - res, err = self.call("strata_stop", {}) - self.assertTrue(err) - self.assertIn("force=true", res["error"]) - res, err = self.call("strata_stop", {"force": True}) - self.assertFalse(err, res) - - def test_external_server_is_only_unloaded(self): - port = free_port() - self.write_config("q2_0", port=port) - p = subprocess.Popen([sys.executable, str(self.root / "serve" / "server.py"), "--config", - str(self.root / "strata-q2_0.json"), "--port", str(port)], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - self.extra.append(p) - self.assertTrue(wait_for(lambda: self.strata.probe(port) is not None, 30)) - st, _ = self.call("strata_status", {"hardware": False}) - self.assertIn("outside this MCP server", st["running"][0]["started_by"]) - res, err = self.call("strata_start", {}) - self.assertIn("started outside this MCP server", res["summary"]) - res, err = self.call("strata_stop", {}) - self.assertFalse(err, res) - self.assertIn("only its model was unloaded", res["summary"]) - time.sleep(0.5) - self.assertIsNone(p.poll()) # the server itself was not touched - - def test_never_kills_an_unrelated_process(self): - other = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) - self.extra.append(other) - # a stale record: this process id, but another start time (a reused id) - self.strata.save_state("server", {"pid": other.pid, "ident": "win:1" if M.WIN else "linux:1", - "port": free_port(), "model": "q2_0"}) - res, _ = self.call("strata_stop", {}) - self.assertEqual(res["summary"], "PolyStrata is not running") - self.assertFalse(M.proc_terminate(other.pid, "linux:1")) - time.sleep(0.3) - self.assertIsNone(other.poll()) - - def test_status_sees_other_programs_on_the_port(self): - class H(BaseHTTPRequestHandler): - def do_GET(self): - self.send_response(404) - self.end_headers() - - def log_message(self, *a): - pass - httpd = HTTPServer(("127.0.0.1", 0), H) - port = httpd.server_address[1] - threading.Thread(target=httpd.serve_forever, daemon=True).start() - try: - self.write_config("q2_0", port=port) - st, _ = self.call("strata_status", {"hardware": False}) - self.assertEqual(st["running"], []) - self.assertEqual(st["ports_used_by_other_programs"][0]["port"], port) - res, err = self.call("strata_start", {}) - self.assertTrue(err) - self.assertIn("used by another program", res["error"]) - finally: - httpd.shutdown() - httpd.server_close() - - -# ------------------------------------------------------------------------------------------------ helpers -class Helpers(unittest.TestCase): - def test_progress_from_setup_output(self): - with tempfile.TemporaryDirectory() as d: - f = Path(d) / "setup.log" - f.write_text("=== Step 4: the PolyStrata engine ===\n [ok] engine\n=== Step 5: downloading X ===\n" - "\r a.gguf: 1.00 / 50.00 GB (2%) \r a.gguf: 25.00 / 50.00 GB (50%) \n") - p = M.install_progress(M.read_tail(f, 50)) - self.assertEqual(p["step"], "5/7: downloading X") - self.assertEqual(p["download"], {"file": "a.gguf", "done_gb": 25.0, "total_gb": 50.0, "percent": 50}) - self.assertNotIn("error", p) - - def test_builtin_table_matches_setup(self): - s = M.Strata(HERE.parent) - S = s.setup_module() - self.assertIsNotNone(S, "the repository's setup.py did not import") - self.assertEqual(list(S.MODELS), list(M.FALLBACK_MODELS)) - for m, d in S.MODELS.items(): - for k in ("download_gb", "ram_gb", "arena_gb"): - self.assertEqual(d[k], M.FALLBACK_MODELS[m][k], f"{m} {k}") - for k in ("experimental", "vision"): - self.assertEqual(d.get(k), M.FALLBACK_MODELS[m].get(k), f"{m} {k}") - self.assertEqual(d.get("families", ("qwen", "swift")), M.FALLBACK_MODELS[m].get("families", ("qwen", "swift"))) - self.assertEqual(list(S.FAMILIES), list(M.FALLBACK_FAMILIES)) - for f, d in S.FAMILIES.items(): - self.assertEqual(d["tag"], M.FALLBACK_FAMILIES[f]["tag"]) - self.assertEqual((d.get("vision"), d["about"]), (M.FALLBACK_FAMILIES[f].get("vision"), - M.FALLBACK_FAMILIES[f]["about"]), f) - own = M.FALLBACK_FAMILIES[f].get("models", {}) - self.assertEqual(list(d.get("models", {})), list(own), f) - for m, size in d.get("models", {}).items(): - for k in ("about", "download_gb", "ram_gb", "arena_gb"): - self.assertEqual(size[k], own[m][k], f"{f} {m} {k}") - self.assertEqual(list(S.CONTEXTS), M.FALLBACK_CONTEXTS) - - def test_unsloth_sizes(self): - """0.1.39: UD-IQ4_XS is a regular size, listed first; MODEL-UPDATE Phase 2: UD-Q4_K_XL is no longer experimental, - and UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 follow by size.""" - s = M.Strata(HERE.parent) - for models in (s.tables()[0], M.FALLBACK_MODELS): - self.assertEqual(s.sizes_of(models, "unsloth"), ["UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"]) - self.assertFalse(models["UD-IQ4_XS"].get("experimental")) - self.assertFalse(models["UD-Q4_K_XL"].get("experimental")) - self.assertEqual(s.sizes_of(M.FALLBACK_MODELS, "qwen"), ["Q2_0", "IQ2_XS", "IQ3_XXS", "IQ3_S"]) - fam = next(f for f in s.model_table({"ram_gb": 63.7, "gpus": []}) if f["family"] == "unsloth") - self.assertFalse(fam["experimental"]) - self.assertTrue(fam["images"]) - by = {x["model"]: x for x in fam["sizes"]} - self.assertEqual((by["UD-IQ4_XS"]["experimental"], by["UD-IQ4_XS"]["images"]), (False, True)) - self.assertEqual((by["UD-Q4_K_XL"]["experimental"], by["UD-Q4_K_XL"]["images"]), (False, True)) # #967 - self.assertFalse(by["UD-IQ4_XS"]["on_this_pc"].startswith("experimental")) - self.assertIn("read from the SSD", by["UD-Q4_K_XL"]["on_this_pc"]) # 64 GB: the RAM budget - fam = next(f for f in s.model_table({"ram_gb": 127.8, "gpus": []}) if f["family"] == "unsloth") - by = {x["model"]: x for x in fam["sizes"]} - self.assertEqual(by["UD-Q4_K_XL"]["on_this_pc"], "fits (all of its experts in RAM)") - self.assertIn("read from the SSD", by["Q8_0"]["on_this_pc"]) - - def test_recommendation_follows_ram(self): - s = M.Strata(HERE.parent) - gpu = [{"index": 0, "name": "x", "vram_gb": 24.0, "usable": True, "vendor": "nvidia"}] - cases = {96: ("qwen", "IQ3_XXS", 131072), 48: ("qwen", "Q2_0", 131072), 32: ("coder", "IQ1_M", 131072)} - for ram, want in cases.items(): - r = s.recommend({"ram_gb": ram, "gpus": gpu, "cpu": {"avx2": True}}) - self.assertEqual((r["family"], r["model"], r["context"]), want, ram) - r = s.recommend({"ram_gb": 16, "gpus": [{**gpu[0], "vram_gb": 8.0}], "cpu": {"avx2": True}}) - self.assertIsNone(r["model"]) - r = s.recommend({"ram_gb": 64, "gpus": [], "cpu": {"avx2": True}}) - self.assertIsNone(r["model"]) - r = s.recommend({"ram_gb": 64, "gpus": [{**gpu[0], "vram_gb": 12.0}], "cpu": {"avx2": True}}) - self.assertEqual(r["context"], 32768) - - -if __name__ == "__main__": - unittest.main() diff --git a/update.sh b/update.sh deleted file mode 100755 index bb67a55..0000000 --- a/update.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/bin/sh -# Update PolyStrata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then -# what ./setup.sh does before a start - the engine (a new ready-made one when this version needs it, or compiled -# again when its source changed), the Python packages, each installed model's settings and draft subset. The model -# files are not touched. Start the model later with ./setup.sh. Options are passed on to setup.py. -cd "$(dirname "$0")" || exit 1 -# all of it in a function, read before it runs: the git pull below can change this very file -main() { - if [ -e .git ]; then - if ! command -v git >/dev/null 2>&1; then - echo "This folder is a git clone, but git is not installed: install it (sudo apt install git) or run" - echo "\"git pull\" here yourself, then run ./update.sh again." - exit 1 - fi - echo "Getting the newest PolyStrata (git pull) ..." - if ! git pull --ff-only; then - # The history of the repository was rewritten on 2026-10-06 (#1276): a clone made before that has no commit in - # common with origin/main, so a fast-forward can never work. Say so, and move it over when nothing is lost. - if [ "$(git rev-parse --is-shallow-repository 2>/dev/null)" != "true" ] && ! git merge-base HEAD origin/main >/dev/null 2>&1; then - echo - echo "This clone is on the repository's old history (cleaned up on 2026-10-06): it has no commit in common" - echo "with origin/main, so it cannot be updated by git pull." - if [ -n "$(git status --porcelain --untracked-files=no)" ]; then - echo "You have local changes to tracked files here, so nothing was touched. To move to the new history" - echo "yourself (your untracked files, models and settings stay where they are):" - echo " git branch pre-cleanup-backup && git stash push # keeps the old commits and your edits" - echo " git checkout -B main origin/main" - echo "then run ./update.sh again." - exit 1 - fi - bk=pre-cleanup-backup - if git rev-parse --verify -q "refs/heads/$bk" >/dev/null 2>&1; then - bk="pre-cleanup-backup-$(date +%Y%m%d%H%M%S)" - fi - branch=$(git symbolic-ref --short -q HEAD || echo main) - if git branch "$bk" HEAD && git checkout -q -B "$branch" origin/main; then - echo "Moved to the new history. Your old commits are kept in the branch $bk." - echo "Untracked files (models, settings, the engine) were not touched." - else - # the backup branch made a moment ago would make the by-hand `git branch pre-cleanup-backup` below fail - git branch -D "$bk" >/dev/null 2>&1 - echo "Could not move to the new history (the reason is above): nothing was updated. By hand:" - echo " git branch pre-cleanup-backup" - echo " git checkout -B main origin/main" - exit 1 - fi - else - echo - echo "git pull did not succeed (the reason is above): nothing was updated. Files you changed here can stop it:" - echo "\"git status\" lists them." - exit 1 - fi - fi - else - echo "This copy of PolyStrata was not made with git, so it cannot fetch new files itself. Download the newest one:" - echo " https://github.com/VecSzn/PolyStrata/archive/refs/heads/main.zip" - echo "unzip it anywhere and run ./setup.sh (or ./update.sh) in it: it finds the model files in PolyStrata-data and" - echo "sets itself up the same way - nothing big is downloaded again." - echo "Checking this copy's engine and settings meanwhile ..." - fi - exec sh ./setup.sh --update "$@" -} -main "$@"