okami.mom/strata

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

Niko1221Merge f-own-2a-oracle 07df43732 (quant_parity golden reference leg, quant_golden_regen) into f-own-int67148809b

main
5.8 KiB106 linesraw
1"""tests/quant/golden_merge.py - write tests/quant/golden_x86.txt from `quant_parity --write-golden` fragments (tests/quant/make_golden.sh runs it).
2
3    python tests/quant/golden_merge.py --gcc gcc-avx2.txt gcc-avx.txt gcc-none.txt --msvc msvc-avx2.txt msvc-avx.txt msvc-none.txt -o tests/quant/golden_x86.txt
4
5Family gcc: every group of the GCC 13.x fragments.  Family msvc: only the groups whose MSVC 19.4x reference differs from the gcc line; each needs a reason
6in WHY below (the merge refuses an unexplained difference, and any group whose INPUTS differ between the toolchains: that is a test bug, not arithmetic).
7"""
8import argparse
9import datetime
10import os
11import re
12import sys
13
14# why a family has its own line for (flavour, section, type), with what was measured (OWN-2A-ORACLE, 11-10: MSVC 19.44 on the owner PC against GCC 13.3 on p1004)
15WHY = {
16    ("msvc", "avx2", "dot", "q5_K"): "GCC contracts ggml's _mm256_add_ps(_mm256_mul_ps(a, b), c) here into an FMA and MSVC does not; ggml and the layer agree "
17                                     "within each toolchain; measured 1-512 ulp (max relative 3.3e-5), n = 512..2048",
18    ("msvc", "avx2", "dot", "iq1_s"): "GCC contracts ggml's add-of-mul intrinsics here into an FMA and MSVC does not; ggml and the layer agree within each toolchain; "
19                                      "measured 1-16 ulp (max relative 1.6e-6), n = 512..2048",
20}
21ORDER = ["avx2", "avx", "generic"]
22
23
24def read_fragment(path):
25    made, lines = None, []
26    with open(path, encoding="utf-8") as f:
27        for ln in f:
28            ln = ln.rstrip("\r\n")
29            if ln.startswith("# made by "):
30                made = ln[len("# made by "):]
31            elif ln and not ln.startswith("#"):
32                p = ln.split()
33                if len(p) != 7:
34                    sys.exit("%s: malformed line: %s" % (path, ln))
35                lines.append(p)
36    if made is None or not lines:
37        sys.exit("%s: not a quant_parity --write-golden file" % path)
38    return made, lines
39
40
41def main():
42    ap = argparse.ArgumentParser()
43    ap.add_argument("--gcc", nargs="+", required=True)
44    ap.add_argument("--msvc", nargs="+", required=True)
45    ap.add_argument("-o", required=True)
46    ap.add_argument("--date", default=datetime.date.today().isoformat())
47    a = ap.parse_args()
48    here = os.path.dirname(os.path.abspath(__file__))
49    pin = "unknown"
50    up = os.path.join(here, "..", "..", "third_party", "strata-ggml", "UPSTREAM.md")
51    if os.path.exists(up):
52        m = re.search(r"^pin: ([0-9a-f]{40})", open(up, encoding="utf-8").read(), re.M)
53        pin = m.group(1) if m else pin
54    gcc, msvc, made = {}, {}, {"gcc": set(), "msvc": set()}
55    for fam, files, into in (("gcc", a.gcc, gcc), ("msvc", a.msvc, msvc)):
56        for path in files:
57            who, lines = read_fragment(path)
58            if fam == "gcc" and not re.match(r"GCC 13\.", who):
59                sys.exit("%s: family gcc needs GCC 13.x, this fragment is made by %s" % (path, who))
60            if fam == "msvc" and not re.match(r"MSVC 194", who):
61                sys.exit("%s: family msvc needs MSVC 19.4x, this fragment is made by %s" % (path, who))
62            name = who.split(",")[0]
63            m = re.match(r"MSVC (\d{2})(\d{2})(\d{5})$", name)
64            made[fam].add("MSVC %s.%s.%s" % m.groups() if m else name)
65            fl = lines[0][0]
66            into[fl] = lines
67    out = []
68    head = [
69        "# tests/quant/golden_x86.txt - the reference digests of the quant layer's oracle test, leg 1 (tests/quant/quant_parity.cpp says how they are checked).",
70        "# Line: <family> <flavour> <section> <type> <n> <rows> <input digest> <reference digest>; digests: golden_fnv1a64 (FNV-1a, 64 bit) in quant_parity.cpp.",
71        "# family gcc: ggml-cpu built by %s, every group; every toolchain is held to these lines unless it has its own." % ", ".join(sorted(made["gcc"])),
72        "# family msvc: ggml-cpu built by %s, only the groups where its reference differs from the gcc line (%%note says why)." % ", ".join(sorted(made["msvc"])),
73        "# ggml: third_party/strata-ggml, llama.cpp pin %s (UPSTREAM.md)." % pin,
74        "# made by: tests/quant/make_golden.sh (GCC side, quant_parity --write-golden per flavour) + quant_parity --write-golden under MSVC + tests/quant/golden_merge.py",
75        "# date: %s" % a.date,
76    ]
77    for fl in ORDER:
78        if fl not in gcc or fl not in msvc:
79            sys.exit("flavour %s is missing from the gcc or the msvc fragments" % fl)
80        g, m = gcc[fl], msvc[fl]
81        gk = {tuple(p[:4]): p for p in g}
82        mk = {tuple(p[:4]): p for p in m}
83        if set(gk) != set(mk):
84            sys.exit("flavour %s: the toolchains ran different groups: %s" % (fl, sorted(set(gk) ^ set(mk))[:10]))
85        own = []
86        for p in g:
87            q = mk[tuple(p[:4])]
88            if q[4] != p[4] or q[5] != p[5]:
89                sys.exit("flavour %s group %s: the INPUTS differ between GCC and MSVC (a test bug, not arithmetic)" % (fl, " ".join(p[:4])))
90            if q[6] != p[6]:
91                if ("msvc", fl, p[1], p[2]) not in WHY:
92                    sys.exit("flavour %s group %s: MSVC's reference differs and WHY has no reason for it" % (fl, " ".join(p[:4])))
93                own.append(q)
94        rows = sum(int(p[4]) for p in g)
95        head.append("# flavour %s: %d groups, %d rows; family msvc: %d own lines" % (fl, len(g), rows, len(own)))
96        out += ["gcc " + " ".join(p) for p in g]
97        for key in sorted({(p[1], p[2]) for p in own}):
98            out.append("%%note msvc %s %s %s %s" % (fl, key[0], key[1], WHY[("msvc", fl) + key]))
99        out += ["msvc " + " ".join(q) for q in own]
100    with open(a.o, "w", encoding="utf-8", newline="\n") as f:
101        f.write("\n".join(head + out) + "\n")
102    print("golden_merge: wrote %s (%d lines)" % (a.o, len(head) + len(out)))
103
104
105if __name__ == "__main__":
106    main()