okami.mom/strata

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

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
3.8 KiB83 linesraw
1#!/usr/bin/env python3
2"""Check the loader's tensor conversion (src/split/src/tensor_convert.hpp) against gguf-py.
3
4  convert_dump MODEL.gguf OUTDIR name... > dump.txt
5  convert_check.py MODEL.gguf OUTDIR dump.txt --gguf-py /path/to/llama.cpp/gguf-py
6
7For each tensor in the dump: the values the loader holds now (read back by convert_dump) must equal gguf-py's dequantization of the
8file's original tensor to within what the target type allows: exactly (F32 target), or within half a Q8_0 step per 32 values
9(amax/254, plus the f16 rounding of the scale). Prints one line per tensor and exits 1 on any miss.
10"""
11import argparse
12import os
13import sys
14
15import numpy as np
16
17
18def main():
19    ap = argparse.ArgumentParser()
20    ap.add_argument("model")
21    ap.add_argument("outdir")
22    ap.add_argument("dump")
23    ap.add_argument("--gguf-py", help="optional: a folder that holds llama.cpp's gguf package, to compare against it (default: tools/strata_gguf.py)")
24    a = ap.parse_args()
25    sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "tools"))
26    if a.gguf_py:
27        os.environ["STRATA_GGUF_PY"] = a.gguf_py
28    from _paths import gguf_lib
29    gguf = gguf_lib()
30    quants = gguf.quants
31
32    shards = [a.model]
33    import re
34    m = re.match(r"(.*-)(\d{5})(-of-)(\d{5})(\.gguf)$", a.model)
35    if m:
36        shards = ["%s%05d%s%s%s" % (m[1], i, m[3], m[4], m[5]) for i in range(1, int(m[4]) + 1)]
37    tensors = {}
38    for s in shards:
39        r = gguf.GGUFReader(s)
40        for t in r.tensors:
41            tensors[t.name] = t
42
43    bad = 0
44    for line in open(a.dump):
45        p = line.split()
46        if len(p) != 3 or p[0] == "converted":
47            continue
48        name, ty = p[0], int(p[1])
49        t = tensors[name]
50        if t.tensor_type.name == "Q2_0":   # Strata's type 42, not in gguf-py's dequantizers: (code - 1) * d, value j in byte j / 4 at bit 2 (j % 4)
51            raw = np.ascontiguousarray(t.data).reshape(-1, 18)
52            d = raw[:, :2].copy().view(np.float16).astype(np.float64).reshape(-1, 1)
53            qs = raw[:, 2:]
54            codes = np.stack([(qs >> (2 * k)) & 3 for k in range(4)], axis=2).reshape(-1, 64)
55            ref = ((codes.astype(np.float64) - 1.0) * d).reshape(-1)
56        else:
57            ref = quants.dequantize(t.data, t.tensor_type).astype(np.float64).reshape(-1)
58        got = np.fromfile(os.path.join(a.outdir, name + ".f32"), dtype=np.float32).astype(np.float64)
59        if ref.shape != got.shape:
60            print("FAIL %s: %d values, gguf-py %d" % (name, got.size, ref.size))
61            bad += 1
62            continue
63        err = np.abs(got - ref)
64        if ty == 0:     # F32: BF16 / F16 / F32 source, exact
65            lim = np.zeros_like(err)
66        elif ty != 8:   # a type the loader keeps or repacks without changing a value (Q2_0 -> Q4_0, IQ4_NL as is): f32 rounding only
67            lim = np.abs(ref) * 1e-6 + 1e-12
68        else:           # Q8_0: half a step of its block, the scale stored as f16
69            blk = ref.reshape(-1, 32)
70            amax = np.abs(blk).max(axis=1)
71            # the scale d = amax/127 is stored as f16 (relative error 2^-11), and the value is q*d with |q| <= 127
72            # (a block whose d falls below f16's normal range, 6.1e-5, has an absolute step of 2^-25 in d: 127 * 2^-25 on the value;
73            # 8 of the 19.9M blocks of token_embd are like that)
74            lim = np.repeat(amax * (0.5 / 127.0 + 2.0 ** -10) + 127 * 2.0 ** -25 + 1e-12, 32)
75        ok = bool((err <= lim).all())
76        rel = float(np.sqrt((err ** 2).sum() / max((ref ** 2).sum(), 1e-30)))
77        print("%s %s %s  from %s  max|d|=%.3g  rel_rms=%.3g" % ("ok  " if ok else "FAIL", name, {0: "F32", 8: "Q8_0", 2: "Q4_0", 20: "IQ4_NL"}.get(ty, str(ty)), t.tensor_type.name, err.max(), rel))
78        bad += not ok
79    sys.exit(1 if bad else 0)
80
81
82if __name__ == "__main__":
83    main()