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
8.1 KiB151 linesraw
1#!/usr/bin/env python3
2"""The answers gate of the own vision tower: greedy picture answers of the whole Strata server, one run per picture reader, compared.
3
4    python3 answers_gate.py --box <box.json> --helper <strata-vision> --out <dir> [--towers mtmd,own] [--max-tokens 1024] [--threads N]
5                            [--gpu] [--n-tokens 48] [--question "..."] [--port N] <image> [<image> ...]
6
7For each tower a fresh `serve/server.py` is started (engine + the picture reader `<helper> ... --tower <tower>`, through a one-line wrapper script made
8in <dir>), every picture is sent with each question at temperature 0 (max --n-tokens tokens), and the server is stopped (its own process group only).
9Then the answers of the towers are compared picture by picture: how many are identical, and the differing ones are printed side by side (not
10argued away).  The box file is the one tools of the 145-vis runs use (src, exe, pack, native, ple, profile, mtp, tokenizer, mmproj, lib_dirs, gpu, port).
11Exit 0 when every answer is identical, 1 otherwise.  Standard library plus the repo's tools/strata_bench.py.
12"""
13import argparse
14import base64
15import json
16import os
17import signal
18import stat
19import subprocess
20import sys
21import time
22import urllib.request
23from pathlib import Path
24
25QUESTIONS = ["What text is written in the image? Answer with the text only.",
26             "List every shape in the image with its colour, from left to right. One short line each.",
27             "Which colours do you see? List them, comma separated.",
28             "How many separate shapes are in the picture? Answer with a number."]
29
30
31def main():
32    ap = argparse.ArgumentParser()
33    ap.add_argument("--box", required=True)
34    ap.add_argument("--helper", required=True)
35    ap.add_argument("--out", required=True)
36    ap.add_argument("--towers", default="mtmd,own")
37    ap.add_argument("--max-tokens", type=int, default=1024)
38    ap.add_argument("--threads", type=int, default=0)
39    ap.add_argument("--gpu", action="store_true", help="the picture reader on the GPU (default: the CPU reader)")
40    ap.add_argument("--n-tokens", type=int, default=48)
41    ap.add_argument("--question", action="append", default=[])
42    ap.add_argument("--port", type=int, default=0)
43    ap.add_argument("images", nargs="+")
44    a = ap.parse_args()
45    box = json.load(open(a.box))
46    out = Path(a.out).resolve()
47    (out / "logs").mkdir(parents=True, exist_ok=True)
48    src = Path(box["src"])
49    sys.path.insert(0, str(src / "tools"))
50    sys.path.insert(0, str(src))
51    import strata_bench as SB  # noqa: E402
52
53    port = a.port or int(box.get("port", 8195))
54    base = "http://127.0.0.1:%d" % port
55    questions = a.question or QUESTIONS
56    ctx = 65536
57
58    def get(path, timeout=20):
59        with urllib.request.urlopen(base + path, timeout=timeout) as r:
60            return json.loads(r.read())
61
62    results = {}
63    for spec in a.towers.split(","):
64        # a reader spec: name[+round][:gpu][@tag]  (mtmd, own, mtmd:gpu, own:gpu, mtmd@2 for a second run of the same reader,
65        # own+round and own+round:gpu with STRATA_VIT_REF_ROUND=1 in the reader's environment)
66        name, _, mode = spec.split("@")[0].partition(":")
67        rounding = name.endswith("+round")
68        name = name.replace("+round", "")
69        gpu = a.gpu or mode == "gpu"
70        tower = spec.replace(":", "-").replace("@", "-").replace("+", "-")        # the label of this run in file names and in the report
71        wrap = out / ("reader-%s.sh" % tower)
72        wrap.write_text('#!/bin/sh\n%sexec "%s" "$@" --tower %s\n' % ("export STRATA_VIT_REF_ROUND=1\n" if rounding else "", a.helper, name))
73        wrap.chmod(wrap.stat().st_mode | stat.S_IXUSR)
74        vis = {"exe": str(wrap), "mmproj": box["mmproj"], "model": box["native"], "gpu": gpu, "max_tokens": a.max_tokens}
75        if a.threads and not gpu:
76            vis["threads"] = a.threads
77        cfg = {"exe": box["exe"], "cwd": str(src), "tokenizer": box["tokenizer"], "model_name": "qwen3.8-flash-next-iq3",
78               "log": str(out / "logs" / ("engine-%s.log" % tower)), "lib_dirs": box.get("lib_dirs", []), "port": port, "gpu": box.get("gpu", 0),
79               "gpus_asked": True, "vision": vis,
80               "args": ["--pack", box["pack"], "--native", box["native"], "--ple-gguf", box["ple"], "--expert-profile", box["profile"],
81                        "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", box["mtp"],
82                        "--max-context", str(ctx), "--kv", "int8", "--vision", "--vram-reserve-mib", "700"]}
83        cfgp = out / "logs" / ("cfg-%s.json" % tower)
84        cfgp.write_text(json.dumps(cfg, indent=1))
85        log = open(out / "logs" / ("server-%s.log" % tower), "w")
86        p = subprocess.Popen([sys.executable, str(src / "serve" / "server.py"), "--engine", "strata", "--config", str(cfgp), "--port", str(port)],
87                             stdout=log, stderr=subprocess.STDOUT, cwd=str(src), start_new_session=True)
88        answers = {}
89        try:
90            t0, ok = time.time(), False
91            while time.time() - t0 < 1500:
92                if p.poll() is not None:
93                    raise SystemExit("%s: the server exited (rc %s) while loading, see %s" % (tower, p.returncode, log.name))
94                try:
95                    if get("/v1/status", 5).get("loaded"):
96                        ok = True
97                        break
98                except Exception:  # noqa: BLE001
99                    pass
100                time.sleep(3)
101            if not ok:
102                raise SystemExit("%s: the server did not load in 1500 s" % tower)
103            print("%s: server up after %.0f s" % (tower, time.time() - t0), flush=True)
104            time.sleep(3)
105            for img in a.images:
106                b64 = base64.b64encode(Path(img).read_bytes()).decode()
107                mime = "image/jpeg" if img.lower().endswith((".jpg", ".jpeg")) else "image/png"
108                for qi, q in enumerate(questions):
109                    msgs = [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:%s;base64,%s" % (mime, b64)}},
110                                                          {"type": "text", "text": q}]}]
111                    t1 = time.time()
112                    r = SB.chat(base, "", msgs, a.n_tokens)
113                    key = "%s|q%d" % (os.path.basename(img), qi)
114                    answers[key] = {"text": r.get("text") or "", "err": r.get("err"), "s": round(time.time() - t1, 1)}
115                    print("%s %-28s q%d (%.1f s): %r%s" % (tower, os.path.basename(img), qi, time.time() - t1, answers[key]["text"][:90],
116                                                          "  ERR " + str(r.get("err")) if r.get("err") else ""), flush=True)
117        finally:
118            try:
119                os.killpg(p.pid, signal.SIGTERM)       # our own process group only
120            except ProcessLookupError:
121                pass
122            for _ in range(60):
123                if p.poll() is not None:
124                    break
125                time.sleep(1)
126        results[tower] = answers
127        (out / "answers.json").write_text(json.dumps(results, indent=1))
128
129    towers = list(results)
130    keys = list(results[towers[0]])
131    ok = lambda t, k: results[t].get(k) and not results[t][k]["err"]  # noqa: E731
132    print("ANSWERS, pair by pair (identical / compared):")
133    differing = []
134    for i, ta in enumerate(towers):
135        for tb in towers[i + 1:]:
136            same = sum(1 for k in keys if ok(ta, k) and ok(tb, k) and results[ta][k]["text"] == results[tb][k]["text"])
137            print("  %-14s vs %-14s %d / %d" % (ta, tb, same, len(keys)))
138    for k in keys:
139        texts = {t: (results[t][k]["text"] if ok(t, k) else "ERR " + str(results[t].get(k, {}).get("err"))) for t in towers}
140        if len(set(texts.values())) > 1:
141            differing.append(k)
142    print("%d of %d answers differ between some readers; all of them:" % (len(differing), len(keys)))
143    for k in differing:
144        print("DIFFERS %s" % k)
145        for t in towers:
146            print("  %-14s: %r" % (t, results[t][k]["text"] if ok(t, k) else "ERR " + str(results[t].get(k, {}).get("err"))))
147    return 0 if not differing else 1
148
149
150if __name__ == "__main__":
151    sys.exit(main())