From 5ecc7fea17e54ce98924d6de353b66b56538100e Mon Sep 17 00:00:00 2001 From: 1872183316 <35711314+1872183316@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:34:05 +0200 Subject: [PATCH] setup: --inspect, a GGUF's real quantization and whether Strata runs it, from its headers only (#911) tools/quantscope.py (from 1872183316/quantscope, MIT OR Apache-2.0) reads only the headers (a file, a folder, a URL, ms: or hf: repositories); tools/strata_inspect.py compares them with data/gguf_fingerprints.json, the files setup installs. Changed from the PR: the size menu is untouched (its bits per weight line would change the golden output; left out), and the untested verdict says that setup still refuses the GGUF names it lists as unsupported, so the two do not contradict each other. (PR #911) --- data/gguf_fingerprints.json | 436 +++++++++++++++++++++++++++++++++++ docs/INSTALL.md | 8 +- setup.py | 5 + tools/quantscope.py | 394 +++++++++++++++++++++++++++++++ tools/strata_inspect.py | 176 ++++++++++++++ tools/test_strata_inspect.py | 63 +++++ 6 files changed, 1081 insertions(+), 1 deletion(-) create mode 100644 data/gguf_fingerprints.json create mode 100644 tools/quantscope.py create mode 100644 tools/strata_inspect.py create mode 100644 tools/test_strata_inspect.py diff --git a/data/gguf_fingerprints.json b/data/gguf_fingerprints.json new file mode 100644 index 00000000..2ab4fc2a --- /dev/null +++ b/data/gguf_fingerprints.json @@ -0,0 +1,436 @@ +{ + "qwen/Q2_0": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 66412853760, + "expert_bytes": { + "Q2_0": 33973862400 + }, + "experts_bpw": 2.25, + "bpw": 3.003, + "files": [ + "Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" + ], + "repo": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" + }, + "qwen/IQ2_XS": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 68015068160, + "expert_bytes": { + "IQ1_M": 1101004800, + "IQ2_S": 18271436800, + "IQ2_XXS": 4757913600, + "Q2_0": 11324620800 + }, + "experts_bpw": 2.348, + "bpw": 3.075, + "files": [ + "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf" + ], + "repo": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" + }, + "qwen/IQ3_XXS": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 75828974080, + "expert_bytes": { + "IQ2_S": 5373952000, + "IQ2_XS": 4849664000, + "IQ2_XXS": 3892838400, + "IQ3_S": 9371648000, + "IQ3_XXS": 3853516800, + "IQ4_NL": 8493465600, + "Q2_0": 7077888000 + }, + "experts_bpw": 2.842, + "bpw": 3.428, + "files": [ + "IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf" + ], + "repo": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" + }, + "qwen/IQ3_S": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 83606638080, + "expert_bytes": { + "IQ2_S": 10747904000, + "IQ3_S": 7208960000, + "IQ3_XXS": 10918297600, + "IQ4_NL": 18402508800, + "IQ4_XS": 891289600, + "Q2_0": 2123366400 + }, + "experts_bpw": 3.331, + "bpw": 3.78, + "files": [ + "IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf" + ], + "repo": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" + }, + "swift/Q2_0": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 66538928640, + "expert_bytes": { + "Q2_0": 33973862400 + }, + "experts_bpw": 2.25, + "bpw": 3.008, + "files": [ + "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" + ], + "repo": "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" + }, + "swift/IQ2_XS": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 68141143040, + "expert_bytes": { + "IQ1_M": 1101004800, + "IQ2_S": 18271436800, + "IQ2_XXS": 4757913600, + "Q2_0": 11324620800 + }, + "experts_bpw": 2.348, + "bpw": 3.081, + "files": [ + "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf" + ], + "repo": "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" + }, + "swift/IQ3_XXS": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 75955048960, + "expert_bytes": { + "IQ2_S": 5373952000, + "IQ2_XS": 4849664000, + "IQ2_XXS": 3892838400, + "IQ3_S": 9371648000, + "IQ3_XXS": 3853516800, + "IQ4_NL": 8493465600, + "Q2_0": 7077888000 + }, + "experts_bpw": 2.842, + "bpw": 3.434, + "files": [ + "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf" + ], + "repo": "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" + }, + "coder/IQ1_M": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 58397560320, + "expert_bytes": { + "IQ2_S": 5373952000, + "IQ3_S": 3604480000, + "IQ3_XXS": 5459148800, + "IQ4_NL": 9201254400, + "IQ4_XS": 445644800, + "Q2_0": 1061683200 + }, + "experts_bpw": 3.331, + "bpw": 4.01, + "files": [ + "IQ1_M/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf", + "IQ1_M/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf" + ], + "repo": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF" + }, + "unsloth/UD-IQ4_XS": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 93671559680, + "expert_bytes": { + "IQ3_S": 33882112000, + "IQ4_NL": 20289945600, + "IQ4_XS": 891289600, + "Q8_0": 4456448000 + }, + "experts_bpw": 3.942, + "bpw": 4.235, + "files": [ + "UD-IQ4_XS/Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf", + "UD-IQ4_XS/Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00003.gguf", + "UD-IQ4_XS/Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf" + ], + "repo": "unsloth/Qwen3.8-Flash-Next-GGUF" + }, + "unsloth/UD-Q4_K_XL": { + "arch": "qwen4exp", + "tensors": 1224, + "bytes": 111323630080, + "expert_bytes": { + "Q4_K": 44354764800, + "Q5_1": 27053260800, + "Q5_K": 1153433600, + "Q8_0": 4456448000 + }, + "experts_bpw": 5.101, + "bpw": 5.033, + "files": [ + "UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", + "UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf", + "UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf", + "UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf" + ], + "repo": "unsloth/Qwen3.8-Flash-Next-GGUF" + }, + "_roles": { + "blk.N.attn_gate.weight": [ + "IQ3_S", + "IQ4_XS", + "Q2_0", + "Q3_K", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "blk.N.attn_k.weight": [ + "IQ3_S", + "IQ4_XS", + "Q3_K", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "blk.N.attn_k_norm.weight": [ + "F32" + ], + "blk.N.attn_output.weight": [ + "IQ3_S", + "IQ4_XS", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "blk.N.attn_q.weight": [ + "IQ3_S", + "IQ4_XS", + "Q2_0", + "Q3_K", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "blk.N.attn_q_norm.weight": [ + "F32" + ], + "blk.N.attn_qkv.weight": [ + "IQ3_S", + "IQ4_XS", + "Q2_0", + "Q3_K", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "blk.N.attn_v.weight": [ + "IQ4_XS", + "Q3_K", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "blk.N.ffn_down_exps.weight": [ + "IQ4_NL", + "Q2_0", + "Q5_1", + "Q8_0" + ], + "blk.N.ffn_down_shexp.weight": [ + "IQ4_NL", + "Q2_0", + "Q4_0", + "Q5_0", + "Q8_0" + ], + "blk.N.ffn_gate_exps.weight": [ + "IQ1_M", + "IQ2_S", + "IQ2_XS", + "IQ2_XXS", + "IQ3_S", + "IQ3_XXS", + "IQ4_XS", + "Q2_0", + "Q4_K", + "Q5_K" + ], + "blk.N.ffn_gate_inp.weight": [ + "BF16", + "F32" + ], + "blk.N.ffn_gate_inp_shexp.weight": [ + "BF16", + "F32" + ], + "blk.N.ffn_gate_shexp.weight": [ + "IQ3_S", + "IQ4_XS", + "Q2_0", + "Q3_K", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "blk.N.ffn_up_exps.weight": [ + "IQ1_M", + "IQ2_S", + "IQ2_XS", + "IQ2_XXS", + "IQ3_S", + "IQ3_XXS", + "IQ4_XS", + "Q2_0", + "Q4_K", + "Q5_K" + ], + "blk.N.ffn_up_shexp.weight": [ + "IQ3_S", + "IQ4_XS", + "Q2_0", + "Q3_K", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "blk.N.hc_attn_down.weight": [ + "BF16", + "Q8_0" + ], + "blk.N.hc_attn_inject.weight": [ + "BF16", + "F32" + ], + "blk.N.hc_attn_norm.weight": [ + "F32" + ], + "blk.N.hc_attn_up.weight": [ + "BF16", + "Q8_0" + ], + "blk.N.hc_ffn_down.weight": [ + "BF16", + "Q8_0" + ], + "blk.N.hc_ffn_inject.weight": [ + "BF16", + "F32" + ], + "blk.N.hc_ffn_norm.weight": [ + "F32" + ], + "blk.N.hc_ffn_up.weight": [ + "BF16", + "Q8_0" + ], + "blk.N.indexer.k_norm.weight": [ + "F32" + ], + "blk.N.indexer.k_proj.weight": [ + "BF16" + ], + "blk.N.indexer.q_norm.weight": [ + "F32" + ], + "blk.N.indexer.q_proj.weight": [ + "BF16" + ], + "blk.N.ple_conv1d.weight": [ + "F16", + "F32" + ], + "blk.N.ple_key.weight": [ + "BF16", + "Q2_0", + "Q8_0" + ], + "blk.N.ple_norm_conv.weight": [ + "F32" + ], + "blk.N.ple_norm_key.weight": [ + "F32" + ], + "blk.N.ple_norm_query.weight": [ + "F32" + ], + "blk.N.ple_value.weight": [ + "BF16", + "Q8_0" + ], + "blk.N.ssm_a": [ + "F32" + ], + "blk.N.ssm_alpha.weight": [ + "BF16", + "F32" + ], + "blk.N.ssm_beta.weight": [ + "BF16", + "F32" + ], + "blk.N.ssm_conv1d.weight": [ + "F32" + ], + "blk.N.ssm_dt.bias": [ + "F32" + ], + "blk.N.ssm_norm.weight": [ + "F32" + ], + "blk.N.ssm_out.weight": [ + "IQ3_S", + "IQ4_XS", + "Q3_K", + "Q4_K", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "output.weight": [ + "IQ4_XS", + "Q5_K", + "Q6_K", + "Q8_0" + ], + "output_hc_down.weight": [ + "BF16", + "Q8_0" + ], + "output_hc_norm.weight": [ + "F32" + ], + "output_hc_up.weight": [ + "BF16", + "Q8_0" + ], + "per_layer_token_embd.weight": [ + "IQ4_NL" + ], + "token_embd.weight": [ + "IQ3_S", + "IQ4_XS", + "Q3_K", + "Q8_0" + ] + } +} diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 13c32f42..47c5b045 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -227,6 +227,7 @@ START-HERE.bat --setup install another model, or change SETUP.bat the same (double-click it) START-HERE.bat --model IQ2_XS --context 32768 --vision yes --yes no questions START-HERE.bat --gguf-dir D:\models\IQ2_XS use GGUF files you already have +START-HERE.bat --inspect D:\models\some.gguf what a GGUF really holds and whether Strata runs it (no download) START-HERE.bat --data-dir E:\Strata-data keep the model files somewhere else START-HERE.bat --port 8081 another port START-HERE.bat --gpu 1 another GPU (setup picks the one with the most VRAM) @@ -261,7 +262,12 @@ free the most. **Model files downloaded by hand, or from a mirror (#495):** setup's step 5 prints the folder it expects them in (`Strata-data\models\\`, e.g. `Strata-data\models\IQ3_XXS\`): put them there with their original names, or -point setup at them with `--gguf-dir`. To let setup download from a Hugging Face mirror itself, set `HF_ENDPOINT` +point setup at them with `--gguf-dir`. To see what a file really holds before using or downloading it, `--inspect` +reads only its headers (a few MB, also over the network: a file, a folder, a URL, `ms:owner/repo` for ModelScope or +`hf:owner/repo`): every weight group's real bits per weight and storage types, and whether it is one of the files setup +installs (under any name), stored like one of them, or not one Strata runs (another architecture, or experts in a +format no Strata kernel reads). A name says little: Unsloth's `UD-IQ3_XXS` stores its routed experts at 3.22 bits per +weight, `UD-Q4_K_XL` at 5.10, the original `Q2_0` at 2.25 and `IQ3_S` at 3.33. To let setup download from a Hugging Face mirror itself, set `HF_ENDPOINT` first (Windows: `set HF_ENDPOINT=https://hf-mirror.com`, Linux: `export HF_ENDPOINT=https://hf-mirror.com`): the same pinned revisions and checks apply, and the MTP draft layer comes from there too. diff --git a/setup.py b/setup.py index 924f58bb..9c219caa 100644 --- a/setup.py +++ b/setup.py @@ -4224,6 +4224,9 @@ def main() -> int: help="where the model files come from: auto (default: Hugging Face), huggingface or modelscope " "(mainland China: the same files, checked against ModelScope's published SHA-256; " "STRATA_SOURCE)") + ap.add_argument("--inspect", nargs="+", metavar=("SOURCE", "VARIANT"), + help="what a GGUF is and whether Strata runs it, from its headers only (no download): a file, a " + "folder, a URL, ms:owner/repo (ModelScope) or hf:owner/repo, and optionally a variant name") ap.add_argument("--cuda", choices=["12", "13", "auto"], default=os.environ.get("STRATA_CUDA") or None, help="NVIDIA: the CUDA toolkit of this model's engine. auto (default): CUDA 13, the ready-made " "engine; CUDA 12 (experimental) when a chosen card is older than CUDA 13 supports (Pascal, " @@ -4263,6 +4266,8 @@ def main() -> int: a = ap.parse_args() if a.source: os.environ["STRATA_SOURCE"] = a.source + if a.inspect: # headers only: nothing is installed + sys.exit(subprocess.run([sys.executable, str(ROOT / "tools" / "strata_inspect.py"), *a.inspect[:2]]).returncode) if a.backend == "sycl": # Intel Arc: the SYCL port's own setup (sycl/setup_intel.py) return sycl_setup(sys.argv[1:]) if a.resident_budget_gib is not None and not a.resident_budget_gib > 0: diff --git a/tools/quantscope.py b/tools/quantscope.py new file mode 100644 index 00000000..27af4ae5 --- /dev/null +++ b/tools/quantscope.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT OR Apache-2.0 +# From https://github.com/1872183316/quantscope (commit bfdf205), used by tools/strata_inspect.py and setup's --inspect. +"""quantscope: find the real quantization of a model without downloading it. + +Reads only file headers (a few MB per file, via HTTP range requests) of GGUF or safetensors +models on ModelScope, Hugging Face, any URL, or local disk, and reports the actual storage +type and bits per weight of every tensor group (routed experts, attention, embeddings, ...). +File names such as "IQ4_XS" or "Q4_K_XL" are recipe labels; the header is the ground truth. + +Examples: + python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF # list variants + python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF UD-Q4_K_XL # one variant + python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF --all # compare all variants + python quantscope.py hf:Qwen/Qwen3-30B-A3B-GPTQ-Int4 + python quantscope.py models/model-00001-of-00003.gguf +""" + +from __future__ import annotations + +import argparse +import fnmatch +import glob +import json +import os +import re +import struct +import sys +import urllib.request +from collections import defaultdict + +# ---------------------------------------------------------------- sources -------------------- + +HUBS = { + "ms": ("https://modelscope.cn/api/v1/models/{repo}/repo/files?Recursive=true", + "https://modelscope.cn/models/{repo}/resolve/master/{path}"), + "hf": ("https://huggingface.co/api/models/{repo}/tree/main?recursive=true", + "https://huggingface.co/{repo}/resolve/main/{path}"), +} +if os.environ.get("HF_ENDPOINT"): + base = os.environ["HF_ENDPOINT"].rstrip("/") + HUBS["hf"] = (base + "/api/models/{repo}/tree/main?recursive=true", + base + "/{repo}/resolve/main/{path}") + + +def http(url: str, start: int | None = None, end: int | None = None) -> bytes: + headers = {"User-Agent": "quantscope"} + if start is not None: + headers["Range"] = f"bytes={start}-{end}" + for attempt in range(5): + try: + with urllib.request.urlopen(urllib.request.Request(url, headers=headers), + timeout=60) as r: + return r.read() + except Exception as error: # noqa: BLE001 - network retries + if attempt == 4: + raise RuntimeError(f"{url}: {error}") from error + raise AssertionError + + +class Source: + """A file readable by byte ranges (remote or local) with a known size.""" + + def __init__(self, name: str, size: int, url: str | None = None, path: str | None = None): + self.name, self.size, self.url, self.path = name, size, url, path + + def read(self, start: int, length: int) -> bytes: + length = max(0, min(length, self.size - start)) + if length == 0: + return b"" + if self.path: + with open(self.path, "rb") as f: + f.seek(start) + return f.read(length) + return http(self.url, start, start + length - 1) + + +def list_hub(kind: str, repo: str) -> list[Source]: + list_url, file_url = HUBS[kind] + data = json.loads(http(list_url.format(repo=repo))) + out = [] + if kind == "ms": + for f in data["Data"]["Files"]: + if f.get("Type") == "blob": + out.append(Source(f["Path"], int(f.get("Size") or 0), + url=file_url.format(repo=repo, path=f["Path"]))) + else: + for f in data: + if f.get("type") == "file": + size = int((f.get("lfs") or {}).get("size") or f.get("size") or 0) + out.append(Source(f["path"], size, url=file_url.format(repo=repo, path=f["path"]))) + return out + + +def resolve(spec: str) -> list[Source]: + m = re.match(r"^(ms|hf):([^/]+/[^/:]+)$", spec) + if m: + return list_hub(m.group(1), m.group(2)) + if spec.startswith(("http://", "https://")): + head = urllib.request.Request(spec, method="HEAD", headers={"User-Agent": "quantscope"}) + with urllib.request.urlopen(head, timeout=60) as r: + size = int(r.headers.get("Content-Length") or 0) + return [Source(spec.rsplit("/", 1)[-1], size, url=spec)] + paths = [spec] if os.path.isfile(spec) else sorted( + glob.glob(os.path.join(spec, "**", "*"), recursive=True)) + return [Source(os.path.relpath(p, spec) if os.path.isdir(spec) else os.path.basename(p), + os.path.getsize(p), path=p) for p in paths if os.path.isfile(p)] + + +def variant_of(name: str) -> str: + """Groups the shards of one model file: strips -00001-of-00004 and the extension.""" + return re.sub(r"(-\d{5}-of-\d{5})?\.(gguf|safetensors|ninfer)$", "", name) + + +# ---------------------------------------------------------------- GGUF ----------------------- + +GGML_TYPES = { + 0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 6: "Q5_0", 7: "Q5_1", 8: "Q8_0", 9: "Q8_1", + 10: "Q2_K", 11: "Q3_K", 12: "Q4_K", 13: "Q5_K", 14: "Q6_K", 15: "Q8_K", 16: "IQ2_XXS", + 17: "IQ2_XS", 18: "IQ3_XXS", 19: "IQ1_S", 20: "IQ4_NL", 21: "IQ3_S", 22: "IQ2_S", + 23: "IQ4_XS", 24: "I8", 25: "I16", 26: "I32", 27: "I64", 28: "F64", 29: "IQ1_M", + 30: "BF16", 34: "TQ1_0", 35: "TQ2_0", 39: "MXFP4", + 42: "Q2_0", # ISTA-DASLab GSQ-RCO 2-bit (Strata, llama.cpp fork type) +} + + +class Buffered: + """Sequential reader over a remote header that fetches more bytes on demand.""" + + def __init__(self, src: Source, first: int = 4 << 20): + self.src, self.buf, self.pos = src, src.read(0, first), 0 + + def take(self, n: int) -> bytes: + while self.pos + n > len(self.buf): + if len(self.buf) >= self.src.size: + raise EOFError(f"{self.src.name}: truncated header") + self.buf += self.src.read(len(self.buf), max(len(self.buf), 4 << 20)) + out = self.buf[self.pos:self.pos + n] + self.pos += n + return out + + def u32(self) -> int: return struct.unpack(" int: return struct.unpack(" str: return self.take(self.u64()).decode("utf-8", "replace") + + +SCALAR = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8} + + +def gguf_value(r: Buffered, vtype: int): + if vtype == 8: + return r.string() + if vtype == 9: + itype, n = r.u32(), r.u64() + if itype == 8: + items = [r.string() for _ in range(n)] # must be consumed either way + return items if n <= 64 else None + if itype == 9: + raise ValueError("nested GGUF arrays are not supported") + size = SCALAR[itype] + r.take(size * n) + return None + raw = r.take(SCALAR[vtype]) + fmt = {0: " tuple[dict, list[dict]]: + r = Buffered(src) + if r.take(4) != b"GGUF": + raise ValueError(f"{src.name}: not a GGUF file") + r.u32() # version + n_tensors, n_kv = r.u64(), r.u64() + meta = {} + for _ in range(n_kv): + key = r.string() + meta[key] = gguf_value(r, r.u32()) + tensors = [] + for _ in range(n_tensors): + name = r.string() + dims = [r.u64() for _ in range(r.u32())] + ttype, offset = r.u32(), r.u64() + count = 1 + for d in dims: + count *= d + tensors.append({"name": name, "type": GGML_TYPES.get(ttype, f"type#{ttype}"), + "elements": count, "offset": offset}) + align = int(meta.get("general.alignment") or 32) + data_start = (r.pos + align - 1) // align * align + # Actual stored bytes from the offsets: exact for every type, including unknown ones. + order = sorted(tensors, key=lambda t: t["offset"]) + for a, b in zip(order, order[1:] + [None]): + end = b["offset"] if b else src.size - data_start + a["bytes"] = end - a["offset"] + return meta, tensors + + +# ---------------------------------------------------------------- safetensors ---------------- + +ST_BYTES = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2, "F8_E4M3": 1, "F8_E5M2": 1, "I64": 8, + "I32": 4, "I16": 2, "I8": 1, "U8": 1, "BOOL": 1, "F8_E8M0": 1, "U32": 4} +PACKED = re.compile(r"(qweight|weight_packed|\.blocks$|_blocks$)") + + +def read_safetensors(src: Source, bits: int | None) -> list[dict]: + n = struct.unpack(" list[dict]: + """Logical parameters of a NInfer v3 .ninfer entry, from its directory JSON only. + + A stored object may hold several logical parameters (for example an expert bank); each + binding's share of the object's stored bytes is proportional to its element range. + """ + head = src.read(0, 32) + magic, json_bytes, _artifact_id = struct.unpack("<8sQ16s", head) + if magic != NINFER_MAGIC: + raise ValueError(f"{src.name}: not a NInfer v3 entry") + directory = json.loads(src.read(32, json_bytes)) + objects = {o["id"]: o for o in directory["objects"] if o.get("kind", "tensor") == "tensor"} + elements = {} + for oid, o in objects.items(): + count = 1 + for d in o["shape"]: + count *= d + elements[oid] = count + out = [] + for name, binding in directory["bindings"].items(): + parts = ([{"object": binding["object"], "range": [0, elements.get(binding["object"], 0)]}] + if "object" in binding else binding.get("parts", [])) + count = nbytes = 0 + fmt = None + for part in parts: + o = objects.get(part["object"]) + if o is None: + continue + n = part["range"][1] - part["range"][0] + count += n + nbytes += o["bytes"] * n / max(elements[part["object"]], 1) + fmt = o["format"] + if count: + out.append({"name": name, "type": (fmt or "?").upper(), "elements": count, + "bytes": nbytes}) + return out + + +# ---------------------------------------------------------------- summary -------------------- + +CATEGORIES = [ + ("norms", r"(norm)"), + ("hyper-connections", r"(hc_|_hc\.|hyper_connection)"), + ("routed experts", r"(_exps\b|\.experts\.|experts\.\d+|block_sparse_moe\.experts)"), + ("shared experts", r"(_shexp|shared_expert|moe\.shared\.)"), + ("router", r"(ffn_gate_inp|\.gate\.weight$|\.router\b|shared_score)"), + ("n-gram/per-layer embeddings", r"(ngram|per_layer|ple_|\.ple\.)"), + ("linear attn/SSM", r"(ssm_|linear_attn|mamba|conv1d|\.gdn\.)"), + # GGUF also names GatedDeltaNet input projections attn_qkv/attn_gate. + ("attention (incl. GDN qkv/gate)", r"(attn|attention|self_attn|indexer|\.q_proj|\.k_proj|" + r"\.v_proj|\.o_proj)"), + ("dense FFN", r"(ffn_|\.mlp\.)"), + ("token embedding", r"(token_embd|embed_tokens|token_embedding|wte)"), + ("output head", r"(^output\.|lm_head|output_head)"), + ("MTP / nextn", r"(nextn|mtp)"), +] + + +def category(name: str) -> str: + n = name.lower().replace("/", ".") # NInfer logical names use slashes + for label, pattern in CATEGORIES: + if re.search(pattern, n): + return label + return "other" + + +def q_class(bpw: float) -> str: + for limit, label in [(1.9, "Q1 class"), (2.8, "Q2 class"), (3.7, "Q3 class"), + (4.9, "Q4 class"), (5.9, "Q5 class"), (7.5, "Q6 class"), + (10.0, "Q8 class"), (17.0, "16-bit")]: + if bpw < limit: + return label + return "32-bit" + + +def summarize(title: str, tensors: list[dict]) -> dict: + groups: dict[str, dict] = defaultdict(lambda: {"elements": 0, "bytes": 0, + "types": defaultdict(int)}) + for t in tensors: + g = groups[category(t["name"])] + g["elements"] += t["elements"] + g["bytes"] += t["bytes"] + g["types"][t["type"]] += t["bytes"] + total_e = sum(g["elements"] for g in groups.values()) + total_b = sum(g["bytes"] for g in groups.values()) + print(f"\n=== {title} ===") + print(f"total {total_b / 1e9:.2f} GB, {total_e / 1e9:.2f} B weights, " + f"{8 * total_b / max(total_e, 1):.2f} bits/weight overall") + print(f"{'group':30s} {'weights':>9s} {'GB':>8s} {'bits/w':>7s} types (share of bytes)") + for label, g in sorted(groups.items(), key=lambda kv: -kv[1]["bytes"]): + bpw = 8 * g["bytes"] / g["elements"] if g["elements"] else float("nan") + types = ", ".join(f"{k} {100 * v / g['bytes']:.0f}%" + for k, v in sorted(g["types"].items(), key=lambda kv: -kv[1])) + print(f"{label:30s} {g['elements'] / 1e9:8.2f}B {g['bytes'] / 1e9:8.2f} {bpw:7.2f} {types}") + experts = groups.get("routed experts") + verdict = None + if experts and experts["elements"]: + verdict = 8 * experts["bytes"] / experts["elements"] + print(f"-> routed experts are {verdict:.2f} bits/weight ({q_class(verdict)})") + return {"title": title, "gb": total_b / 1e9, "bpw": 8 * total_b / max(total_e, 1), + "experts_bpw": verdict} + + +def scan(label: str, files: list[Source], meta_config: dict | None) -> dict: + tensors: list[dict] = [] + for src in files: + if src.name.endswith(".gguf"): + _meta, ts = read_gguf(src) + elif src.name.endswith(".ninfer"): + ts = read_ninfer(src) + else: + bits = None + if meta_config: + q = meta_config.get("quantization_config") or {} + bits = q.get("bits") or q.get("w_bit") + ts = read_safetensors(src, bits) + tensors += ts + print(f" read header of {src.name}: {len(ts)} tensors", file=sys.stderr) + return summarize(label, tensors) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("source", help="ms:owner/repo, hf:owner/repo, URL, file or directory") + parser.add_argument("variant", nargs="?", help="variant name or glob (e.g. UD-Q4_K_XL)") + parser.add_argument("--all", action="store_true", help="scan and compare every variant") + args = parser.parse_args() + + files = [f for f in resolve(args.source) + if f.name.endswith((".gguf", ".safetensors", ".ninfer"))] + config = None + for f in resolve(args.source) if args.source.startswith(("ms:", "hf:")) else []: + if f.name == "config.json": + config = json.loads(http(f.url)) + if config.get("quantization_config"): + print("config.json quantization_config:", + json.dumps(config["quantization_config"])[:400]) + variants: dict[str, list[Source]] = defaultdict(list) + for f in files: + variants[variant_of(f.name)].append(f) + if not variants: + sys.exit("no .gguf, .safetensors or .ninfer files found") + if len(variants) > 1 and not args.variant and not args.all: + print("variants (pass one as the second argument, or --all):") + for name, fs in sorted(variants.items()): + print(f" {name:70s} {sum(f.size for f in fs) / 1e9:8.2f} GB {len(fs)} file(s)") + return + chosen = {k: v for k, v in variants.items() + if args.all or not args.variant or args.variant in k + or fnmatch.fnmatch(k, args.variant)} + results = [scan(name, sorted(fs, key=lambda f: f.name), config) + for name, fs in sorted(chosen.items())] + if len(results) > 1: + print("\n=== comparison ===") + print(f"{'variant':60s} {'GB':>8s} {'bits/w':>7s} {'experts bits/w':>15s}") + for r in results: + e = f"{r['experts_bpw']:.2f} ({q_class(r['experts_bpw'])})" if r["experts_bpw"] else "-" + print(f"{r['title']:60s} {r['gb']:8.2f} {r['bpw']:7.2f} {e:>15s}") + + +if __name__ == "__main__": + main() diff --git a/tools/strata_inspect.py b/tools/strata_inspect.py new file mode 100644 index 00000000..66cb727c --- /dev/null +++ b/tools/strata_inspect.py @@ -0,0 +1,176 @@ +"""Which Strata model a GGUF is - and whether Strata can run it - from its header alone. + +Reads only the files' headers (a few MB each, by HTTP range requests for a remote file) with quantscope, prints the +real storage of every weight group (bits per weight, quantization types), then compares the routed experts and the +sizes with the files setup installs (data/gguf_fingerprints.json): + + python tools/strata_inspect.py ms:ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF # list the variants + python tools/strata_inspect.py ms:ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF IQ3_S # one variant + python tools/strata_inspect.py ms:unsloth/Qwen3.8-Flash-Next-GGUF UD-Q2_K_XL + python tools/strata_inspect.py D:/models/my-copy-00001-of-00002.gguf # a local file or folder + python tools/strata_inspect.py https://example.com/x-00001-of-00002.gguf # one URL (that shard only) + +ms: is ModelScope, hf: Hugging Face (HF_ENDPOINT is honoured). setup.py --inspect runs the same. + python tools/strata_inspect.py --fingerprints data/gguf_fingerprints.json # remake the table +""" +from __future__ import annotations + +import argparse +import fnmatch +import re +import json +import sys +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import quantscope as qs # noqa: E402 + +FINGERPRINTS = ROOT / "data" / "gguf_fingerprints.json" +ARCH = "qwen4exp" # Qwen3.8-Flash-Next's general.architecture + +# the files setup installs: (family, model, ModelScope repository, file name prefix) - for --fingerprints +KNOWN = [ + ("qwen", "Q2_0", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Q2_0/"), + ("qwen", "IQ2_XS", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "IQ2_XS/"), + ("qwen", "IQ3_XXS", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "IQ3_XXS/"), + ("qwen", "IQ3_S", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "IQ3_S/"), + ("swift", "Q2_0", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0"), + ("swift", "IQ2_XS", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS"), + ("swift", "IQ3_XXS", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS"), + ("coder", "IQ1_M", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF", "IQ1_M/"), + ("unsloth", "UD-IQ4_XS", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-IQ4_XS/"), + ("unsloth", "UD-Q4_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q4_K_XL/"), +] + + +def read_headers(files: list) -> tuple[str | None, list[dict]]: + """The architecture and every tensor of a model's shards (headers only).""" + arch, tensors = None, [] + for f in files: + meta, ts = qs.read_gguf(f) + arch = arch or meta.get("general.architecture") + tensors += ts + return arch, tensors + + +def role(name: str) -> str: + """A tensor's name without its layer number: blk.7.ffn_down_exps.weight -> blk.N.ffn_down_exps.weight.""" + return re.sub(r"^blk\.\d+\.", "blk.N.", name) + + +def roles(tensors: list[dict]) -> dict[str, list[str]]: + out: dict[str, set] = defaultdict(set) + for t in tensors: + out[role(t["name"])].add(t["type"]) + return {k: sorted(v) for k, v in sorted(out.items())} + + +def fingerprint(arch: str | None, tensors: list[dict]) -> dict: + """What the comparison needs from a model's shards: architecture, tensor count, bytes, routed experts' bytes per + quantization type and their bits per weight.""" + n, total_b, total_e, exp_e = len(tensors), 0, 0, 0 + experts: dict[str, int] = defaultdict(int) + for t in tensors: + total_b += t["bytes"] + total_e += t["elements"] + if qs.category(t["name"]) == "routed experts": + experts[t["type"]] += t["bytes"] + exp_e += t["elements"] + return {"arch": arch, "tensors": n, "bytes": total_b, "expert_bytes": dict(sorted(experts.items())), + "experts_bpw": round(8 * sum(experts.values()) / exp_e, 3) if exp_e else None, + "bpw": round(8 * total_b / total_e, 3) if total_e else None, "roles": roles(tensors)} + + +def load_fingerprints(path: Path = FINGERPRINTS) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def verdict(fp: dict, table: dict) -> tuple[str, str]: + """(kind, sentence): kind is "known" (a file setup installs, under any name), "layout" (the same routed-expert + layout as one: a fine-tune made with the same recipe, untested), "no" (Strata cannot run it) or "untested" + (naming the tensors whose quantization no file Strata runs has for them).""" + known = {k: v for k, v in table.items() if not k.startswith("_")} + if fp["arch"] != ARCH: + return "no", f"not Qwen3.8-Flash-Next (architecture {fp['arch']!r}): Strata runs only that model" + exact = [k for k, v in known.items() if v["expert_bytes"] == fp["expert_bytes"] and v["bytes"] == fp["bytes"] + and v["tensors"] == fp["tensors"]] + if exact: + fam, model = exact[0].split("/") + return "known", f"this is setup's --family {fam} --model {model} (give its folder with --gguf-dir)" + same = [k for k, v in known.items() if v["expert_bytes"] == fp["expert_bytes"]] + if same: + return "layout", ("the routed experts are stored exactly as in " + " / ".join(same) + + ", but the file is not one setup knows (a fine-tune with the same recipe?): it may run as " + "that size; not tested") + runs = set().union(*(v["expert_bytes"] for v in known.values())) + other = sorted(set(fp["expert_bytes"]) - runs) + if other: + return "no", ("its routed experts use " + ", ".join(other) + ", a quantization no file Strata runs uses " + "(Strata's expert kernels cover " + ", ".join(sorted(runs)) + ")") + seen = table.get("_roles", {}) + new = [f"{r} {'/'.join(t for t in ts if t not in seen.get(r, []))}" for r, ts in fp.get("roles", {}).items() + if any(t not in seen.get(r, []) for t in ts)] + head = ("its routed experts use only quantizations Strata runs (" + ", ".join(fp["expert_bytes"]) + + "), but this file is not one setup installs: not tested (and setup still refuses the GGUF names " + "it lists as unsupported, such as UD-Q2_K_XL: this is a header reading, not a promise that it runs)") + if new: + return "untested", head + ". Stored differently from every file Strata runs: " + ", ".join(new) + return "untested", head + "; every tensor uses a quantization some file Strata runs has for it" + + +def make_fingerprints(out: Path) -> None: + listing, table = {}, {} + for fam, model, repo, prefix in KNOWN: + if repo not in listing: + listing[repo] = qs.list_hub("ms", repo) + files = sorted((f for f in listing[repo] if f.name.startswith(prefix) and f.name.endswith(".gguf")), + key=lambda f: f.name) + table[f"{fam}/{model}"] = {**fingerprint(*read_headers(files)), "files": [f.name for f in files], "repo": repo} + print(f"{fam}/{model}: experts {table[f'{fam}/{model}']['experts_bpw']} bits/weight", file=sys.stderr) + union: dict[str, set] = defaultdict(set) + for v in table.values(): + for r, ts in v.pop("roles").items(): + union[r] |= set(ts) + table["_roles"] = {r: sorted(ts) for r, ts in sorted(union.items())} # every quantization each tensor has + out.write_text(json.dumps(table, indent=1) + "\n", encoding="utf-8") + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("source", nargs="?", help="ms:owner/repo, hf:owner/repo, a URL, a .gguf file or a folder") + ap.add_argument("variant", nargs="?", help="a variant name or glob (e.g. IQ3_S, UD-Q2_K_XL)") + ap.add_argument("--fingerprints", metavar="OUT", help="read the files setup installs and write the table") + a = ap.parse_args() + if a.fingerprints: + make_fingerprints(Path(a.fingerprints)) + return + if not a.source: + ap.error("a source is needed") + files = [f for f in qs.resolve(a.source) if f.name.endswith(".gguf") and "mmproj" not in f.name.lower()] + variants: dict[str, list] = defaultdict(list) + for f in files: + variants[qs.variant_of(f.name)].append(f) + if not variants: + sys.exit("no model .gguf files there") + chosen = {k: v for k, v in variants.items() if not a.variant or a.variant in k or fnmatch.fnmatch(k, a.variant)} + if len(chosen) > 1: + print("variants (pass one as the second argument):") + for name, fs in sorted(chosen.items()): + print(f" {name:70s} {sum(f.size for f in fs) / 1e9:8.2f} GB {len(fs)} file(s)") + return + if not chosen: + sys.exit(f"no variant matches {a.variant!r}") + name, fs = next(iter(chosen.items())) + fs = sorted(fs, key=lambda f: f.name) + arch, tensors = read_headers(fs) + qs.summarize(name, tensors) + fp = fingerprint(arch, tensors) + kind, sentence = verdict(fp, load_fingerprints()) + print(f"\nStrata: {sentence}") + sys.exit(0 if kind in ("known", "layout") else 2 if kind == "no" else 0) + + +if __name__ == "__main__": + main() diff --git a/tools/test_strata_inspect.py b/tools/test_strata_inspect.py new file mode 100644 index 00000000..db375497 --- /dev/null +++ b/tools/test_strata_inspect.py @@ -0,0 +1,63 @@ +"""tools/strata_inspect.py's verdict, offline: the fingerprints of the files setup installs (data/gguf_fingerprints.json) +stand in for headers read from the network. + + python -m unittest tools.test_strata_inspect +""" +from __future__ import annotations + +import copy +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import strata_inspect as SI # noqa: E402 + + +class Verdict(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.table = SI.load_fingerprints() + + def fp(self, key): + return copy.deepcopy({k: v for k, v in self.table[key].items() if k not in ("files", "repo")}) + + def test_every_installed_file_is_known(self): + for key in (k for k in self.table if not k.startswith("_")): + kind, sentence = SI.verdict(self.fp(key), self.table) + fam, model = key.split("/") + self.assertEqual(kind, "known", key) + self.assertIn(f"--family {fam} --model {model}", sentence) + + def test_same_layout_other_file(self): + fp = self.fp("qwen/Q2_0") + fp["bytes"] += 1234 # a fine-tune with the same recipe + kind, sentence = SI.verdict(fp, self.table) + self.assertEqual(kind, "layout") + self.assertIn("qwen/Q2_0", sentence) + + def test_other_architecture(self): + fp = self.fp("qwen/Q2_0") + fp["arch"] = "qwen3moe" + self.assertEqual(SI.verdict(fp, self.table)[0], "no") + + def test_expert_type_without_kernel(self): + fp = self.fp("qwen/IQ3_S") + fp["expert_bytes"] = {"IQ1_S": 30_000_000_000} + kind, sentence = SI.verdict(fp, self.table) + self.assertEqual(kind, "no") + self.assertIn("IQ1_S", sentence) + + def test_untested_names_the_new_tensors(self): # Unsloth UD-Q2_K_XL's case: known expert types, a new head type + fp = self.fp("qwen/IQ3_XXS") + fp["expert_bytes"] = {"IQ2_XS": 1, "IQ3_XXS": 2, "IQ4_NL": 3} + fp["roles"] = {"output.weight": ["Q4_K"], "token_embd.weight": ["Q3_K"]} + kind, sentence = SI.verdict(fp, self.table) + self.assertEqual(kind, "untested") + self.assertIn("output.weight Q4_K", sentence) + self.assertNotIn("token_embd", sentence) + + +if __name__ == "__main__": + unittest.main()