File size: 2,271 Bytes
41a0653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""Matched-bytes quant recipe for a pruned GLM-5.3-Flash GGUF, derived from Unsloth's UD-Q2_K_XL.

Every non-expert tensor gets EXACTLY the type Unsloth gave it in UD-Q2_K_XL, so the only
differences between our arm and the incumbent are (a) fewer routed experts and (b) the bits those
experts get with the bytes the prune freed. Routed-expert tensors step up a fixed ladder from
Unsloth's per-tensor choice, so Unsloth's per-layer upgrades (first MoE layer, down_proj, MTP)
carry over.

Writes a --tensor-type-file of anchored regexes (^name$=type) and prints the predicted size.
Usage: gguf_recipe.py <K> <ladder-name> <out.txt> <unsloth shard>...
"""
from __future__ import annotations

import os
import re
import sys

sys.path.insert(0, os.environ.get("LLAMA_GGUF_PY", "llama.cpp/gguf-py"))  # upstream llama.cpp gguf-py
from gguf import GGUFReader  # noqa: E402

BPW = {"IQ2_XS": 2.3125, "IQ3_XXS": 3.0625, "IQ3_S": 3.4375, "IQ4_XS": 4.25, "Q2_K": 2.625,
       "Q3_K": 3.4375, "Q4_K": 4.5, "Q5_K": 5.5, "Q6_K": 6.5625, "Q8_0": 8.5}
LADDERS = {
    # 216E: about +34% expert bits for 0.75x the experts
    "216": {"IQ2_XS": "IQ3_XXS", "IQ3_XXS": "IQ4_XS", "IQ4_XS": "Q5_K", "Q2_K": "Q3_K", "Q3_K": "Q4_K"},
    # 192E: about +50% expert bits for 0.667x the experts
    "192": {"IQ2_XS": "IQ3_S", "IQ3_XXS": "Q4_K", "IQ4_XS": "Q5_K", "Q2_K": "Q3_K", "Q3_K": "Q4_K"},
}
EXP = re.compile(r"^blk\.\d+\.ffn_(gate|up|down)_exps\.weight$")


def main() -> None:
    K, ladder_name, out, *shards = sys.argv[1:]
    K = int(K)
    ladder = LADDERS[ladder_name]
    lines, base, ours = [], 0, 0
    for p in shards:
        for t in GGUFReader(p).tensors:
            typ, n = t.tensor_type.name, int(t.n_bytes)
            base += n
            if EXP.match(t.name):
                new = ladder[typ]
                ours += n * K / 288 * BPW[new] / BPW[typ]
            else:
                new = typ
                ours += n
            lines.append(f"^{re.escape(t.name)}$={new.lower()}")
    with open(out, "w") as f:
        f.write("\n".join(lines) + "\n")
    print(f"{len(lines)} tensors; UD-Q2_K_XL {base/2**30:.2f} GiB; predicted {K}E/{ladder_name} "
          f"{ours/2**30:.2f} GiB ({100*(ours/base-1):+.1f}%) -> {out}")


if __name__ == "__main__":
    main()