adriandj3's picture
TernaryPilot v2 adapter (rank 64, F16) and fixed benchmark runner
b0693db verified
Raw History Blame Contribute Delete
9.06 kB
"""Public benchmarks, base model vs one or more LoRAs on the same server: every case is asked once per arm (base = all
adapters at scale 0, then each adapter alone at scale 1), same image payload, greedy.
ss2 ScreenSpot-v2 (OS-Copilot/ScreenSpot-v2), 1,272 instructions, hit = point inside the box
sspro ScreenSpot-Pro (likaixin/ScreenSpot-Pro), 1,581 instructions on professional apps, hit = point inside the box
g360g GUI-360-Bench grounding (vyokky/GUI-360 test): the agent's thought -> point inside the control rectangle
g360a GUI-360-Bench action prediction: task + history -> action type right and, for click/type, point inside the rectangle
Usage:
python banco_pubblico.py --server llama-server --model M.gguf --mmproj P.gguf --lora v2.gguf v1.gguf --names v2 v1 \
--bench ss2 --data DIR --out res.jsonl [--limit N] [--parallel 4]
"""
import argparse
import base64
import concurrent.futures as cf
import glob
import io
import json
import os
import random
import re
import subprocess
import sys
import time
import urllib.request
from PIL import Image
import make_data as md
def png(im):
b = io.BytesIO()
im.save(b, "PNG")
return {"type": "image_url", "image_url": {"url": "data:image/png;base64," + base64.b64encode(b.getvalue()).decode()}}
def post(port, body, timeout=600):
r = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", json.dumps(body).encode(),
{"Content-Type": "application/json"})
return json.loads(urllib.request.urlopen(r, timeout=timeout).read())
def chiedi(port, img, testo, scale, max_tok): # img: the png() payload, built once per case
body = {"messages": [{"role": "user", "content": [img, {"type": "text", "text": testo}]}], "temperature": 0,
"max_tokens": max_tok, "chat_template_kwargs": {"enable_thinking": False},
"lora": [{"id": i, "scale": s} for i, s in enumerate(scale)]}
return post(port, body)["choices"][0]["message"].get("content") or ""
def punto(testo): # first x/y pair on the 0-1000 grid
m = re.search(r'"x"\s*:\s*(-?\d+).*?"y"\s*:\s*(-?\d+)', testo, re.S) or re.search(r"x\s*=\s*(-?\d+)\s*,\s*y\s*=\s*(-?\d+)", testo)
return (int(m.group(1)), int(m.group(2))) if m else None
def dentro(p, im, box): # p on the 0-1000 grid, box (x1, y1, x2, y2) in pixels of im
if not p:
return False
x, y = p[0] * im.size[0] / 1000, p[1] * im.size[1] / 1000
return box[0] <= x <= box[2] and box[1] <= y <= box[3]
def casi_ss2(d):
for f in sorted(glob.glob(f"{d}/screenspot_*_v2.json")):
for r in json.load(open(f, encoding="utf-8")):
x, y, w, h = r["bbox"]
yield {"img": f"{d}/screenspotv2_image/{r['img_filename']}", "testo": md.P_CLIC + r["instruction"], "box": (x, y, x + w, y + h),
"gruppo": f"{os.path.basename(f).split('_')[1]}-{r['data_type']}", "tipo": "click"}
def casi_sspro(d):
for f in sorted(glob.glob(f"{d}/annotations/*.json")):
for r in json.load(open(f, encoding="utf-8")):
yield {"img": f"{d}/images/{r['img_filename']}", "testo": md.P_CLIC + r["instruction"], "box": tuple(r["bbox"]),
"gruppo": f"{r['group']}-{r['ui_type']}", "tipo": "click"}
def casi_g360(d, azioni):
for f in sorted(glob.glob(f"{d}/test/data/*/*/success/*.jsonl")):
app, cat = f.replace("\\", "/").split("/")[-4:-2]
storia = []
for riga in open(f, encoding="utf-8"):
r = json.loads(riga)
s, a = r["step"], r["step"]["action"]
img = f"{d}/test/image/{app}/{cat}/{s['screenshot_clean']}"
rect = a.get("rectangle") or {}
box = (rect.get("left"), rect.get("top"), rect.get("right"), rect.get("bottom")) if rect else None
f_ = a.get("function")
if a.get("action_type") == "GUI" and box and None not in box and os.path.exists(img):
if azioni and f_ in ("click", "type", "drag", "wheel_mouse_input"):
yield {"img": img, "testo": md.p_azione("Windows computer", r["request"], storia), "box": box, "gruppo": f"{app}-{f_}",
"tipo": "azione", "vero": {"click": "click", "type": "type", "drag": "drag", "wheel_mouse_input": "scroll"}[f_]}
elif not azioni and "grounding" in (s.get("tags") or []) and s.get("thought"):
yield {"img": img, "testo": md.P_CLIC + md.frase(s["thought"], 300), "box": box, "gruppo": app, "tipo": "click"}
storia.append(md.frase(s.get("thought") or "", 160))
def categoria(testo):
m = re.search(r"Action:\s*(.+)", testo, re.S)
corpo = m.group(1) if m else testo
if "write(" in corpo:
return "type"
t = re.match(r"\s*(\w+)\(", corpo)
if not t:
return None
n = t.group(1)
return {"click": "click", "double_click": "click", "right_click": "click", "drag": "drag", "scroll": "scroll",
"move": "drag" if "drag(" in corpo else "scroll" if "scroll(" in corpo else "move"}.get(n, n)
def valuta(c, testo, im):
if c["tipo"] == "click":
return dentro(punto(testo), im, c["box"])
cat = categoria(testo)
if cat != c["vero"]:
return False
return dentro(punto(testo), im, c["box"]) if cat in ("click", "type") else True
class Server:
def __init__(self, a):
self.a, self.p = a, None
def __enter__(self):
a = self.a
cmd = [a.server, "-m", a.model, "--mmproj", a.mmproj, "--lora-scaled", ",".join(f"{x}:0" for x in a.lora),
"--image-max-tokens", "1024", "-ngl", "999", "-fa", "on", "--jinja", "-c", str(16384 * a.parallel),
"--parallel", str(a.parallel), "--port", str(a.port), "--cache-ram", "0"] # prompt cache in host RAM: 8 GiB per server by default
self.log = open(a.out + ".server.log", "w")
self.p = subprocess.Popen(cmd, stdout=self.log, stderr=subprocess.STDOUT)
for _ in range(900):
try:
with urllib.request.urlopen(f"http://127.0.0.1:{a.port}/health", timeout=2) as r:
if r.status == 200:
return self
except Exception:
time.sleep(1)
if self.p.poll() is not None:
sys.exit("server exited, see " + self.log.name)
sys.exit("server not ready")
def __exit__(self, *e):
self.p.terminate()
self.p.wait(timeout=60)
def main():
ap = argparse.ArgumentParser()
for k in ("server", "model", "mmproj", "bench", "data", "out"):
ap.add_argument("--" + k, required=True)
ap.add_argument("--lora", nargs="+", required=True), ap.add_argument("--names", nargs="+")
ap.add_argument("--limit", type=int, default=0), ap.add_argument("--parallel", type=int, default=4)
ap.add_argument("--port", type=int, default=8791), ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
casi = list({"ss2": lambda: casi_ss2(a.data), "sspro": lambda: casi_sspro(a.data), "g360g": lambda: casi_g360(a.data, False),
"g360a": lambda: casi_g360(a.data, True)}[a.bench]())
if a.limit and len(casi) > a.limit:
casi = random.Random(a.seed).sample(casi, a.limit)
max_tok = 64 if a.bench in ("ss2", "sspro", "g360g") else 256
nomi = a.names or [f"lora{i}" for i in range(len(a.lora))]
assert len(nomi) == len(a.lora)
bracci = [("base", [0.0] * len(a.lora))] + [(n, [float(i == j) for j in range(len(a.lora))]) for i, n in enumerate(nomi)]
def uno(c):
im = Image.open(c["img"]).convert("RGB")
img = png(im)
r = {"gruppo": c["gruppo"], "img": os.path.basename(c["img"])}
for nome, scale in bracci:
t0 = time.time()
testo = chiedi(a.port, img, c["testo"], scale, max_tok)
r[nome] = {"ok": valuta(c, testo, im), "s": round(time.time() - t0, 2), "out": testo[-200:]}
return r
tot = {k: 0 for k, _ in bracci}
per = {}
with Server(a), cf.ThreadPoolExecutor(a.parallel) as ex, open(a.out, "w", encoding="utf-8") as fo:
for i, r in enumerate(ex.map(uno, casi)):
fo.write(json.dumps(r, ensure_ascii=False) + "\n")
g = per.setdefault(r["gruppo"], {"n": 0, **{k: 0 for k in tot}})
g["n"] += 1
for k in tot:
tot[k] += r[k]["ok"]
g[k] += r[k]["ok"]
if (i + 1) % 100 == 0:
print(f"{i + 1}/{len(casi)} " + " ".join(f"{k} {v}" for k, v in tot.items()), flush=True)
n = len(casi)
riass = {"bench": a.bench, "n": n, **tot, **{k + "_pct": round(100 * v / n, 1) for k, v in tot.items()}, "per_gruppo": per}
print(json.dumps(riass), flush=True)
json.dump(riass, open(a.out + ".summary.json", "w"), indent=1)
if __name__ == "__main__":
main()