okami.mom/strata

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

Niko1221Merge f-022-ownfiles: own GGUF files load again, plain download/prepare steps, chosen models folderc7938c2d3

main
10.0 KiB186 linesraw
1"""Which Strata model a GGUF is - and whether Strata can run it - from its header alone.
2
3Reads only the files' headers (a few MB each, by HTTP range requests for a remote file) with quantscope, prints the
4real storage of every weight group (bits per weight, quantization types), then compares the routed experts and the
5sizes with the files setup installs (data/gguf_fingerprints.json):
6
7    python tools/strata_inspect.py ms:ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF          # list the variants
8    python tools/strata_inspect.py ms:ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF IQ3_S    # one variant
9    python tools/strata_inspect.py ms:unsloth/Qwen3.8-Flash-Next-GGUF UD-Q2_K_XL
10    python tools/strata_inspect.py D:/models/my-copy-00001-of-00002.gguf                  # a local file or folder
11    python tools/strata_inspect.py https://example.com/x-00001-of-00002.gguf              # one URL (that shard only)
12
13ms: is ModelScope, hf: Hugging Face (HF_ENDPOINT is honoured).  setup.py --inspect runs the same.
14    python tools/strata_inspect.py --fingerprints data/gguf_fingerprints.json             # remake the table
15"""
16from __future__ import annotations
17
18import argparse
19import fnmatch
20import re
21import json
22import sys
23from collections import defaultdict
24from pathlib import Path
25
26ROOT = Path(__file__).resolve().parents[1]
27sys.path.insert(0, str(ROOT / "tools"))
28import quantscope as qs  # noqa: E402
29
30FINGERPRINTS = ROOT / "data" / "gguf_fingerprints.json"
31ARCH = "qwen4exp"                                       # Qwen3.8-Flash-Next's general.architecture
32PREVIEW_ARCHS = {"qwen35moe": "Qwen3.6-35B-A3B"}         # model families Strata knows but does not run yet (T0)
33
34# the files setup installs: (family, model, ModelScope repository, file name prefix) - for --fingerprints
35KNOWN = [
36    ("qwen", "Q2_0", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Q2_0/"),
37    ("qwen", "IQ2_XS", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "IQ2_XS/"),
38    ("qwen", "IQ3_XXS", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "IQ3_XXS/"),
39    ("qwen", "IQ3_S", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "IQ3_S/"),
40    ("swift", "Q2_0", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0"),
41    ("swift", "IQ2_XS", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS"),
42    ("swift", "IQ3_XXS", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS"),
43    ("swift", "IQ3_S", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S"),
44    ("coder", "IQ1_M", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF", "IQ1_M/"),
45    ("unsloth", "UD-IQ4_XS", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-IQ4_XS/"),
46    ("unsloth", "UD-Q4_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q4_K_XL/"),
47    ("unsloth", "UD-Q5_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q5_K_XL/"),
48    ("unsloth", "UD-Q6_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q6_K_XL/"),
49    ("unsloth", "Q8_0", "unsloth/Qwen3.8-Flash-Next-GGUF", "Q8_0/"),
50]
51
52
53def read_headers(files: list) -> tuple[str | None, list[dict]]:
54    """The architecture and every tensor of a model's shards (headers only)."""
55    arch, tensors = None, []
56    for f in files:
57        meta, ts = qs.read_gguf(f)
58        arch = arch or meta.get("general.architecture")
59        tensors += ts
60    return arch, tensors
61
62
63def role(name: str) -> str:
64    """A tensor's name without its layer number: blk.7.ffn_down_exps.weight -> blk.N.ffn_down_exps.weight."""
65    return re.sub(r"^blk\.\d+\.", "blk.N.", name)
66
67
68def roles(tensors: list[dict]) -> dict[str, list[str]]:
69    out: dict[str, set] = defaultdict(set)
70    for t in tensors:
71        out[role(t["name"])].add(t["type"])
72    return {k: sorted(v) for k, v in sorted(out.items())}
73
74
75def fingerprint(arch: str | None, tensors: list[dict]) -> dict:
76    """What the comparison needs from a model's shards: architecture, tensor count, bytes, routed experts' bytes per
77    quantization type and their bits per weight."""
78    n, total_b, total_e, exp_e = len(tensors), 0, 0, 0
79    experts: dict[str, int] = defaultdict(int)
80    for t in tensors:
81        total_b += t["bytes"]
82        total_e += t["elements"]
83        if qs.category(t["name"]) == "routed experts":
84            experts[t["type"]] += t["bytes"]
85            exp_e += t["elements"]
86    return {"arch": arch, "tensors": n, "bytes": total_b, "expert_bytes": dict(sorted(experts.items())),
87            "experts_bpw": round(8 * sum(experts.values()) / exp_e, 3) if exp_e else None,
88            "bpw": round(8 * total_b / total_e, 3) if total_e else None, "roles": roles(tensors)}
89
90
91def load_fingerprints(path: Path = FINGERPRINTS) -> dict:
92    return json.loads(path.read_text(encoding="utf-8"))
93
94
95def verdict(fp: dict, table: dict) -> tuple[str, str]:
96    """(kind, sentence): kind is "known" (a file setup installs, under any name), "family" (another family Strata
97    runs on its own engine path: Qwen3.6), "layout" (the same routed-expert
98    layout as one: a fine-tune made with the same recipe, untested), "no" (Strata cannot run it) or "untested"
99    (naming the tensors whose quantization no file Strata runs has for them)."""
100    known = {k: v for k, v in table.items() if not k.startswith("_")}
101    if fp["arch"] in PREVIEW_ARCHS:
102        return "family", (f"{PREVIEW_ARCHS[fp['arch']]} (architecture {fp['arch']!r}): Strata runs it on its own "
103                          "engine path in the NVIDIA (CUDA) and AMD (HIP) builds, not yet on Intel Arc (SYCL); setup "
104                          "installs it with --family qwen36")
105    if fp["arch"] != ARCH:
106        return "no", f"not Qwen3.8-Flash-Next (architecture {fp['arch']!r}): Strata runs only that model"
107    exact = [k for k, v in known.items() if v["expert_bytes"] == fp["expert_bytes"] and v["bytes"] == fp["bytes"]
108             and v["tensors"] == fp["tensors"]]
109    if exact:
110        fam, model = exact[0].split("/")
111        return "known", f"this is setup's --family {fam} --model {model} (give its folder with --gguf-dir)"
112    same = [k for k, v in known.items() if v["expert_bytes"] == fp["expert_bytes"]]
113    if same:
114        return "layout", ("the routed experts are stored exactly as in " + " / ".join(same) +
115                          ", but the file is not one setup knows (a fine-tune with the same recipe?): it may run as "
116                          "that size; not tested")
117    runs = set().union(*(v["expert_bytes"] for v in known.values()))
118    other = sorted(set(fp["expert_bytes"]) - runs)
119    if other:
120        return "no", ("its routed experts use " + ", ".join(other) + ", a quantization no file Strata runs uses "
121                      "(Strata's expert kernels cover " + ", ".join(sorted(runs)) + ")")
122    seen = table.get("_roles", {})
123    new = [f"{r} {'/'.join(t for t in ts if t not in seen.get(r, []))}" for r, ts in fp.get("roles", {}).items()
124           if any(t not in seen.get(r, []) for t in ts)]
125    head = ("its routed experts use only quantizations Strata runs (" + ", ".join(fp["expert_bytes"]) +
126            "), but this file is not one setup installs: not tested (and setup still refuses the GGUF names "
127            "it lists as unsupported, such as UD-Q2_K_XL: this is a header reading, not a promise that it runs)")
128    if new:
129        return "untested", head + ". Stored differently from every file Strata runs: " + ", ".join(new)
130    return "untested", head + "; every tensor uses a quantization some file Strata runs has for it"
131
132
133def make_fingerprints(out: Path) -> None:
134    listing, table = {}, {}
135    for fam, model, repo, prefix in KNOWN:
136        if repo not in listing:
137            listing[repo] = qs.list_hub("ms", repo)
138        files = sorted((f for f in listing[repo] if f.name.startswith(prefix) and f.name.endswith(".gguf")),
139                       key=lambda f: f.name)
140        table[f"{fam}/{model}"] = {**fingerprint(*read_headers(files)), "files": [f.name for f in files], "repo": repo}
141        print(f"{fam}/{model}: experts {table[f'{fam}/{model}']['experts_bpw']} bits/weight", file=sys.stderr)
142    union: dict[str, set] = defaultdict(set)
143    for v in table.values():
144        for r, ts in v.pop("roles").items():
145            union[r] |= set(ts)
146    table["_roles"] = {r: sorted(ts) for r, ts in sorted(union.items())}   # every quantization each tensor has
147    out.write_text(json.dumps(table, indent=1) + "\n", encoding="utf-8")
148
149
150def main() -> None:
151    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
152    ap.add_argument("source", nargs="?", help="ms:owner/repo, hf:owner/repo, a URL, a .gguf file or a folder")
153    ap.add_argument("variant", nargs="?", help="a variant name or glob (e.g. IQ3_S, UD-Q2_K_XL)")
154    ap.add_argument("--fingerprints", metavar="OUT", help="read the files setup installs and write the table")
155    a = ap.parse_args()
156    if a.fingerprints:
157        make_fingerprints(Path(a.fingerprints))
158        return
159    if not a.source:
160        ap.error("a source is needed")
161    files = [f for f in qs.resolve(a.source) if f.name.endswith(".gguf") and "mmproj" not in f.name.lower()]
162    variants: dict[str, list] = defaultdict(list)
163    for f in files:
164        variants[qs.variant_of(f.name)].append(f)
165    if not variants:
166        sys.exit("no model .gguf files there")
167    chosen = {k: v for k, v in variants.items() if not a.variant or a.variant in k or fnmatch.fnmatch(k, a.variant)}
168    if len(chosen) > 1:
169        print("variants (pass one as the second argument):")
170        for name, fs in sorted(chosen.items()):
171            print(f"  {name:70s} {sum(f.size for f in fs) / 1e9:8.2f} GB  {len(fs)} file(s)")
172        return
173    if not chosen:
174        sys.exit(f"no variant matches {a.variant!r}")
175    name, fs = next(iter(chosen.items()))
176    fs = sorted(fs, key=lambda f: f.name)
177    arch, tensors = read_headers(fs)
178    qs.summarize(name, tensors)
179    fp = fingerprint(arch, tensors)
180    kind, sentence = verdict(fp, load_fingerprints())
181    print(f"\nStrata: {sentence}")
182    sys.exit(0 if kind in ("known", "layout") else 2 if kind == "no" else 0)
183
184
185if __name__ == "__main__":
186    main()