okami.mom/strata

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

Niko1221Merge f-vit-exact: the picture reader follows the float32 reference closer on the CPU and on the GPU60d431e2a

main
13.1 KiB257 linesraw
1#!/usr/bin/env python3
2"""The GPU gate of the own vision tower (rule 6 of RESULTS-OWN-3V.md): our GPU tower against the float32 reference, and no noisier than mtmd's GPU path.
3
4    python3 gate_gpu.py --helper <strata-vision> --compare <strata-vision-own-compare> --mmproj <mmproj.gguf> --model <text model .gguf> --out <dir>
5                        [--max-tokens 1024] [--repeat 4] [--ref-dir <dir of our float32 reference's <picture>.sve>] [--cpu-dir <dir of stored mtmd-CPU <picture>.sve>]
6                        <image> [<image> ...]
7
8The reference is our float32 tower (VitRef: the own tower on the CPU with STRATA_VIT_CPU=ref), from --ref-dir where it holds the picture's file, else made
9here.  Until 11-14 the reference was mtmd's CPU path; mtmd itself sits up to 0.0168 below float32 (16 pictures: global cosine min 0.983 on its GPU, 0.998
10on its CPU), so it stays only as an information column.  One strata-vision per reader (VitRef on the CPU, mtmd on the CPU unless --cpu-dir gives its
11files, mtmd on the GPU, own on the GPU), every picture through each.  Per picture:
12  main      cosine(own GPU, float32)               must be >= --min-cos (0.999)
13  floor     cosine(mtmd GPU, float32)              what llama.cpp's reader gives
14  no-worse  main >= floor - 1e-4  or  main >= 0.9999   our GPU tower is at least as close to float32 as mtmd-GPU is (the coordinator's tolerance, 11-09)
15  info      cosine(own GPU, mtmd CPU), cosine(own GPU, mtmd GPU) (printed, no pass / fail)
16and the times of the two GPU readers (median of --repeat further encodes, after the first); the GPU memory (nvidia-smi, rocm-smi or Linux DRM fdinfo); whether
17our GPU tower gives byte-identical output on every encode (REPEATABLE line; information, the exit code does not depend on it).  Exit 0 when every picture passes main and no-worse.  Standard library only.
18"""
19import argparse
20import hashlib
21import os
22import statistics
23import subprocess
24import sys
25
26
27def fdinfo_mib(pid):
28    """Device-local memory of a process from Linux's DRM fdinfo (/proc/<pid>/fdinfo; i915 / xe drm-total-local0 or drm-resident-local0, amdgpu
29    drm-memory-vram), the largest over its DRM files, MiB; 0 where it cannot be read (no such files, another OS)."""
30    best = 0
31    d = "/proc/%d/fdinfo" % pid
32    try:
33        fds = os.listdir(d)
34    except OSError:
35        return 0
36    for fd in fds:
37        try:
38            with open(os.path.join(d, fd)) as f:
39                txt = f.read()
40        except OSError:
41            continue
42        if "drm-driver" not in txt:
43            continue
44        for line in txt.splitlines():
45            k, _, v = line.partition(":")
46            if k.strip() not in ("drm-total-local0", "drm-resident-local0", "drm-memory-vram", "drm-total-vram0", "drm-resident-vram0"):
47                continue
48            parts = v.split()
49            if not parts:
50                continue
51            n = float(parts[0])
52            unit = parts[1] if len(parts) > 1 else ""
53            mib = {"KiB": n / 1024.0, "MiB": n, "GiB": n * 1024.0}.get(unit, n / 1048576.0)
54            best = max(best, int(mib))
55    return best
56
57
58def mac_footprint_mib(pid):
59    """macOS: the process's physical footprint (what Activity Monitor calls Memory; on unified memory it includes the GPU buffers), MiB, from the
60    `footprint` tool (no root needed for our own process); 0 elsewhere or when it cannot be read."""
61    if sys.platform != "darwin":
62        return 0
63    try:
64        out = subprocess.run(["footprint", "-p", str(pid)], capture_output=True, text=True, timeout=60).stdout
65    except Exception:  # noqa: BLE001
66        return 0
67    for line in out.splitlines():
68        low = line.lower()
69        if "phys_footprint:" in low or low.strip().startswith("footprint:"):
70            t = line.split(":", 1)[1].split()
71            if len(t) >= 2:
72                try:
73                    n = float(t[0])
74                except ValueError:
75                    continue
76                return int({"KB": n / 1024.0, "MB": n, "GB": n * 1024.0}.get(t[1].upper(), 0))
77    return 0
78
79
80class Reader:
81    def __init__(self, exe, tower, mmproj, model, gpu, max_tokens, threads, out, label, env=None):
82        args = [exe, "--mmproj", mmproj, "--model", model, "--tower", tower]
83        if gpu:
84            args.append("--gpu")
85        if max_tokens:
86            args += ["--max-tokens", str(max_tokens)]
87        if threads and not gpu:
88            args += ["--threads", str(threads)]
89        self.label = label
90        self.p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=open(os.path.join(out, label + ".stderr"), "w"), text=True,
91                                  env=dict(os.environ, **env) if env else None)
92        line = self.p.stdout.readline().strip()
93        if not line.startswith("READY"):
94            raise SystemExit("%s reader did not start: %r" % (label, line))
95
96    peak_mib = 0
97
98    def vram(self):
99        """This reader's GPU memory now (nvidia-smi's compute-apps list, by pid); remembers the peak.  0 when it cannot be read."""
100        try:
101            out = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"], capture_output=True, text=True,
102                                 timeout=30).stdout
103            for line in out.splitlines():
104                pid, _, mem = line.partition(",")
105                if pid.strip() == str(self.p.pid) and mem.strip().isdigit():
106                    self.peak_mib = max(self.peak_mib, int(mem.strip()))
107        except Exception:  # noqa: BLE001
108            pass
109        try:   # AMD: rocm-smi's KFD process list:  PID  NAME  #GPUs  VRAM USED(B)  SDMA USED  CU OCCUPANCY
110            out = subprocess.run(["rocm-smi", "--showpids"], capture_output=True, text=True, timeout=30).stdout
111            for line in out.splitlines():
112                t = line.split()
113                if len(t) >= 6 and t[0] == str(self.p.pid) and t[-3].isdigit():
114                    self.peak_mib = max(self.peak_mib, int(t[-3]) // (1 << 20))
115        except Exception:  # noqa: BLE001
116            pass
117        self.peak_mib = max(self.peak_mib, fdinfo_mib(self.p.pid))   # Linux DRM: Intel (i915 / xe) and AMD report device memory per process here
118        self.peak_mib = max(self.peak_mib, mac_footprint_mib(self.p.pid))   # a Mac: the whole footprint (unified memory)
119        return self.peak_mib
120
121    def enc(self, img, out):
122        self.p.stdin.write("ENC %s %s\n" % (img, out))
123        self.p.stdin.flush()
124        res = self.p.stdout.readline().strip()
125        if self.label.endswith("-gpu"):
126            self.vram()
127        return res
128
129    def close(self):
130        try:
131            self.p.stdin.write("QUIT\n")
132            self.p.stdin.flush()
133            self.p.wait(timeout=30)
134        except Exception:
135            self.p.kill()
136
137
138def cmp(compare, a, b):
139    r = subprocess.run([compare, a, b], capture_output=True, text=True).stdout.strip()
140    if not r.startswith("n="):
141        return None
142    return dict(p.split("=") for p in r.split())
143
144
145def gate_pass(main, floor, min_cos=0.999, skip_cpu=False):
146    """main = cosine(own GPU, float32), floor = cosine(mtmd GPU, float32).  Rule 1: main >= min_cos; rule 2: main >= floor - 1e-4, or main >= 0.9999.
147    With --skip-cpu (no float32 reference: pictures at the largest token limit) main compares the two GPU readers and only has to reach 0.99."""
148    if skip_cpu:
149        return main >= 0.99
150    return main >= min_cos and (main >= floor - 1e-4 or main >= 0.9999)
151
152
153def main():
154    ap = argparse.ArgumentParser()
155    ap.add_argument("--helper", required=True)
156    ap.add_argument("--compare", required=True)
157    ap.add_argument("--mmproj", required=True)
158    ap.add_argument("--model", required=True)
159    ap.add_argument("--out", required=True)
160    ap.add_argument("--max-tokens", type=int, default=1024)
161    ap.add_argument("--threads", type=int, default=12)
162    ap.add_argument("--repeat", type=int, default=4)
163    ap.add_argument("--min-cos", type=float, default=0.999)
164    ap.add_argument("--ref-dir", default="")
165    ap.add_argument("--cpu-dir", default="")
166    ap.add_argument("--skip-cpu", action="store_true", help="no mtmd-CPU run: for pictures at the largest token limit (the columns then compare the two GPU readers)")
167    ap.add_argument("images", nargs="+")
168    a = ap.parse_args()
169    for d in ("ref-cpu", "mtmd-cpu", "mtmd-gpu", "own-gpu"):
170        os.makedirs(os.path.join(a.out, d), exist_ok=True)
171    mk = lambda tower, gpu, label, env=None: Reader(a.helper, tower, a.mmproj, a.model, gpu, a.max_tokens, a.threads, a.out, label, env)  # noqa: E731
172    ref_of = lambda name: os.path.join(a.ref_dir, name + ".sve") if a.ref_dir and os.path.isfile(os.path.join(a.ref_dir, name + ".sve")) else None  # noqa: E731
173    need_ref = not a.skip_cpu and any(ref_of(os.path.basename(i)) is None for i in a.images)
174    r_ref = mk("own", False, "ref-cpu", {"STRATA_VIT_CPU": "ref"}) if need_ref else None     # the float32 reference, made here where --ref-dir lacks it
175    r_cpu = None if (a.cpu_dir or a.skip_cpu) else mk("mtmd", False, "mtmd-cpu")
176    r_mg = mk("mtmd", True, "mtmd-gpu")
177    r_og = mk("own", True, "own-gpu")
178
179    unrepeatable = []      # own-gpu pictures whose output bytes changed between encodes in one process
180
181    def digest(path):
182        with open(path, "rb") as f:
183            return hashlib.sha256(f.read()).hexdigest()
184
185    def run(r, img, name, repeat=None):
186        out = os.path.join(a.out, r.label, name + ".sve")
187        res = r.enc(os.path.abspath(img), out)
188        if not res.startswith("OK"):
189            return out, None, res
190        ms = []
191        seen = {digest(out)} if r is r_og else set()
192        for _ in range(a.repeat if repeat is None else repeat):
193            again = r.enc(os.path.abspath(img), out)
194            if again.startswith("OK"):
195                ms.append(float(again.split()[4]))
196                if r is r_og:
197                    seen.add(digest(out))
198        if len(seen) > 1:
199            unrepeatable.append("%s (%d different outputs in %d encodes)" % (name, len(seen), a.repeat + 1))
200        return out, statistics.median(ms) if ms else float(res.split()[4]), res
201
202    hdr = "%-22s %6s | %9s %9s %9s | %9s %9s | %8s %8s %6s | %s"
203    print(hdr % ("picture", "tokens", "own/ref", "mtmdG/ref", "own/mtmdG", "own/mtmdC", "tokmin", "mtmdG ms", "own ms", "ratio", "gate"), flush=True)
204    ok_all, main_c, floor_c = True, [], []
205    for img in a.images:
206        name = os.path.basename(img)
207        res_r, res_c, cpu_f = "OK", "OK", None
208        if a.skip_cpu:
209            ref_f = None      # a picture at the largest token limit: the CPU readers would take many minutes; the GPU reader of mtmd is the yardstick
210        else:
211            ref_f = ref_of(name)
212            if ref_f is None:
213                ref_f, _, res_r = run(r_ref, img, name, 0)
214            if a.cpu_dir:
215                cpu_f = os.path.join(a.cpu_dir, name + ".sve")
216            elif r_cpu:
217                cpu_f, _, res_c = run(r_cpu, img, name, 0)
218        mg_f, mg_ms, res_m = run(r_mg, img, name)
219        og_f, og_ms, res_o = run(r_og, img, name)
220        if ref_f is None:
221            ref_f = mg_f
222        if not (str(res_r).startswith("OK") and str(res_c).startswith("OK") and res_m.startswith("OK") and res_o.startswith("OK")) or mg_ms is None or og_ms is None:
223            print("%-22s FAILED: ref=%s mtmd-cpu=%s mtmd-gpu=%s own-gpu=%s" % (name, res_r, res_c, res_m, res_o), flush=True)
224            ok_all = False
225            continue
226        main = cmp(a.compare, og_f, ref_f)
227        floor = cmp(a.compare, mg_f, ref_f)
228        info = cmp(a.compare, og_f, mg_f)
229        info_c = cmp(a.compare, og_f, cpu_f) if cpu_f and os.path.isfile(cpu_f) else None
230        if not (main and floor and info):
231            print("%-22s shapes differ between readers" % name, flush=True)
232            ok_all = False
233            continue
234        m, f = float(main["global"]), float(floor["global"])
235        passed = gate_pass(m, f, a.min_cos, a.skip_cpu)
236        ok_all &= passed
237        main_c.append(m)
238        floor_c.append(f)
239        print(hdr % (name, main["n"], main["global"], floor["global"], info["global"], info_c["global"] if info_c else "-", main["tokmin"], "%.0f" % mg_ms, "%.0f" % og_ms,
240                     "%.2f" % (og_ms / mg_ms), "ok" if passed else "FAIL (%s)" % ("main < %.4f" % a.min_cos if m < a.min_cos else "noisier than mtmd-GPU")), flush=True)
241    vram = "GPU memory of the reader (nvidia-smi / rocm-smi / DRM fdinfo / macOS footprint, peak after the pictures): mtmd-gpu %d MiB, own-gpu %d MiB%s" % (
242        r_mg.peak_mib, r_og.peak_mib, "" if r_og.peak_mib <= r_mg.peak_mib else "  (own is larger)")
243    print("REPEATABLE own-gpu: %s" % ("yes, every picture byte-identical over %d encodes" % (a.repeat + 1) if not unrepeatable else "NO: " + "; ".join(unrepeatable)),
244          flush=True)
245    for r in (r_ref, r_cpu, r_mg, r_og):
246        if r:
247            r.close()
248    print(vram, flush=True)
249    if main_c:
250        print("SUMMARY own GPU vs float32: %d pictures, min %.6f mean %.6f; mtmd GPU vs float32 (the floor): min %.6f mean %.6f" %
251              (len(main_c), min(main_c), sum(main_c) / len(main_c), min(floor_c), sum(floor_c) / len(floor_c)), flush=True)
252    print("RESULT %s" % ("PASS" if ok_all and main_c else "FAIL"), flush=True)
253    return 0 if ok_all and main_c else 1
254
255
256if __name__ == "__main__":
257    sys.exit(main())