"""eval_vl.py's benchmark (same items, same scoring) against an OpenAI-compatible SGLang server. python eval_sglang.py --url http://127.0.0.1:30000 --n 30 --out plain.json python eval_sglang.py --url http://127.0.0.1:30000 --n 30 --think --out think.json """ import argparse import base64 import io import json import random import re import time from concurrent.futures import ThreadPoolExecutor import pyarrow.parquet as pq import requests from huggingface_hub import hf_hub_download, list_repo_files from PIL import Image SHORT = "\nAnswer the question using a single word or phrase." LETTER = "\nAnswer with the option's letter from the given choices directly." MAX_PIXELS = 640 * 640 def rows_of(repo, prefix, n, seed=0): files = sorted(f for f in list_repo_files(repo, repo_type="dataset") if f.startswith(prefix) and f.endswith(".parquet")) recs = pq.read_table(hf_hub_download(repo, files[0], repo_type="dataset")).to_pylist() random.Random(seed).shuffle(recs) return recs[:n] def norm(s): s = s.lower().strip().rstrip(".") s = re.sub(r"\b(a|an|the)\b", " ", s) return " ".join(s.replace(",", "").split()) def relaxed(pred, gold): try: p, g = float(pred.replace("%", "").replace(",", "")), float(gold.replace("%", "").replace(",", "")) return abs(p - g) <= 0.05 * abs(g) if g else p == g except ValueError: return norm(pred) == norm(gold) def letter(pred): m = re.search(r"\b([A-D])\b", pred.strip()) return m.group(1) if m else pred.strip()[:1].upper() def tasks(n): out = [] for r in rows_of("lmms-lab/textvqa", "data/validation", n): out.append(("textvqa", r["image"], r["question"] + SHORT, lambda p, r=r: min(1.0, sum(norm(p) == norm(a) for a in r["answers"]) / 3))) for r in rows_of("lmms-lab/ChartQA", "data/test", n): out.append(("chartqa", r["image"], r["question"] + SHORT, lambda p, r=r: float(relaxed(p, str(r["answer"]))))) for r in rows_of("lmms-lab/POPE", "data/test", n): out.append(("pope", r["image"], r["question"] + SHORT, lambda p, r=r: float(norm(p).startswith(r["answer"].lower())))) for r in rows_of("lmms-lab/MMBench", "en/dev", n): opts = "".join(f"\n{k}. {r[k]}" for k in "ABCD" if r.get(k) not in (None, "", "nan")) hint = f"{r['hint']}\n" if r.get("hint") not in (None, "", "nan") else "" out.append(("mmbench", r["image"], hint + r["question"] + opts + LETTER, lambda p, r=r: float(letter(p) == r["answer"]))) for r in rows_of("lmms-lab/ai2d", "data/test", n): opts = "".join(f"\n{'ABCD'[i]}. {o}" for i, o in enumerate(r["options"])) out.append(("ai2d", r["image"], r["question"] + opts + LETTER, lambda p, r=r: float(letter(p) == "ABCD"[int(r["answer"])]))) return out def data_url(x): im = Image.open(io.BytesIO(x["bytes"])) if isinstance(x, dict) else x im = im.convert("RGB") w, h = im.size if w * h > MAX_PIXELS: s = (MAX_PIXELS / (w * h)) ** 0.5 im = im.resize((max(28, int(w * s)), max(28, int(h * s)))) buf = io.BytesIO() im.save(buf, "JPEG", quality=92) return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode() def ask(url, model, image, q, think, max_tokens): body = {"model": model, "max_tokens": max_tokens, "temperature": 0, "chat_template_kwargs": {"enable_thinking": think}, "messages": [{"role": "user", "content": [ {"type": "image_url", "image_url": {"url": data_url(image)}}, {"type": "text", "text": q}]}]} t = time.time() r = requests.post(f"{url}/v1/chat/completions", json=body, timeout=1800) r.raise_for_status() d = r.json() msg = d["choices"][0]["message"] text = msg.get("content") or "" reasoning = msg.get("reasoning_content") if reasoning is None and think: reasoning, _, text = text.partition("") if "" in text else (text, "", "") return {"answer": text.strip(), "reasoning": reasoning, "closed": (not think) or "" in (msg.get("content") or "") or msg.get("reasoning_content") is not None and bool(text.strip()), "tokens": d.get("usage", {}).get("completion_tokens"), "seconds": round(time.time() - t, 1)} def main(): ap = argparse.ArgumentParser() ap.add_argument("--url", default="http://127.0.0.1:30000") ap.add_argument("--model", default="kaivoss/Clover-Preview-VL") ap.add_argument("--n", type=int, default=30) ap.add_argument("--think", action="store_true") ap.add_argument("--max-tokens", type=int, default=0) ap.add_argument("-j", type=int, default=4) ap.add_argument("--out", required=True) args = ap.parse_args() max_tokens = args.max_tokens or (2048 if args.think else 32) items = tasks(args.n) t0 = time.time() def run(item): name, image, q, score = item try: r = ask(args.url, args.model, image, q, args.think, max_tokens) except Exception as e: r = {"answer": f"", "reasoning": None, "closed": False} return {"task": name, "q": q, **r, "score": score(r["answer"])} with ThreadPoolExecutor(args.j) as pool: results = list(pool.map(run, items)) scores = {} for r in results: scores.setdefault(r["task"], []).append(r["score"]) summary = {k: round(100 * sum(v) / len(v), 1) for k, v in scores.items()} summary["mean"] = round(sum(summary.values()) / len(summary), 1) if args.think: summary["closed_think"] = sum(bool(r["closed"]) for r in results) toks = sorted(r.get("tokens") or 0 for r in results) summary["median_completion_tokens"] = toks[len(toks) // 2] summary["n"] = len(results) summary["minutes"] = round((time.time() - t0) / 60, 1) json.dump({"summary": summary, "results": results}, open(args.out, "w"), indent=1, ensure_ascii=False) print(json.dumps(summary), flush=True) if __name__ == "__main__": main()