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.2 KiB72 linesraw
1#!/usr/bin/env python3
2"""Check the prompt kernel's weight tiles against gguf-py.
3
4  moe_tile_test MODEL.gguf OUTDIR > tiles.txt
5  tile_check.py MODEL.gguf OUTDIR tiles.txt --gguf-py /path/to/gguf-py
6
7For each line of the dump (tensor, loader type, rows, columns, expert): the f16 values the tile put in shared memory must equal gguf-py's
8dequantization of the file's expert, rounded once to f16 (a tile value may differ by one f16 step where the two compute the f32 product in
9another order). Strata's Q2_0 (type 42; the loader repacks it to Q4_0 blocks, type 2) is checked against (code - 1) * d read from the
10file. Prints one line per tensor and expert; exit 1 on any miss.
11"""
12import argparse
13import os
14import re
15import sys
16
17import numpy as np
18
19
20def main():
21    ap = argparse.ArgumentParser()
22    ap.add_argument("model")
23    ap.add_argument("outdir")
24    ap.add_argument("dump")
25    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)")
26    a = ap.parse_args()
27    sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "tools"))
28    if a.gguf_py:
29        os.environ["STRATA_GGUF_PY"] = a.gguf_py
30    from _paths import gguf_lib
31    gguf = gguf_lib()
32    quants = gguf.quants
33
34    m = re.match(r"(.*-)(\d{5})(-of-)(\d{5})(\.gguf)$", a.model)
35    shards = ["%s%05d%s%s%s" % (m[1], i, m[3], m[4], m[5]) for i in range(1, int(m[4]) + 1)] if m else [a.model]
36    tensors = {}
37    for s in shards:
38        for t in gguf.GGUFReader(s).tensors:
39            tensors[t.name] = t
40
41    bad = 0
42    for line in open(a.dump):
43        p = line.split()
44        if len(p) != 5 or not p[1].isdigit():
45            continue
46        name, ty, nrows, ncols, e = p[0], int(p[1]), int(p[2]), int(p[3]), int(p[4])
47        t = tensors[name]
48        raw = np.asarray(t.data)[e]
49        if t.tensor_type.name == "Q2_0":
50            raw = np.ascontiguousarray(raw).reshape(-1, 18)
51            d = raw[:, :2].copy().view(np.float16).astype(np.float32).reshape(-1, 1)
52            codes = np.stack([(raw[:, 2:] >> (2 * k)) & 3 for k in range(4)], axis=2).reshape(-1, 64)
53            ref = ((codes.astype(np.float32) - 1.0) * d).reshape(nrows, ncols)
54        else:
55            ref = quants.dequantize(raw, t.tensor_type).astype(np.float32).reshape(nrows, ncols)
56        ref16 = ref.astype(np.float16)
57        got = np.fromfile(os.path.join(a.outdir, "%s.e%d.f16" % (name, e)), dtype=np.float16).reshape(nrows, ncols)
58        gi, ri = got.view(np.int16).astype(np.int32), ref16.view(np.int16).astype(np.int32)
59        # f16 ordering: compare as sign-magnitude steps
60        def key(x):
61            return np.where(x < 0, -(x & 0x7FFF), x)
62        step = np.abs(key(gi) - key(ri))
63        exact = float((step == 0).mean())
64        ok = bool(step.max() <= 1 and exact >= 0.999 and not np.isnan(got.astype(np.float32)).any())
65        print("%s %-44s %-8s e%-3d exact %.5f  max step %d  max|d| %.3g" % ("ok  " if ok else "FAIL", name, t.tensor_type.name, e, exact, step.max(),
66                                                                          float(np.abs(got.astype(np.float32) - ref).max())))
67        bad += not ok
68    sys.exit(1 if bad else 0)
69
70
71if __name__ == "__main__":
72    main()