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.
This commit is contained in:
Robert Karl committed 2026-10-17 20:38:18 -07:00
1 parent 7e683af1bb
commit ec59208d87
72 files changed
+15 -25575

No files matched your search

-27
View File
@@ -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
-119
View File
@@ -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=<secret>. 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"]
-3
View File
@@ -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 %*
-52
View File
@@ -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
-81
View File
@@ -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
)
+12 -1
View File
@@ -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`.
-9
View File
@@ -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
-106
View File
@@ -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-<model>.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-<model>.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 "$@"
Generated
-27
View File
@@ -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
}
-49
View File
@@ -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}
'';
};
};
};
}
-23
View File
@@ -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"
-8223
View File
File diff suppressed because it is too large. Load diff
-69
View File
@@ -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 "$@"
-173
View File
@@ -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 <rocm-sdk path --root> \\
--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())
-101
View File
@@ -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-<model>.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())
-203
View File
@@ -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/<repo>, 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
-75
View File
@@ -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<Qwen::QwenImage21Runner>(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<Qwen::QwenImage21NativeRunner>(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<Qwen::QwenImage21Runner>(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")
-679
View File
@@ -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 <cstdint>
#include <cstdlib>
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 <bool RES, bool LN>
__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<float4*>(x + row * C);
const float4* hr = reinterpret_cast<const float4*>(h + row * C);
const float4* t4 = reinterpret_cast<const float4*>(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<const float4*>(m);
float4* o4 = reinterpret_cast<float4*>(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 <bool RES, bool LN>
__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 <typename QT>
__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 <typename QT>
__device__ __forceinline__ void qi_store4(QT* dst, float a, float b, float c, float d);
template <>
__device__ __forceinline__ void qi_store4<float>(float* dst, float a, float b, float c, float d) {
*reinterpret_cast<float4*>(dst) = make_float4(a, b, c, d);
}
template <>
__device__ __forceinline__ void qi_store4<half>(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<uint32_t*>(&lo);
u.y = *reinterpret_cast<uint32_t*>(&hi2);
*reinterpret_cast<uint2*>(dst) = u;
}
template <typename QT>
__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<const float4*>(pe + ((size_t) t * (QI_D / 2) + lane * 2) * 4);
const float4 p1 = *reinterpret_cast<const float4*>(pe + ((size_t) t * (QI_D / 2) + lane * 2 + 1) * 4);
for (int which = 0; which < 2; ++which) {
const float4 x = *reinterpret_cast<const float4*>((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<const float4*>((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<QT>(qo + ((size_t) hh * q_tstride + t) * QI_D + d, r0, r1, r2, r3);
else
qi_store4<half>(ko + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, r0, r1, r2, r3);
}
const float4 vv = *reinterpret_cast<const float4*>(v + src);
qi_store4<half>(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<const uint4*>(p + QI_KOFF(hi)));
#else
(void) hi;
const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(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 <bool LO>
__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<const uint4*>(Kh + (size_t) key * QI_D + c);
*reinterpret_cast<uint4*>(&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<const uint4*>(Vh + (size_t) (k0 + r4 + j) * QI_D + c);
*reinterpret_cast<uint4*>(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<uint2*>(&sVt[c + dd][r4]) = *reinterpret_cast<uint2*>(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<uint32_t*>(&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<const uint32_t*>(Qh + (size_t) r0 * QI_D + kc * 16 + c2);
qa[kc][1] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r1 * QI_D + kc * 16 + c2);
qa[kc][2] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r0 * QI_D + kc * 16 + c2 + 8);
qa[kc][3] = *reinterpret_cast<const uint32_t*>(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<float2*>(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<float2*>(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<cudaStream_t>(s); }
} // namespace
extern "C" {
void* qi21_stream(ggml_backend_t backend) {
return static_cast<ggml_backend_cuda_context*>(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<ggml_backend_cuda_context*>(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<ggml_backend_cuda_context*>(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<true, true><<<T, 256, 0, qi_s(stream)>>>(x, h, tg, out, m, C, eps);
else if (h != nullptr)
k_res_ln_mod4<true, false><<<T, 256, 0, qi_s(stream)>>>(x, h, tg, out, m, C, eps);
else
k_res_ln_mod4<false, true><<<T, 256, 0, qi_s(stream)>>>(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<true, true><<<T, 256, 0, qi_s(stream)>>>(x, h, g, out, m, C, eps);
else if (h != nullptr)
k_res_ln_mod<true, false><<<T, 256, 0, qi_s(stream)>>>(x, h, g, out, m, C, eps);
else
k_res_ln_mod<false, true><<<T, 256, 0, qi_s(stream)>>>(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<half><<<gw, 256, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<half*>(qo), q_tstride,
static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride,
kv_off, eps);
else
k_qkv_post_w<float><<<gw, 256, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<float*>(qo),
q_tstride, static_cast<half*>(ko), static_cast<half*>(vo),
kv_tstride, kv_off, eps);
return cudaGetLastError() == cudaSuccess ? 0 : 2;
}
const dim3 grid(T, H);
if (q_f16)
k_qkv_post<half><<<grid, QI_D, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<half*>(qo),
static_cast<half*>(qlo), q_tstride,
static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride,
kv_off, eps);
else
k_qkv_post<float><<<grid, QI_D, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<float*>(qo), nullptr,
q_tstride,
static_cast<half*>(ko), static_cast<half*>(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<<<dim3(Lq, H), QI_D, smem, qi_s(stream)>>>(q, q_tstride, static_cast<const half*>(k),
static_cast<const half*>(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<true><<<grid, FA_NW * 32, 0, qi_s(stream)>>>(static_cast<const _Float16*>(q),
static_cast<const _Float16*>(qlo), q_tstride,
static_cast<const _Float16*>(k),
static_cast<const _Float16*>(v), kv_tstride, out, H,
nq, nkv, sl);
else
k_attn_wmma<false><<<grid, FA_NW * 32, 0, qi_s(stream)>>>(static_cast<const _Float16*>(q), nullptr, q_tstride,
static_cast<const _Float16*>(k),
static_cast<const _Float16*>(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<<<dim3((nq + MF_BQ - 1) / MF_BQ, H), MF_NW * 32, MF_SMEM, qi_s(stream)>>>(
static_cast<const half*>(q), q_tstride, static_cast<const half*>(k), static_cast<const half*>(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"
@@ -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 <chrono>
#include <cstdio>
#include <cstring>
#include <memory>
#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<std::string, ggml_tensor*> 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<char> gbuf; // ggml graph metadata arena
QwenImage21NativeRunner(ggml_backend_t backend, const String2TensorStorage& weights, const std::string& prefix,
std::shared_ptr<RunnerWeightManager> 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<Piece> plan;
std::map<ggml_tensor*, ggml_type> 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<std::string, std::pair<ggml_tensor*, size_t>> 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<char> 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<char> raw(nb);
std::vector<float> 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<int64_t>(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<int64_t>(l_cap, 1));
pk = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D * H, std::max<int64_t>(l_cap, 1), config.num_layers);
pv = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D * H, std::max<int64_t>(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<ggml_tensor*> 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<float> 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<QwenImage21DiffusionExtra>(&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<std::pair<int64_t, int64_t>> 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<float> 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<float> 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<float> o((size_t) T * config.out_channels);
ggml_backend_tensor_get(outp, o.data(), 0, o.size() * sizeof(float));
sd::Tensor<float> 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<double, std::milli>(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__
+3
View File
@@ -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
-1885
View File
File diff suppressed because it is too large. Load diff
-117
View File
@@ -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-<tag>.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()
-174
View File
@@ -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()
-202
View File
@@ -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 <x>\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()
-578
View File
@@ -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()
-99
View File
@@ -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()
-663
View File
@@ -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, "<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, "<D> 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), [])
-36
View File
@@ -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()
-277
View File
@@ -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-<model>.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()
-63
View File
@@ -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-<model>.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()
-115
View File
@@ -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()
-153
View File
@@ -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()
-390
View File
@@ -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()
-105
View File
@@ -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()
-290
View File
@@ -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()
-452
View File
@@ -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()
File diff suppressed because it is too large. Load diff
-214
View File
@@ -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"(?<![w.-]){re.escape(setup.EXE)}(?![w.-])", "<EXE>", v.replace(str(t), "<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": ["<cuda>"]}))
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()
-53
View File
@@ -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<project version> 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()
-117
View File
@@ -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()
-126
View File
@@ -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()
-173
View File
@@ -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()
-84
View File
@@ -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()
-281
View File
@@ -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 <model>.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()
-210
View File
@@ -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()
-139
View File
@@ -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/<repo>/resolve/master/<path> and
/api/v1/models/<repo>/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()
-180
View File
@@ -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()
-95
View File
@@ -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()
-287
View File
@@ -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"], "<T>/engine-cuda12/<EXE>")
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"], "<T>/engine/<EXE>")
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": ["<cu13>"]}
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"<cu{tk}>"]), \
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, ["<cu12>"]))
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()
-158
View File
@@ -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()
-63
View File
@@ -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()
-44
View File
@@ -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()
-360
View File
@@ -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"<html>not a zip</html>")
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()
-149
View File
@@ -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()
-307
View File
@@ -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()
-98
View File
@@ -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()
-104
View File
@@ -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()
-514
View File
@@ -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()
File diff suppressed because it is too large. Load diff
-168
View File
@@ -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 "<html><body>" + "".join(f'<a href="../rocm-{v}.tar.gz">rocm-{v}.tar.gz</a><br/>' for v in LISTINGS[family]) + "</body></html>"
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()
-121
View File
@@ -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()
-54
View File
@@ -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("<Q", len(b)) + b
def gguf(path, tensors=(), pad_data=0):
"""A GGUF v3 file with one string key and the given (name, n_floats) F32 tensors."""
kv = _str("general.name") + struct.pack("<I", 8) + _str("t")
tinfo = b""
off = 0
for name, n in tensors:
tinfo += _str(name) + struct.pack("<I", 1) + struct.pack("<Q", n) + struct.pack("<I", 0) + struct.pack("<Q", off)
off += ((n * 4 + 31) // 32) * 32
head = b"GGUF" + struct.pack("<IQQ", 3, len(tensors), 1) + kv + tinfo
body = head
if tensors:
body += b"\0" * ((32 - len(head) % 32) % 32)
body += b"\0" * pad_data
path.write_bytes(body)
return len(head)
class ShardCheck(unittest.TestCase):
def setUp(self):
self.d = Path(tempfile.mkdtemp())
def test_metadata_only_shard_without_padding_is_whole(self):
p = self.d / "m-00001-of-00006.gguf"
n = gguf(p)
self.assertNotEqual(n % 32, 0, "the test file must end unaligned, like the real shard")
setup.check_shards([p]) # must not stop setup
def test_truncated_tensor_data_is_still_refused(self):
p = self.d / "t-00002-of-00006.gguf"
gguf(p, tensors=[("w", 64)], pad_data=100) # needs 256 bytes of data, has 100
with self.assertRaises(SystemExit):
setup.check_shards([p])
if __name__ == "__main__":
unittest.main()
-131
View File
@@ -1,131 +0,0 @@
"""Tests for setup's UD-* start on a card of about 8 GB (0.1.44): the VRAM estimate, the plan that picks the least harmful
config that starts, and the words (UD-Q4 is slow here: pick IQ3_XXS / IQ3_S). Measured on an 8 GB Arc A750: setup's
8192 / int8 / reserve 400 start stopped with "no VRAM is left for the expert cache, short 473 MiB".
python -m unittest tools.test_setup_small_card
"""
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_unsloth import Base # noqa: E402
class Estimate(unittest.TestCase):
def test_the_a750_measurement(self):
# 8192 / int8 / reserve 400 was 473 MiB short; 4608 / q4_0 / reserve 0 started (without the draft layer's slack)
self.assertAlmostEqual(setup.unsloth_vram_slack_mib(8.0, 8192, "int8", 400), -473, delta=2)
self.assertGreaterEqual(setup.unsloth_vram_slack_mib(8.0, 4608, "q4_0", 0), 0)
def test_a_bigger_card_has_room(self):
self.assertGreater(setup.unsloth_vram_slack_mib(12.0, 32768, "int8", 700), setup.UD_FIT_MIN_SLACK_MIB)
def test_cuda_and_hip_pay_for_the_runtime_sycl_does_not(self):
self.assertEqual(setup.unsloth_runtime_mib({"driver": "i915"}), 0)
self.assertEqual(setup.unsloth_runtime_mib({"driver": "xe"}), 0)
self.assertEqual(setup.unsloth_runtime_mib({"driver": "580.97"}), setup.UD_FIT_RUNTIME_MIB)
self.assertEqual(setup.unsloth_runtime_mib({"driver": "amdgpu"}), setup.UD_FIT_RUNTIME_MIB)
class Plan(unittest.TestCase):
def test_a_card_that_fits_is_not_changed(self):
self.assertEqual(setup.unsloth_small_card_plan(10.0, 8192, "fp16", None)[:3], (8192, "fp16", True))
def test_8gb_drops_the_draft_layer_first(self):
# nothing else frees enough on 8 GB: the context and the KV alone do not fit with the draft layer
for kv in ("fp16", "int8"):
plan = setup.unsloth_small_card_plan(8.0, 8192, kv, 300)
self.assertIsNotNone(plan)
self.assertFalse(plan[2])
self.assertEqual(plan[:2], (8192, kv)) # the context and the KV the user would get are kept
self.assertGreaterEqual(plan[3], setup.UD_FIT_MIN_SLACK_MIB)
def test_a_card_just_short_changes_the_kv_before_the_context_before_the_draft(self):
# ~8.9 GB: the 4-bit KV is enough with the draft layer
vg = (setup.UD_FIT_FIXED_MIB + setup.UD_FIT_MTP_MIB + 8192 * 13 * 576 / 2 ** 20 + 300 + 80) / 1024
plan = setup.unsloth_small_card_plan(vg, 8192, "fp16", 300)
self.assertEqual(plan[:3], (8192, "q4_0", True))
# ... and a smaller context when the user fixed the KV
vg = (setup.UD_FIT_FIXED_MIB + setup.UD_FIT_MTP_MIB + 4608 * 13 * 2112 / 2 ** 20 + 300 + 80) / 1024
plan = setup.unsloth_small_card_plan(vg, 8192, "fp16", 300, kv_fixed=True)
self.assertEqual(plan[:3], (4608, "fp16", True))
def test_what_the_user_chose_is_not_changed(self):
plan = setup.unsloth_small_card_plan(8.0, 32768, "int8", 300, ctx_fixed=True, kv_fixed=True)
self.assertEqual(plan[:2], (32768, "int8"))
def test_a_6gb_card_has_no_plan(self):
self.assertIsNone(setup.unsloth_small_card_plan(6.0, 8192, "int8", None))
def test_a_reserve_the_user_gave_is_counted(self):
a = setup.unsloth_small_card_plan(8.0, 8192, "int8", 0)
b = setup.unsloth_small_card_plan(8.0, 8192, "int8", 1500)
self.assertGreater(a[3], b[3] if b else -1e9)
class Words(unittest.TestCase):
def test_always_says_to_pick_iq3(self):
lines = setup.unsloth_small_card_lines("UD-Q4_K_XL", 8.0, (8192, "int8", False, 400.0), False)
text = " ".join(lines)
self.assertIn("very slow", text)
self.assertIn("IQ3_XXS or IQ3_S", text)
def test_no_plan_says_the_start_will_probably_stop(self):
lines = setup.unsloth_small_card_lines("UD-Q4_K_XL", 6.0, None, False)
self.assertTrue(any("will probably" in x for x in lines))
class Main8GB(Base):
"""setup.main() for UD-Q4_K_XL on an 8 GB NVIDIA card: the written config is the one that starts."""
def arg(self, cfg, name):
return cfg["args"][cfg["args"].index(name) + 1]
def test_nvidia_8gb_writes_a_config_that_fits_and_says_so(self):
code, out, cfg = self.main(["--context", "8192"], vram=8.0)
self.assertEqual(code, 0, out)
self.assertNotIn("--mtp", cfg["args"]) # no draft layer on the GPU
self.assertEqual(self.arg(cfg, "--max-context"), "8192") # the context the user asked for
self.assertIn("would not start on this 8 GB card", out)
self.assertIn("no MTP draft layer", out)
self.assertIn("IQ3_XXS or IQ3_S", out)
self.assertIn("very slow", out)
def test_a_context_and_kv_the_user_chose_are_kept(self):
code, out, cfg = self.main(["--context", "16384", "--kv", "int8"], vram=8.0)
self.assertEqual(code, 0, out)
self.assertEqual(self.arg(cfg, "--max-context"), "16384")
self.assertEqual(self.arg(cfg, "--kv"), "int8")
def test_the_default_context_on_8gb_starts_without_asking(self):
code, out, cfg = self.main([], vram=8.0)
self.assertEqual(code, 0, out)
self.assertEqual(self.arg(cfg, "--max-context"), "8192")
self.assertNotIn("--mtp", cfg["args"])
def test_a_12gb_card_is_untouched(self):
code, out, cfg = self.main(["--context", "8192"], vram=11.9)
self.assertEqual(code, 0, out)
self.assertIn("--mtp", cfg["args"])
self.assertNotIn("would not start", out)
self.assertNotIn("very slow", out)
def test_amd_8gb(self):
r = [{"index": 0, "name": "AMD Radeon RX 7600", "vram_gb": 8.0, "arch": "gfx1102", "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"), mock.patch.object(setup, "hip_card", lambda eng, gpu, listed: gpu):
code, out, cfg = self.main(["--context", "8192", "--backend", "hip", "--vision", "no"], amd=r)
self.assertEqual(code, 0, out)
self.assertNotIn("--mtp", cfg["args"])
self.assertIn("IQ3_XXS or IQ3_S", out)
if __name__ == "__main__":
unittest.main()
-153
View File
@@ -1,153 +0,0 @@
"""#2054: BUILD.json is trusted only beside a binary of the source's version.
A build that stopped (nvcc rejecting a newer host gcc) once left the old engine next to a stamp of the new source, and
every later update said "engine already built for this PC" for good. `stale_binary` reads the version compiled into the
binary; `build_engine` refuses to stamp or install a binary of another version and compiles again when the installed
one is stale.
python -m unittest tools.test_setup_stale_stamp
"""
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
GPU = {"arch": 86, "archs": [86], "name": "RTX 3060"}
def binary(version: str | None) -> 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()
-40
View File
@@ -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()
-561
View File
@@ -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<N>/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()
-228
View File
@@ -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.<name> = <replacement>` in setup_intel.py must accept
all the parameters of setup.<name> (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()
-860
View File
@@ -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()
-208
View File
@@ -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-<model>.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()
-53
View File
@@ -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()
-671
View File
@@ -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()
-63
View File
@@ -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 "$@"