okami.mom/strata

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

Niko1221Merge f-split-tuiqa (95f380769) into f-split-int: TUI QA fixes (launch with flags, discovery, monitor menu, connect checks, layouts, no browser, warnings), picture reader CPU under 24 GB / GPU from 24 GBfd0e3766a

main
16.6 KiB395 linesraw
1#!/usr/bin/env python3
2# SPDX-License-Identifier: MIT OR Apache-2.0
3# From https://github.com/1872183316/quantscope (commit bfdf205), used by tools/strata_inspect.py and setup's --inspect.
4"""quantscope: find the real quantization of a model without downloading it.
5
6Reads only file headers (a few MB per file, via HTTP range requests) of GGUF or safetensors
7models on ModelScope, Hugging Face, any URL, or local disk, and reports the actual storage
8type and bits per weight of every tensor group (routed experts, attention, embeddings, ...).
9File names such as "IQ4_XS" or "Q4_K_XL" are recipe labels; the header is the ground truth.
10
11Examples:
12  python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF              # list variants
13  python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF UD-Q4_K_XL   # one variant
14  python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF --all        # compare all variants
15  python quantscope.py hf:Qwen/Qwen3-30B-A3B-GPTQ-Int4
16  python quantscope.py models/model-00001-of-00003.gguf
17"""
18
19from __future__ import annotations
20
21import argparse
22import fnmatch
23import glob
24import json
25import os
26import re
27import struct
28import sys
29import urllib.request
30from collections import defaultdict
31
32# ---------------------------------------------------------------- sources --------------------
33
34HUBS = {
35    "ms": ("https://modelscope.cn/api/v1/models/{repo}/repo/files?Recursive=true",
36           "https://modelscope.cn/models/{repo}/resolve/master/{path}"),
37    "hf": ("https://huggingface.co/api/models/{repo}/tree/main?recursive=true",
38           "https://huggingface.co/{repo}/resolve/main/{path}"),
39}
40if os.environ.get("HF_ENDPOINT"):
41    base = os.environ["HF_ENDPOINT"].rstrip("/")
42    HUBS["hf"] = (base + "/api/models/{repo}/tree/main?recursive=true",
43                  base + "/{repo}/resolve/main/{path}")
44
45
46def http(url: str, start: int | None = None, end: int | None = None) -> bytes:
47    headers = {"User-Agent": "quantscope"}
48    if start is not None:
49        headers["Range"] = f"bytes={start}-{end}"
50    for attempt in range(5):
51        try:
52            with urllib.request.urlopen(urllib.request.Request(url, headers=headers),
53                                        timeout=60) as r:
54                return r.read()
55        except Exception as error:  # noqa: BLE001 - network retries
56            if attempt == 4:
57                raise RuntimeError(f"{url}: {error}") from error
58    raise AssertionError
59
60
61class Source:
62    """A file readable by byte ranges (remote or local) with a known size."""
63
64    def __init__(self, name: str, size: int, url: str | None = None, path: str | None = None):
65        self.name, self.size, self.url, self.path = name, size, url, path
66
67    def read(self, start: int, length: int) -> bytes:
68        length = max(0, min(length, self.size - start))
69        if length == 0:
70            return b""
71        if self.path:
72            with open(self.path, "rb") as f:
73                f.seek(start)
74                return f.read(length)
75        return http(self.url, start, start + length - 1)
76
77
78def list_hub(kind: str, repo: str) -> list[Source]:
79    list_url, file_url = HUBS[kind]
80    data = json.loads(http(list_url.format(repo=repo)))
81    out = []
82    if kind == "ms":
83        for f in data["Data"]["Files"]:
84            if f.get("Type") == "blob":
85                out.append(Source(f["Path"], int(f.get("Size") or 0),
86                                  url=file_url.format(repo=repo, path=f["Path"])))
87    else:
88        for f in data:
89            if f.get("type") == "file":
90                size = int((f.get("lfs") or {}).get("size") or f.get("size") or 0)
91                out.append(Source(f["path"], size, url=file_url.format(repo=repo, path=f["path"])))
92    return out
93
94
95def resolve(spec: str) -> list[Source]:
96    m = re.match(r"^(ms|hf):([^/]+/[^/:]+)$", spec)
97    if m:
98        return list_hub(m.group(1), m.group(2))
99    if spec.startswith(("http://", "https://")):
100        head = urllib.request.Request(spec, method="HEAD", headers={"User-Agent": "quantscope"})
101        with urllib.request.urlopen(head, timeout=60) as r:
102            size = int(r.headers.get("Content-Length") or 0)
103        return [Source(spec.rsplit("/", 1)[-1], size, url=spec)]
104    paths = [spec] if os.path.isfile(spec) else sorted(
105        glob.glob(os.path.join(spec, "**", "*"), recursive=True))
106    return [Source(os.path.relpath(p, spec) if os.path.isdir(spec) else os.path.basename(p),
107                   os.path.getsize(p), path=p) for p in paths if os.path.isfile(p)]
108
109
110def variant_of(name: str) -> str:
111    """Groups the shards of one model file: strips -00001-of-00004 and the extension."""
112    return re.sub(r"(-\d{5}-of-\d{5})?\.(gguf|safetensors|ninfer)$", "", name)
113
114
115# ---------------------------------------------------------------- GGUF -----------------------
116
117GGML_TYPES = {
118    0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 6: "Q5_0", 7: "Q5_1", 8: "Q8_0", 9: "Q8_1",
119    10: "Q2_K", 11: "Q3_K", 12: "Q4_K", 13: "Q5_K", 14: "Q6_K", 15: "Q8_K", 16: "IQ2_XXS",
120    17: "IQ2_XS", 18: "IQ3_XXS", 19: "IQ1_S", 20: "IQ4_NL", 21: "IQ3_S", 22: "IQ2_S",
121    23: "IQ4_XS", 24: "I8", 25: "I16", 26: "I32", 27: "I64", 28: "F64", 29: "IQ1_M",
122    30: "BF16", 34: "TQ1_0", 35: "TQ2_0", 39: "MXFP4",
123    42: "Q2_0",  # ISTA-DASLab GSQ-RCO 2-bit (Strata, llama.cpp fork type)
124    143: "PTQ1_0", 144: "TQ2_T", 145: "TQK6", 146: "TQK7",  # agentionai Gyro (tools/gguf_reader.py has the block sizes)
125}
126
127
128class Buffered:
129    """Sequential reader over a remote header that fetches more bytes on demand."""
130
131    def __init__(self, src: Source, first: int = 4 << 20):
132        self.src, self.buf, self.pos = src, src.read(0, first), 0
133
134    def take(self, n: int) -> bytes:
135        while self.pos + n > len(self.buf):
136            if len(self.buf) >= self.src.size:
137                raise EOFError(f"{self.src.name}: truncated header")
138            self.buf += self.src.read(len(self.buf), max(len(self.buf), 4 << 20))
139        out = self.buf[self.pos:self.pos + n]
140        self.pos += n
141        return out
142
143    def u32(self) -> int: return struct.unpack("<I", self.take(4))[0]
144    def u64(self) -> int: return struct.unpack("<Q", self.take(8))[0]
145    def string(self) -> str: return self.take(self.u64()).decode("utf-8", "replace")
146
147
148SCALAR = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
149
150
151def gguf_value(r: Buffered, vtype: int):
152    if vtype == 8:
153        return r.string()
154    if vtype == 9:
155        itype, n = r.u32(), r.u64()
156        if itype == 8:
157            items = [r.string() for _ in range(n)]  # must be consumed either way
158            return items if n <= 64 else None
159        if itype == 9:
160            raise ValueError("nested GGUF arrays are not supported")
161        size = SCALAR[itype]
162        r.take(size * n)
163        return None
164    raw = r.take(SCALAR[vtype])
165    fmt = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<?",
166           10: "<Q", 11: "<q", 12: "<d"}[vtype]
167    return struct.unpack(fmt, raw)[0]
168
169
170def read_gguf(src: Source) -> tuple[dict, list[dict]]:
171    r = Buffered(src)
172    if r.take(4) != b"GGUF":
173        raise ValueError(f"{src.name}: not a GGUF file")
174    r.u32()  # version
175    n_tensors, n_kv = r.u64(), r.u64()
176    meta = {}
177    for _ in range(n_kv):
178        key = r.string()
179        meta[key] = gguf_value(r, r.u32())
180    tensors = []
181    for _ in range(n_tensors):
182        name = r.string()
183        dims = [r.u64() for _ in range(r.u32())]
184        ttype, offset = r.u32(), r.u64()
185        count = 1
186        for d in dims:
187            count *= d
188        tensors.append({"name": name, "type": GGML_TYPES.get(ttype, f"type#{ttype}"),
189                        "elements": count, "offset": offset})
190    align = int(meta.get("general.alignment") or 32)
191    data_start = (r.pos + align - 1) // align * align
192    # Actual stored bytes from the offsets: exact for every type, including unknown ones.
193    order = sorted(tensors, key=lambda t: t["offset"])
194    for a, b in zip(order, order[1:] + [None]):
195        end = b["offset"] if b else src.size - data_start
196        a["bytes"] = end - a["offset"]
197    return meta, tensors
198
199
200# ---------------------------------------------------------------- safetensors ----------------
201
202ST_BYTES = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2, "F8_E4M3": 1, "F8_E5M2": 1, "I64": 8,
203            "I32": 4, "I16": 2, "I8": 1, "U8": 1, "BOOL": 1, "F8_E8M0": 1, "U32": 4}
204PACKED = re.compile(r"(qweight|weight_packed|\.blocks$|_blocks$)")
205
206
207def read_safetensors(src: Source, bits: int | None) -> list[dict]:
208    n = struct.unpack("<Q", src.read(0, 8))[0]
209    header = json.loads(src.read(8, n))
210    out = []
211    for name, t in header.items():
212        if name == "__metadata__":
213            continue
214        count = 1
215        for d in t["shape"]:
216            count *= d
217        nbytes = count * ST_BYTES.get(t["dtype"], 1)
218        elements = count
219        if PACKED.search(name):
220            # Packed integer codes: logical weights = stored bits / code bits.
221            elements = nbytes * 8 // (bits or 4)
222        elif re.search(r"(scales|zeros|qzeros|g_idx|scale$|_scale|zero_point)", name):
223            elements = 0  # metadata of a quantized weight: counts as bytes only
224        out.append({"name": name, "type": t["dtype"], "elements": elements, "bytes": nbytes})
225    return out
226
227
228# ---------------------------------------------------------------- NInfer v3 ------------------
229
230NINFER_MAGIC = b"NINFER" + bytes([0, 3])
231
232
233def read_ninfer(src: Source) -> list[dict]:
234    """Logical parameters of a NInfer v3 .ninfer entry, from its directory JSON only.
235
236    A stored object may hold several logical parameters (for example an expert bank); each
237    binding's share of the object's stored bytes is proportional to its element range.
238    """
239    head = src.read(0, 32)
240    magic, json_bytes, _artifact_id = struct.unpack("<8sQ16s", head)
241    if magic != NINFER_MAGIC:
242        raise ValueError(f"{src.name}: not a NInfer v3 entry")
243    directory = json.loads(src.read(32, json_bytes))
244    objects = {o["id"]: o for o in directory["objects"] if o.get("kind", "tensor") == "tensor"}
245    elements = {}
246    for oid, o in objects.items():
247        count = 1
248        for d in o["shape"]:
249            count *= d
250        elements[oid] = count
251    out = []
252    for name, binding in directory["bindings"].items():
253        parts = ([{"object": binding["object"], "range": [0, elements.get(binding["object"], 0)]}]
254                 if "object" in binding else binding.get("parts", []))
255        count = nbytes = 0
256        fmt = None
257        for part in parts:
258            o = objects.get(part["object"])
259            if o is None:
260                continue
261            n = part["range"][1] - part["range"][0]
262            count += n
263            nbytes += o["bytes"] * n / max(elements[part["object"]], 1)
264            fmt = o["format"]
265        if count:
266            out.append({"name": name, "type": (fmt or "?").upper(), "elements": count,
267                        "bytes": nbytes})
268    return out
269
270
271# ---------------------------------------------------------------- summary --------------------
272
273CATEGORIES = [
274    ("norms", r"(norm)"),
275    ("hyper-connections", r"(hc_|_hc\.|hyper_connection)"),
276    ("routed experts", r"(_exps\b|\.experts\.|experts\.\d+|block_sparse_moe\.experts)"),
277    ("shared experts", r"(_shexp|shared_expert|moe\.shared\.)"),
278    ("router", r"(ffn_gate_inp|\.gate\.weight$|\.router\b|shared_score)"),
279    ("n-gram/per-layer embeddings", r"(ngram|per_layer|ple_|\.ple\.)"),
280    ("linear attn/SSM", r"(ssm_|linear_attn|mamba|conv1d|\.gdn\.)"),
281    # GGUF also names GatedDeltaNet input projections attn_qkv/attn_gate.
282    ("attention (incl. GDN qkv/gate)", r"(attn|attention|self_attn|indexer|\.q_proj|\.k_proj|"
283                                       r"\.v_proj|\.o_proj)"),
284    ("dense FFN", r"(ffn_|\.mlp\.)"),
285    ("token embedding", r"(token_embd|embed_tokens|token_embedding|wte)"),
286    ("output head", r"(^output\.|lm_head|output_head)"),
287    ("MTP / nextn", r"(nextn|mtp)"),
288]
289
290
291def category(name: str) -> str:
292    n = name.lower().replace("/", ".")  # NInfer logical names use slashes
293    for label, pattern in CATEGORIES:
294        if re.search(pattern, n):
295            return label
296    return "other"
297
298
299def q_class(bpw: float) -> str:
300    for limit, label in [(1.9, "Q1 class"), (2.8, "Q2 class"), (3.7, "Q3 class"),
301                         (4.9, "Q4 class"), (5.9, "Q5 class"), (7.5, "Q6 class"),
302                         (10.0, "Q8 class"), (17.0, "16-bit")]:
303        if bpw < limit:
304            return label
305    return "32-bit"
306
307
308def summarize(title: str, tensors: list[dict]) -> dict:
309    groups: dict[str, dict] = defaultdict(lambda: {"elements": 0, "bytes": 0,
310                                                  "types": defaultdict(int)})
311    for t in tensors:
312        g = groups[category(t["name"])]
313        g["elements"] += t["elements"]
314        g["bytes"] += t["bytes"]
315        g["types"][t["type"]] += t["bytes"]
316    total_e = sum(g["elements"] for g in groups.values())
317    total_b = sum(g["bytes"] for g in groups.values())
318    print(f"\n=== {title} ===")
319    print(f"total {total_b / 1e9:.2f} GB, {total_e / 1e9:.2f} B weights, "
320          f"{8 * total_b / max(total_e, 1):.2f} bits/weight overall")
321    print(f"{'group':30s} {'weights':>9s} {'GB':>8s} {'bits/w':>7s}  types (share of bytes)")
322    for label, g in sorted(groups.items(), key=lambda kv: -kv[1]["bytes"]):
323        bpw = 8 * g["bytes"] / g["elements"] if g["elements"] else float("nan")
324        types = ", ".join(f"{k} {100 * v / g['bytes']:.0f}%"
325                          for k, v in sorted(g["types"].items(), key=lambda kv: -kv[1]))
326        print(f"{label:30s} {g['elements'] / 1e9:8.2f}B {g['bytes'] / 1e9:8.2f} {bpw:7.2f}  {types}")
327    experts = groups.get("routed experts")
328    verdict = None
329    if experts and experts["elements"]:
330        verdict = 8 * experts["bytes"] / experts["elements"]
331        print(f"-> routed experts are {verdict:.2f} bits/weight ({q_class(verdict)})")
332    return {"title": title, "gb": total_b / 1e9, "bpw": 8 * total_b / max(total_e, 1),
333            "experts_bpw": verdict}
334
335
336def scan(label: str, files: list[Source], meta_config: dict | None) -> dict:
337    tensors: list[dict] = []
338    for src in files:
339        if src.name.endswith(".gguf"):
340            _meta, ts = read_gguf(src)
341        elif src.name.endswith(".ninfer"):
342            ts = read_ninfer(src)
343        else:
344            bits = None
345            if meta_config:
346                q = meta_config.get("quantization_config") or {}
347                bits = q.get("bits") or q.get("w_bit")
348            ts = read_safetensors(src, bits)
349        tensors += ts
350        print(f"  read header of {src.name}: {len(ts)} tensors", file=sys.stderr)
351    return summarize(label, tensors)
352
353
354def main() -> None:
355    parser = argparse.ArgumentParser(description=__doc__,
356                                     formatter_class=argparse.RawDescriptionHelpFormatter)
357    parser.add_argument("source", help="ms:owner/repo, hf:owner/repo, URL, file or directory")
358    parser.add_argument("variant", nargs="?", help="variant name or glob (e.g. UD-Q4_K_XL)")
359    parser.add_argument("--all", action="store_true", help="scan and compare every variant")
360    args = parser.parse_args()
361
362    files = [f for f in resolve(args.source)
363             if f.name.endswith((".gguf", ".safetensors", ".ninfer"))]
364    config = None
365    for f in resolve(args.source) if args.source.startswith(("ms:", "hf:")) else []:
366        if f.name == "config.json":
367            config = json.loads(http(f.url))
368            if config.get("quantization_config"):
369                print("config.json quantization_config:",
370                      json.dumps(config["quantization_config"])[:400])
371    variants: dict[str, list[Source]] = defaultdict(list)
372    for f in files:
373        variants[variant_of(f.name)].append(f)
374    if not variants:
375        sys.exit("no .gguf, .safetensors or .ninfer files found")
376    if len(variants) > 1 and not args.variant and not args.all:
377        print("variants (pass one as the second argument, or --all):")
378        for name, fs in sorted(variants.items()):
379            print(f"  {name:70s} {sum(f.size for f in fs) / 1e9:8.2f} GB  {len(fs)} file(s)")
380        return
381    chosen = {k: v for k, v in variants.items()
382              if args.all or not args.variant or args.variant in k
383              or fnmatch.fnmatch(k, args.variant)}
384    results = [scan(name, sorted(fs, key=lambda f: f.name), config)
385               for name, fs in sorted(chosen.items())]
386    if len(results) > 1:
387        print("\n=== comparison ===")
388        print(f"{'variant':60s} {'GB':>8s} {'bits/w':>7s} {'experts bits/w':>15s}")
389        for r in results:
390            e = f"{r['experts_bpw']:.2f} ({q_class(r['experts_bpw'])})" if r["experts_bpw"] else "-"
391            print(f"{r['title']:60s} {r['gb']:8.2f} {r['bpw']:7.2f} {e:>15s}")
392
393
394if __name__ == "__main__":
395    main()