okami.mom/strata

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

Niko1221Merge f-own-3v (aec86299d) into f-own-int: our own Qwen vision tower (mtmd stays the default)0479b72e9

main
6.7 KiB141 linesraw
1#!/usr/bin/env python3
2"""Runs strata-vision twice (--tower A and --tower B, default mtmd and own) over the same pictures and compares the embeddings.
3
4    python compare_towers.py --helper <strata-vision> --compare <strata-vision-own-compare> --mmproj <mmproj.gguf> --model <text model .gguf>
5                             --out <dir> [--a mtmd] [--b own] [--gpu] [--threads N] [--max-tokens N] [--min-tokens N]
6                             [--repeat K] [--env NAME=VALUE ...] <image> [<image> ...]
7
8Per picture: the tokens, the time of each tower (the first encode, then --repeat K further encodes of the same picture, median reported), and the
9cosine of the two embedding files (global = both files as one vector; tokmin / tokmean = per-token cosines), max |difference|.
10The last lines are the summary the gate asks for: minimum and mean cosine over the pictures.  Exit 0 when every picture was read by both and
11the minimum global cosine is at least --min-cos (default 0.999); 1 otherwise.  Standard library only.
12"""
13import argparse
14import os
15import statistics
16import subprocess
17import sys
18import time
19
20
21class Reader:
22    def __init__(self, exe, tower, a, gpu, label):
23        args = [exe, "--mmproj", a.mmproj, "--model", a.model, "--tower", tower]
24        if gpu:
25            args.append("--gpu")
26        if a.threads:
27            args += ["--threads", str(a.threads)]
28        if a.max_tokens:
29            args += ["--max-tokens", str(a.max_tokens)]
30        if a.min_tokens:
31            args += ["--min-tokens", str(a.min_tokens)]
32        env = dict(os.environ)
33        for kv in a.env:
34            k, _, v = kv.partition("=")
35            env[k] = v
36        self.tower = tower
37        self.t0 = time.time()
38        self.p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=open(os.path.join(a.out, label + ".stderr"), "w"),
39                                  text=True, env=env)
40        line = self.p.stdout.readline().strip()
41        self.ready = line.startswith("READY")
42        self.start_s = time.time() - self.t0
43        if not self.ready:
44            raise SystemExit("%s reader did not start: %r" % (tower, line))
45
46    def enc(self, img, out):
47        self.p.stdin.write("ENC %s %s\n" % (img, out))
48        self.p.stdin.flush()
49        return self.p.stdout.readline().strip()
50
51    def close(self):
52        try:
53            self.p.stdin.write("QUIT\n")
54            self.p.stdin.flush()
55            self.p.wait(timeout=30)
56        except Exception:
57            self.p.kill()
58
59
60def main():
61    ap = argparse.ArgumentParser()
62    ap.add_argument("--helper", required=True)
63    ap.add_argument("--compare", required=True)
64    ap.add_argument("--mmproj", required=True)
65    ap.add_argument("--model", required=True)
66    ap.add_argument("--out", required=True)
67    ap.add_argument("--a", default="mtmd")
68    ap.add_argument("--b", default="own")
69    ap.add_argument("--a-dir", default="", help="A's embeddings from an earlier run: <dir>/<picture name>.sve (no reader is started for A)")
70    ap.add_argument("--helper-b", default="", help="another program for B (e.g. strata-vision-own); default: --helper")
71    ap.add_argument("--gpu", action="store_true", help="both readers on the GPU")
72    ap.add_argument("--gpu-a", action="store_true")
73    ap.add_argument("--gpu-b", action="store_true")
74    ap.add_argument("--threads", type=int, default=0)
75    ap.add_argument("--max-tokens", type=int, default=0)
76    ap.add_argument("--min-tokens", type=int, default=0)
77    ap.add_argument("--repeat", type=int, default=0)
78    ap.add_argument("--min-cos", type=float, default=0.999)
79    ap.add_argument("--env", action="append", default=[])
80    ap.add_argument("images", nargs="+")
81    a = ap.parse_args()
82    os.makedirs(a.out, exist_ok=True)
83    la = a.a + ("-gpu" if a.gpu or a.gpu_a else "")
84    lb = a.b + ("-gpu" if a.gpu or a.gpu_b else "")
85    if la == lb:
86        lb += "-2"
87    for t in (la, lb):
88        os.makedirs(os.path.join(a.out, t), exist_ok=True)
89
90    # --a-dir: A's embeddings were made earlier (<dir>/<picture name>.sve, from a run of the same limits); no reader is started for A
91    ra = None if a.a_dir else Reader(a.helper, a.a, a, a.gpu or a.gpu_a, la)
92    rb = Reader(a.helper_b or a.helper, a.b, a, a.gpu or a.gpu_b, lb)
93    if ra:
94        ra.label = la
95    rb.label = lb
96    print("start: %s %.1f s, %s %.1f s" % (la, ra.start_s if ra else 0.0, lb, rb.start_s), flush=True)
97    print("%-24s %11s %6s %9s %9s  %9s %9s %9s %10s" % ("picture", "size", "tokens", la + " ms", lb + " ms", "global", "tokmin", "tokmean", "maxabs"), flush=True)
98    glob, tmin, ok_all = [], [], True
99    for img in a.images:
100        name = os.path.basename(img)
101        outs, res, times = {}, {}, {}
102        for r in (ra, rb):
103            if r is None:
104                outs[la] = os.path.join(a.a_dir, name + ".sve")
105                res[la] = "OK" if os.path.isfile(outs[la]) else "ERR no file " + outs[la]
106                times[la] = float("nan")
107                continue
108            outs[r.label] = os.path.join(a.out, r.label, name + ".sve")
109            res[r.label] = r.enc(os.path.abspath(img), outs[r.label])
110            ms = [float(res[r.label].split()[4])] if res[r.label].startswith("OK") else []
111            for _ in range(a.repeat if ms else 0):
112                again = r.enc(os.path.abspath(img), outs[r.label])
113                if again.startswith("OK"):
114                    ms.append(float(again.split()[4]))
115            times[r.label] = statistics.median(ms[1:] if len(ms) > 1 else ms) if ms else float("nan")
116        if not (res[la].startswith("OK") and res[lb].startswith("OK")):
117            print("%-24s FAILED: %s: %s | %s: %s" % (name, la, res[la], lb, res[lb]), flush=True)
118            ok_all = False
119            continue
120        c = subprocess.run([a.compare, outs[la], outs[lb]], capture_output=True, text=True).stdout.strip()
121        if not c.startswith("n="):
122            print("%-24s %s" % (name, c), flush=True)
123            ok_all = False
124            continue
125        kv = dict(p.split("=") for p in c.split())
126        size = "%sx%s" % (kv["nx"], kv["ny"])
127        glob.append(float(kv["global"]))
128        tmin.append(float(kv["tokmin"]))
129        print("%-24s %11s %6s %9.0f %9.0f  %9s %9s %9s %10s" % (name, size, kv["n"], times[la], times[lb], kv["global"], kv["tokmin"], kv["tokmean"], kv["maxabs"]), flush=True)
130    if ra:
131        ra.close()
132    rb.close()
133    if glob:
134        print("SUMMARY %s vs %s: %d pictures, global cosine min %.6f mean %.6f, smallest per-token cosine %.6f" % (lb, la, len(glob), min(glob), sum(glob) / len(glob), min(tmin)))
135    good = ok_all and glob and min(glob) >= a.min_cos
136    print("RESULT %s (minimum cosine %s %.4f)" % ("PASS" if good else "FAIL", ">=" if good else "below or errors,", a.min_cos), flush=True)
137    return 0 if good else 1
138
139
140if __name__ == "__main__":
141    sys.exit(main())