Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
setup: Unsloth UD-Q4_K_XL as an experimental choice (--family unsloth) - the four shards pinned at 38bb39e with their sizes and SHA-256, a RAM budget of the PC's RAM less 24 GB, packed with --compat-bf16, engine 0.1.32 or newer
Niko1221242248ceedd8
diff --git a/README.md b/README.mdindex a4a55bba9..93bea0962 100644--- a/README.md+++ b/README.md@@ -87,6 +87,12 @@ one later with `SETUP.bat` (the same as `START-HERE.bat --setup`; on Linux `./seFor **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](docs/ORCA.md).It needs an explicit packing conversion and is not an installer menu option.+**Unsloth's 4-bit UD-Q4_K_XL** (experimental) is the fourth version in setup's menu (`--family unsloth`): the closest+to the full model, but a 111 GB download whose 77 GB of experts do not fit in RAM. Strata keeps your RAM minus 24 GB+of them in RAM and reads the rest from the SSD while it answers: 7-8.5 tokens/s on a 64 GB PC with a 12 GB GPU, several+times slower than the sizes above, and long prompts are slow. It needs 48 GB of RAM or more, an NVMe SSD and one+NVIDIA GPU (no images yet). Details and measurements: [UD-Q4_K_XL](docs/UNSLOTH_Q4.md).+An **AMD Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT or Radeon AI PRO R9700 on Linux** works too (experimental; theRX 7800 XT / 7700 XT and RX 9060 XT were validated by their owners):`./setup.sh --backend hip`, chosen by itself on a PC with no NVIDIA card Strata can use. It installs ROCm without sudo@@ -258,8 +264,9 @@ Want the full picture? The [details](docs/DETAILS.md#how-it-works) explain every- Model: [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team; compressed versions by[ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF);- [Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) by UkisAI. Their licenses apply- to the model files.+ [Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) by UkisAI; the experimental+ [UD-Q4_K_XL](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF) by Unsloth (its support follows+ [eddoursul/Strata](https://github.com/eddoursul/Strata)). Their licenses apply to the model files.- Built with parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) (MIT). Ideas from[Splash](https://github.com/incoai/splash), [ninfer](https://github.com/Neroued/ninfer) and[HyperQwen](https://github.com/syv-ai/HyperQwen). More in the [details](docs/DETAILS.md#credits-and-licenses).diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex a17862a40..4cde380c9 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -221,10 +221,11 @@ thought about for 1,524 tokens. Not a benchmark, but consistent with the claim.START-HERE.bat --setup --family swift --model IQ2_XS```-### Experimental: Unsloth's UD-Q4_K_XL (manual import)+### Experimental: Unsloth's UD-Q4_K_XL-A 4-bit quantization of the same model (111 GB, 72 GiB of experts). Not in setup: packing it and the server-configuration are in **[docs/UNSLOTH_Q4.md](UNSLOTH_Q4.md)**. On a 64 GB PC with a 12 GB RTX 5070 it writes 7-8.5+A 4-bit quantization of the same model (111 GB, 72 GiB of experts). Setup offers it from engine 0.1.32+(`--family unsloth --model UD-Q4_K_XL`: a RAM budget of your RAM less 24 GB, the rest read from the SSD); what it+does and the manual workflow are in **[docs/UNSLOTH_Q4.md](UNSLOTH_Q4.md)**. On a 64 GB PC with a 12 GB RTX 5070 it writes 7-8.5tokens/s, most experts read from the SSD; it picks the same tokens as llama.cpp on the same file at 97.5-99% ofthe positions of short greedy answers, 90-91% after a 16K prompt, differing mostly at near-ties([measured](UNSLOTH_Q4.md#quality-against-llamacpp-on-the-same-file)).diff --git a/docs/UNSLOTH_Q4.md b/docs/UNSLOTH_Q4.mdindex dde5e110c..31d254396 100644--- a/docs/UNSLOTH_Q4.md+++ b/docs/UNSLOTH_Q4.md@@ -1,8 +1,8 @@-# Unsloth UD-Q4_K_XL (experimental, manual import)+# Unsloth UD-Q4_K_XL (experimental)-**Experimental, not in setup yet.** Engine 0.1.31 or newer. Validated on one PC: Windows 10, an RTX 5070 (12 GB),-64 GB of RAM and an AVX-512 CPU, on 2026-10-01. Everything below is a manual workflow; `START-HERE.bat` / `setup.sh`-do not offer this model.+**Experimental.** Setup offers it from engine 0.1.32 ([below](#setup)); the manual workflow after that section works+with engine 0.1.31 or newer. Validated on one PC: Windows 10, an RTX 5070 (12 GB), 64 GB of RAM and an AVX-512 CPU,+on 2026-10-01.The target is Unsloth's 4-bit quantization of the same model the other packs use:[unsloth/Qwen3.8-Flash-Next-GGUF, `UD-Q4_K_XL`, revision `38bb39e`](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/tree/38bb39ee97821de2c9009abb7e93950eec396e66/UD-Q4_K_XL).@@ -11,6 +11,28 @@ Q5_1 (Q8_0 in layers 2, 4, 30, 46, 47) for down; the token embedding, the outputprojections and the PLE key are Q8_0; the 28.8 GB PLE table is IQ4_NL. The routed experts are 71.7 GiB, about twicethe 3-bit models'.+## Setup++`START-HERE.bat --setup` (Linux: `./setup.sh --setup`) and choose **Qwen3.8-Flash-Next (Unsloth)**, marked+`[experimental]`; or directly:++```sh+START-HERE.bat --setup --family unsloth --model UD-Q4_K_XL+```++What setup does differently for this model:++- It needs 48 GB of RAM or more and engine 0.1.32 or newer (checked before anything is downloaded), and an NVIDIA+ GPU. One GPU only: with `--gpus` it uses the first one and says so. No images (the vision encoder is not wired to+ this file yet) and no experimental speed projection (not tested with it).+- It downloads the four shards below from the pinned revision `38bb39e` (resumable, like the other models), then+ checks each one's size and SHA-256 against the table below; the check takes a few minutes once and is remembered+ in the file's finish mark. A file with the wrong hash is deleted, so the next run downloads it again.+- It packs with `--compat-bf16` and never writes `experts.bin` (`--low-ram` does not apply).+- The RAM budget is the PC's RAM less 24 GB: `--resident-budget-gib 40` on 64 GB, at most all 71 GiB of experts on+ 96 GB or more. From a 64K context up, where the KV cache moves to RAM, its size comes out of the budget.+- It recommends an 8K context on a GPU under 14 GB (every GB of KV cache is a GB less of cached experts).+## The filesFour shards, 111,334,654,784 bytes (111.3 GB) together. Shard 1 holds only the metadata; layer 11's down projection is@@ -24,7 +46,8 @@ in shard 2 and its gate/up in shard 3, which this engine handles (`native_expert| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf` | 12,087,983,520 | `753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a` |Keep the four files together in one folder under these names (the engine finds shards 2-4 from shard 1's name; a-missing shard is an error that names it). Check them before packing (`sha256sum -c`, or `Get-FileHash` on Windows).+missing shard is an error that names it). Setup checks them itself; by hand, check them before packing+(`sha256sum -c`, or `Get-FileHash` on Windows).Hugging Face snapshot symlinks work if you pass the snapshot's file name, not the hash-named blob it points to.## What it needs@@ -35,7 +58,7 @@ Hugging Face snapshot symlinks work if you pass the snapshot's file name, not th| RAM | 64 GB measured. The RAM budget (below) holds the most-used experts; the rest come from the SSD through the OS file cache. || GPU | 12 GB measured (RTX 5070): after the weights, the draft layer and the buffers, the expert cache held 1,280 of the 24,576 experts (3.7 GiB) at 4K context. |-## The pack+## The pack (by hand)Build Strata (or install 0.1.31+), then, from the repository root, with gguf-py from the pinned llama.cpp(setup installs it; `STRATA_GGUF_PY` can point to its `gguf-py` folder):diff --git a/setup.py b/setup.pyindex eac1f554d..33e87c7ab 100644--- a/setup.py+++ b/setup.py@@ -35,6 +35,7 @@ import argparseimport ctypesimport hashlibimport json+import mathimport osimport platformimport re@@ -57,6 +58,7 @@ HF_REVISIONS = {"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", # 2026-09-29"ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "b22d729eae29b5796f76fb70f91aef549b9fc52c", # 2026-09-24"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF": "5348543e0147355ac9cbcb031184a3546350988e", # 2026-09-29+ "unsloth/Qwen3.8-Flash-Next-GGUF": "38bb39ee97821de2c9009abb7e93950eec396e66", # 2026-09-30}@@ -104,7 +106,26 @@ MODELS = {# the Coder release: 256 of the 512 experts kept (the ones code, tools and vision use), IQ2_S-IQ4_XS like IQ3_S"IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4,"ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)},+ # EXPERIMENTAL (docs/UNSLOTH_Q4.md): Unsloth's 4-bit file; its 77 GB of experts do not fit a 64 GB PC, so the engine+ # keeps a RAM budget of them (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD+ "UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), EXPERIMENTAL: the best quality, but most experts come from the "+ "SSD on a 64 GB PC (7-8.5 tokens/s measured)", "download_gb": 111.3, "ram_gb": 48,+ "arena_gb": 77.0, "families": ("unsloth",), "budget": True},}+# The experimental Unsloth file's four shards at the pinned revision: name -> (bytes, sha256), checked after the+# download (setup trusts no other model file by name and size alone either: check_shards reads their directories).+UNSLOTH_SHARDS = {+ "Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf":+ (10946624, "4448186216b3af4cc558bbce2c3213f01608f8f8b2e5267a9767971dd3ec8082"),+ "Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf":+ (49859583136, "3f342f1c1580473f1ee94ddd5b28206e8c07a70fa1a366f59d1d6c922919a6c9"),+ "Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf":+ (49376141504, "56758f40269cad5cd9b0d3d6fbae0f40f6d5be6de49e4ab392dbe83157d9cbd3"),+ "Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf":+ (12087983520, "753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a"),+}+UNSLOTH_ENGINE = (0, 1, 32) # the first engine setup configures for UD-Q4_K_XL (0.1.31 ran it by hand)+UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and the file cache the rest is read through# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor# from the final context (final / 262144, at least 1) itself (below), keeps an explicit@@ -135,6 +156,14 @@ FAMILIES = {"mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF"),"mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-coder","profile": "expert-profile-coder.bin"},+ # EXPERIMENTAL: Unsloth's UD-Q4_K_XL of the original model (docs/UNSLOTH_Q4.md): four shards, no images yet+ "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's 4-bit quantization (EXPERIMENTAL)",+ "about": "4-bit, 111 GB download, most experts read from the SSD: slow (7-8.5 tokens/s on a 64 GB PC)",+ "hf": hf("unsloth/Qwen3.8-Flash-Next-GGUF") + "{q}/",+ "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf", "shards": 4, "tag": "unsloth-",+ "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"),+ "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-unsloth",+ "experimental": True, "vision": False, "pack_args": ["--compat-bf16"], "sha256": UNSLOTH_SHARDS},}MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf"# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README@@ -684,6 +713,39 @@ def whole_shard(s: Path) -> bool:return False+def verify_sha256(s: Path, size: int, sha: str) -> None:+ """A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark,+ so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again."""+ m = s.with_name(s.name + ".done")+ if m.exists() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace"):+ return+ have = s.stat().st_size if s.exists() else -1+ if have != size:+ fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)")+ say(f" checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...")+ h = hashlib.sha256()+ with open(s, "rb") as f:+ while True:+ b = f.read(16 << 20)+ if not b:+ break+ h.update(b)+ if h.hexdigest() != sha:+ s.unlink(missing_ok=True)+ m.unlink(missing_ok=True)+ fail(f"{s.name} has the wrong SHA-256 ({h.hexdigest()}, expected {sha}): deleted",+ "run setup again to download it again")+ mark(s, f"sha256 {sha}")+++def resident_budget_gib(model, ram, kv_ram_gb=0.0) -> int:+ """UD-Q4_K_XL: the GiB of experts the engine keeps in RAM (--resident-budget-gib): the RAM (GiB, ram_gb()) less+ 24 for the OS, the engine and the file cache the other experts are read through, less a KV cache streamed to+ RAM; at most all of them, at least 8. 64 GB: 40, the measured setting (docs/UNSLOTH_Q4.md)."""+ gib = round(ram) - UNSLOTH_RAM_LEFT_GB - math.ceil(kv_ram_gb)+ return max(8, min(gib, int(MODELS[model]["arena_gb"] / 1.073741824)))++def check_shards(shards):"""Every shard present and whole, or setup stops naming the file and the numbers. Whole means as long asits own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part@@ -1583,7 +1645,9 @@ def choices_from_config(cfg_path: Path) -> dict:cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))tag = cfg_path.stem[len("strata-"):]family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen")- model = tag.split("-")[-1].upper()+ model = (tag[len(FAMILIES[family]["tag"]):] if tag.startswith(FAMILIES[family]["tag"]) else tag).upper()+ if model not in MODELS: # (sizes have no dash except UD-Q4_K_XL: the old rule)+ model = tag.split("-")[-1].upper()a = cfg.get("args", [])val = lambda k: a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None # noqa: E731vis = cfg.get("vision")@@ -2125,7 +2189,10 @@ def main() -> int:say()for m, d in MODELS.items():verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit"- if low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off":+ if d.get("budget"):+ verdict = (f"EXPERIMENTAL, fits with {resident_budget_gib(m, ram)} GiB of its experts in RAM, the rest "+ "read from the SSD" if ram >= d["ram_gb"] else "does not fit")+ elif low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off":verdict = (f"fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}% ""of its experts, " + ("the rest stays in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"])else "the rest is read from the SSD as needed)"))@@ -2141,7 +2208,7 @@ def main() -> int:else:for i, f in enumerate(fams, 1):d = FAMILIES[f]- say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}")+ say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}" + (" [experimental]" if d.get("experimental") else ""))family = fams[int(ask("Which model?", [str(i) for i in range(1, len(fams) + 1)], "1", a.yes)) - 1]fam = FAMILIES[family]ok(f"model: {fam['title']}")@@ -2154,25 +2221,48 @@ def main() -> int:for i, m in enumerate(names, 1):d = MODELS[m]fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"+ if d.get("budget"):+ say(f" {i}) {m} {d['about']}; download {d['download_gb']:.0f} GB, keeps ~"+ f"{resident_budget_gib(m, ram)} GB of its {d['arena_gb']:.0f} GB of experts in RAM{fit}")+ continueif low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off":fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}%, "+ ("the rest in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) else "the rest from the SSD)"))say(f" {i}) {m:8s} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}")rec = str(names.index("IQ3_XXS") + 1) if ram >= 60 and "IQ3_XXS" in names else "1"model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1]- low_ram = a.low_ram in ("on", "resident", "mmap") or (a.low_ram == "auto" and low_ram_needed(model, ram))+ budget = None+ if MODELS[model].get("budget"):+ # Unsloth's UD-Q4_K_XL: a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM mode (no+ # experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode has no layer split)+ warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md): most of its experts are read from the SSD while it "+ "answers, so it is several times slower than the 2-3-bit models; quality checked against llama.cpp")+ if ram < MODELS[model]["ram_gb"]:+ fail(f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB",+ "choose one of the 2-3-bit models")+ budget = resident_budget_gib(model, ram)+ ok(f"RAM budget: {budget} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD")+ if a.low_ram not in ("auto", "off"):+ warn(f"--low-ram {a.low_ram} does not apply to {model}: it always reads part of its experts from the files")+ if multi:+ warn(f"{model} runs on one GPU: using " + gpu_name(gpu) + " only")+ multi, sel, chosen = [], [gpu["index"]], [gpu]+ low_ram = budget is None and (a.low_ram in ("on", "resident", "mmap") or+ (a.low_ram == "auto" and low_ram_needed(model, ram)))if low_ram and multi:warn("the low-RAM mode runs on one GPU: using " + gpu_name(gpu) + " only")for line in low_ram_one_gpu_why(model, ram, a.low_ram):say(" " + line)multi, sel, chosen = [], [gpu["index"]], [gpu]# (the low-RAM mode's variant is decided once the context is known, below)- if not low_ram and ram < MODELS[model]["ram_gb"] - 4:+ if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4:confirm_paging(model, ram, a.low_ram, a.yes)ok(f"size: {model}")tag = fam["tag"] + model # names of the pack, config and start scriptsmall = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole contextrec_ctx = 32768 if small < 14 else 65536 if small < 20 else 131072+ if budget is not None: # UD-Q4_K_XL: every GB of KV is a GB fewer of cached experts+ rec_ctx = 8192 if small < 14 else 32768if a.context:ctx = a.contextelse:@@ -2229,10 +2319,10 @@ def main() -> int:kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1]if ctx > 8192:ok(f"KV cache: {'8-bit' if kv == 'int8' else '4-bit (Hadamard-rotated)'}")- if hip:+ if hip or fam.get("vision") is False:vision = "none"if a.vision not in (None, "no", "none"):- warn("images are not available with the AMD backend yet: off")+ warn("images are not available " + ("with the AMD backend" if hip else f"with {model}") + " yet: off")elif a.vision:vision = {"yes": "gpu", "no": "none"}.get(a.vision, a.vision)else:@@ -2280,9 +2370,10 @@ def main() -> int:fail(f"the experimental speed projection's vector is missing: {esp}")ok("experimental speed projection: " + ("ON (experimental)" if esp else "off"))elif esp_choice.lower() not in ("", "off", "no", "n", "0"):- warn("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off")+ warn("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off"+ if family == "swift" else f"the experimental speed projection is not tested with {model}: left off")models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag- shards = [models_dir / fam["file"].format(q=model, i=i) for i in (1, 2)]+ shards = [models_dir / fam["file"].format(q=model, i=i) for i in range(1, fam.get("shards", 2) + 1)]if not a.gguf_dir and not all(sh.exists() and done(sh) for sh in shards):for r in elsewhere: # already downloaded in a Strata folder on another drivecand = [r / "models" / tag / sh.name for sh in shards]@@ -2325,6 +2416,10 @@ def main() -> int:eng = build_engine_hip(gpu, llama) if hip else build_engine(gpu, vision, a.yes, llama)meta = json.loads((eng / "BUILD.json").read_text())lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs()+ engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit())+ if budget is not None and engine_ver < UNSLOTH_ENGINE: # checked before the 111 GB download+ fail(f"{model} needs engine {'.'.join(map(str, UNSLOTH_ENGINE))} or newer; this one is {meta.get('version')}",+ "update Strata (or compile the engine with --build) and run setup again")ok(f"engine: {eng / EXE}")# ---- 5. the model files@@ -2346,6 +2441,9 @@ def main() -> int:passdownload(fam["hf"].format(q=model) + s.name, s)check_shards(shards)+ for s in shards: # the experimental Unsloth file: pinned sizes and SHA-256+ if s.name in fam.get("sha256", {}):+ verify_sha256(s, *fam["sha256"][s.name])ok("model files present")mmproj = Path(a.models_dir) / fam["mmproj"]if not mmproj.exists():@@ -2373,7 +2471,9 @@ def main() -> int:"--out", str(pack)], env=env) # writes <pack>/tokenizer/elif not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists():# every tensor as the GGUF stores it; the experts are read from the GGUF at start (seconds to build)- run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack)], env=env)+ # (UD-Q4_K_XL: --compat-bf16 - its Q8_0 hyper-connection projections become BF16, the form the engine reads)+ run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack),+ *fam.get("pack_args", [])], env=env)if low_ram and not (pack / "experts.bin").exists():say(f" Writing the experts into one file for the low-RAM mode (one time, {MODELS[model]['arena_gb']:.0f} GB) ...")run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack),@@ -2399,7 +2499,8 @@ def main() -> int:ple = next((s for s in shards if any(t.name == "per_layer_token_embd.weight" for t in GGUFFile(s).tensors)), None)if ple is None:fail("the model has no per_layer_token_embd tensor (is this a Qwen3.8-Flash-Next GGUF?)")- args = ["--pack", str(pack), "--native", str(shards[0]), "--ple-gguf", str(ple),+ # (a 4-shard file: the engine finds the PLE table's shard itself from shard 1, the measured setup)+ args = ["--pack", str(pack), "--native", str(shards[0]), *(["--ple-gguf", str(ple)] if len(shards) <= 2 else []),"--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto","--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt),"--max-context", str(ctx)]@@ -2407,7 +2508,6 @@ def main() -> int:args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"]if ctx > 8192:args += ["--kv", kv]- engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit())if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE:resident = False # an engine from before --resident-experts would refuse itok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through "@@ -2429,6 +2529,11 @@ def main() -> int:elif ctx >= 65536 and ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1:args += ["--kv-resident", "32768"]ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM")+ if budget is not None: # its RAM comes out of the experts' budget+ budget = resident_budget_gib(model, ram, kv_ram_gb)+ ok(f"RAM budget: {budget} GiB (less the KV cache's RAM)")+ if budget is not None: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N GiB kept in RAM+ args += ["--resident-budget-gib", str(budget)]if vision != "none":args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])]if esp is not None:diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.pynew file mode 100644index 000000000..307a51a77--- /dev/null+++ b/tools/test_setup_unsloth.py@@ -0,0 +1,260 @@+"""Tests for setup.py's experimental Unsloth UD-Q4_K_XL choice (docs/UNSLOTH_Q4.md): 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"+++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.assertTrue(fam["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 Main(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):+ 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": 11.9, "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: []),+ mock.patch.object(setup, "ram_gb", lambda: ram),+ mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, True)),+ 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", 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", "--model", M, "--yes", "--no-start",+ "--models-dir", str(self.t / "models"), *argv]),+ mock.patch("builtins.input", mock.Mock(side_effect=AssertionError("asked"))),+ ]+ with contextlib.ExitStack() as st:+ for p in patches:+ st.enter_context(p)+ code, out = quiet(setup.main)+ cfg = self.t / "strata-unsloth-ud-q4_k_xl.json"+ return code, out, (json.loads(cfg.read_text()) if cfg.exists() else None)++ def test_install(self):+ code, out, cfg = self.main(["--context", "8192"])+ self.assertEqual(code, 0, out)+ self.assertIn("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")++ 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)+ self.assertEqual(code, 1)+ self.assertIn("needs 48 GB of RAM or more", out)+ self.assertEqual(self.downloads, [])++ def test_one_gpu_and_no_images(self):+ code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--vision", "yes", "--low-ram", "on"],+ n_gpus=2)+ self.assertEqual(code, 0, out)+ self.assertIn("runs on one GPU", out)+ self.assertIn("images are not available with UD-Q4_K_XL", out)+ self.assertIn("--low-ram on does not apply", out)+ self.assertNotIn("layer_split", cfg)+ self.assertNotIn("--vision", cfg["args"])+ self.assertNotIn("--mmap-experts", cfg["args"])+ self.assertFalse(any("--experts-bin" in r for r in self.runs))+++if __name__ == "__main__":+ unittest.main()