okami.mom/strata

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

Niko1221Merge f-q4-metal (ed1f58d27): the Mac (Metal) engine follows the compiled geometry (q4_lite/q4_mid/q4_big kernel parity 40/40, gate 2 like CUDA), plus the PLE row-buffer fix in src/program/generate.cpp (sized by the compiled hidden size, not 2560; it overran 24 KB at hidden 4096 and crashed Metal serve); default build unchanged (CUDA SASS 3573/3573 and 160/160 host objects, HIP gfx1201/gfx1151 string offsets only, SYCL 129/129 objects and 22/22 checksums, Metal per-token functions identical, UD-Q4_K_XL 10/10 tokens, CUDA IQ3_S 26/26 tokens) (Qwen4 prep)7f46672a4

main
5.7 KiB139 linesraw
1#!/usr/bin/env python3
2"""msl_text_check.py - are two builds' kernel libraries the same text?
3
4    STRATA_METAL_MSL_DUMP=<dir> strata ...        (any program that compiles kernels through mtl::Context: the engine, a parity binary)
5    python3 metal/tools/msl_text_check.py <dumpdir A> <dumpdir B> [--preprocess "clang -E -P -x c++ -nostdinc -undef"] [--air]
6
7The dump holds one NNN.msl per library (the prelude, <metal_stdlib>, ggml-common, then every kernel file: the exact string handed to
8the compiler) and index.txt (NNN.msl: the kernel files of that library).  Libraries are matched by their file list, in order.
9
10For each pair the tool reports, strongest first:
11  raw        the two strings are byte-identical (sha256 equal)
12  pp         not identical, but the preprocessed texts are (the preprocessor's output with comments, blank lines and runs of blanks
13             dropped): a change of comments, #ifndef guards or a macro that expands to the number it replaced
14  air        (--air, needs `xcrun metal`) the two compile to byte-identical AIR (same code, whatever the text)
15  DIFFERENT  none of the above
16Exit code 0 when every pair is raw or pp (or air with --air), 1 otherwise.
17"""
18import argparse
19import hashlib
20import os
21import re
22import shlex
23import subprocess
24import sys
25import tempfile
26
27
28def read_index(d):
29    out = []
30    p = os.path.join(d, "index.txt")
31    if not os.path.exists(p):
32        sys.exit("no index.txt in " + d)
33    for ln in open(p):
34        ln = ln.rstrip("\n")
35        if not ln:
36            continue
37        name, _, files = ln.partition(":")
38        out.append((name.strip(), tuple(os.path.basename(f) for f in files.split())))   # (the engine passes absolute paths, the tests relative ones)
39    return out
40
41
42def sha(path):
43    return hashlib.sha256(open(path, "rb").read()).hexdigest()
44
45
46def preprocess(path, cmd):
47    # The C preprocessor of clang over the text, the <...> includes left out: none of the kernel sources branches on a Metal macro, so the
48    # macros they and the host's prelude define are all there is to expand (`xcrun metal -E` needs the Metal toolchain component).
49    with tempfile.NamedTemporaryFile(suffix=".cpp", delete=False) as t:
50        data = open(path, "rb").read().decode("utf-8", "replace")
51        data = re.sub(r"(?m)^[ 	]*#[ 	]*include[ 	]*<[^>]*>", "", data)   # <metal_stdlib>, <MetalPerformancePrimitives/...>
52        t.write(data.encode())
53        tmp = t.name
54    try:
55        r = subprocess.run(shlex.split(cmd) + [tmp], capture_output=True, text=True)
56        if r.returncode != 0:
57            return None, r.stderr[-400:]
58        txt = r.stdout
59    finally:
60        os.unlink(tmp)
61    out = []
62    for ln in txt.splitlines():
63        if ln.startswith("#"):
64            continue   # line markers (the file names differ by temp path)
65        ln = re.sub(r"//.*$", "", ln)
66        ln = re.sub(r"\s+", " ", ln).strip()
67        if ln:
68            out.append(ln)
69    return "\n".join(out), ""
70
71
72def air(path, tool):
73    with tempfile.TemporaryDirectory() as td:
74        src = os.path.join(td, "x.metal")
75        open(src, "wb").write(open(path, "rb").read())
76        o = os.path.join(td, "x.air")
77        r = subprocess.run(shlex.split(tool) + ["-c", src, "-o", o], capture_output=True, text=True)
78        if r.returncode != 0:
79            return None, r.stderr[-400:]
80        return hashlib.sha256(open(o, "rb").read()).hexdigest(), ""
81
82
83def main():
84    ap = argparse.ArgumentParser()
85    ap.add_argument("a")
86    ap.add_argument("b")
87    ap.add_argument("--preprocess", default="clang -E -P -x c++ -nostdinc -undef")
88    ap.add_argument("--air", action="store_true")
89    ap.add_argument("--air-tool", default="xcrun -sdk macosx metal -std=metal3.2")
90    a = ap.parse_args()
91    ia, ib = read_index(a.a), read_index(a.b)
92    used = set()
93    bad = 0
94    for na, fa in ia:
95        match = None
96        for nb, fb in ib:
97            if nb not in used and fb == fa:
98                match = nb
99                break
100        if match is None:
101            print("%s %s: no library with this file list in B" % (na, " ".join(fa)))
102            bad += 1
103            continue
104        used.add(match)
105        pa, pb = os.path.join(a.a, na), os.path.join(a.b, match)
106        if sha(pa) == sha(pb):
107            print("raw        %s %s  (%d bytes)" % (na, " ".join(fa), os.path.getsize(pa)))
108            continue
109        ta, ea = preprocess(pa, a.preprocess)
110        tb, eb = preprocess(pb, a.preprocess)
111        if ta is None or tb is None:
112            print("pp-ERROR   %s %s: %s %s" % (na, " ".join(fa), ea, eb))
113            bad += 1
114            continue
115        if ta == tb:
116            print("pp         %s %s  (raw differs: %d vs %d bytes; preprocessed %d bytes identical)" %
117                  (na, " ".join(fa), os.path.getsize(pa), os.path.getsize(pb), len(ta)))
118            continue
119        if a.air:
120            xa, _ = air(pa, a.air_tool)
121            xb, _ = air(pb, a.air_tool)
122            if xa and xa == xb:
123                print("air        %s %s  (AIR identical)" % (na, " ".join(fa)))
124                continue
125        la, lb = ta.splitlines(), tb.splitlines()
126        first = next((i for i in range(min(len(la), len(lb))) if la[i] != lb[i]), min(len(la), len(lb)))
127        print("DIFFERENT  %s %s: first differing preprocessed line %d\n   A: %s\n   B: %s" %
128              (na, " ".join(fa), first, la[first][:200] if first < len(la) else "<end>", lb[first][:200] if first < len(lb) else "<end>"))
129        bad += 1
130    for nb, fb in ib:
131        if nb not in used:
132            print("%s %s: only in B" % (nb, " ".join(fb)))
133            bad += 1
134    print("libraries: A %d, B %d; %s" % (len(ia), len(ib), "all the same text" if bad == 0 else "%d differ" % bad))
135    sys.exit(1 if bad else 0)
136
137
138if __name__ == "__main__":
139    main()