Download generic.py from Jacqkues/sev-generic-bench: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/datasets/Jacqkues/sev-generic-bench/resolve/main/generic.py
- Command line
-
hf download hf://datasets/Jacqkues/sev-generic-bench/generic.py
-
curl -L -o generic.py https://huggingface.co/datasets/Jacqkues/sev-generic-bench/resolve/main/generic.py
12 kB
| """Generic vision benchmark: public multiple-choice and yes/no VLM benchmarks that no Sev model was trained on. | |
| mmstar Lin-Chen/MMStar (1500, vision-indispensable A-D questions; its ScienceQA items are dropped) | |
| mmbench lmms-lab/MMBench en/dev (A-D, 1000 sampled; its ScienceQA items are dropped: Sev trained on ScienceQA) | |
| mme lmms-lab/MME (yes/no, 14 perception and cognition subtasks) | |
| realworldqa xai-org/RealworldQA (lettered options or yes/no; numeric/free-form answers are dropped) | |
| hallusion lmms-lab/HallusionBench image split (yes/no on charts, tables, maps, illusions) | |
| Each item becomes one question: "choice" with the lettered options as criteria, or "noul". Sev models answer in one | |
| forward pass. The baseline is Qwen/Qwen3.5-0.8B (the post-trained VLM Sev's backbone comes from) in zero-shot: its | |
| answer distribution is its next-token probability over the option letters (or Yes/No) after the question, so the same | |
| calibration metrics apply. All models see the image at the same resolution cap (448 x 448 pixels). | |
| uv run modal run modal_app.py::generic_build # -> /vol/data/generic.parquet | |
| KEV_GPU=L4 uv run modal run modal_app.py::generic_eval --runs "Jacqkues/sev-0.8b,Jacqkues/sev-0.8b-docindex,qwen:Qwen/Qwen3.5-0.8B" | |
| """ | |
| import argparse, ast, io, json, random, re | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| LETTERS = "ABCDEFGH" | |
| YESNO = re.compile(r"\s*(please answer (yes or no|directly with a single word or number)\.?)\s*$", re.I) | |
| def _img(v): | |
| return v["bytes"] if isinstance(v, dict) else v | |
| def _read(repo, prefix, columns=None): | |
| from kev_vision.sources import _files, _pf | |
| for f in _files(repo, prefix): | |
| pfile = _pf(repo, f) | |
| for b in pfile.iter_batches(batch_size=200, columns=columns): | |
| yield from b.to_pylist() | |
| def _choice(bench, cat, question, options, answer, image, hint=None): | |
| keys = [k for k in LETTERS if k in options] | |
| if answer not in keys or len(keys) < 2: return None | |
| return {"bench": bench, "category": cat, "type": "choice", "question": question.strip(), "hint": hint, | |
| "options": json.dumps({k: options[k] for k in keys}), "label": keys.index(answer), "image": image} | |
| def _noul(bench, cat, question, yes, image): | |
| return {"bench": bench, "category": cat, "type": "noul", "question": YESNO.sub("", question).strip(), "hint": None, | |
| "options": None, "label": int(yes), "image": image} | |
| def mmstar(): | |
| for r in _read("Lin-Chen/MMStar", ""): | |
| meta = r.get("meta_info") or {} | |
| if isinstance(meta, str): meta = ast.literal_eval(meta) | |
| if "scienceqa" in str(meta.get("source", "")).lower(): continue | |
| q, _, opts = r["question"].partition("\nOptions:") | |
| found = dict(re.findall(r"([A-D]):\s*(.*?)(?=,\s*[A-D]:|$)", opts.strip(), re.S)) | |
| found = {k: v.strip().rstrip(".").strip() for k, v in found.items()} | |
| yield _choice("mmstar", r["category"], q, found, r["answer"].strip(), _img(r["image"])) | |
| def mmbench(n=1000, seed=0): | |
| rows = [r for r in _read("lmms-lab/MMBench", "en/dev-") if r["source"] != "scienceqa"] | |
| for r in random.Random(seed).sample(rows, min(n, len(rows))): | |
| opts = {k: str(r[k]) for k in "ABCD" if r.get(k) is not None and str(r[k]) != "nan"} | |
| hint = r["hint"] if r.get("hint") and str(r["hint"]) != "nan" else None | |
| yield _choice("mmbench", r["category"], r["question"], opts, r["answer"], _img(r["image"]), hint) | |
| def mme(): | |
| for r in _read("lmms-lab/MME", "data/test-"): | |
| if r["answer"] not in ("Yes", "No"): continue | |
| yield _noul("mme", r["category"], r["question"], r["answer"] == "Yes", _img(r["image"])) | |
| def realworldqa(): | |
| for r in _read("xai-org/RealworldQA", "data/test-"): | |
| q, a = r["question"], r["answer"].strip().rstrip(".") | |
| lines = q.split("\n") | |
| opts = {m.group(1): m.group(2).strip() for l in lines if (m := re.match(r"^([A-F])[.)]\s*(.+)$", l.strip()))} | |
| if opts and a in opts: | |
| stem = "\n".join(l for l in lines if not re.match(r"^([A-F])[.)]\s", l.strip())) | |
| stem = re.sub(r"please answer directly with (only )?the letter.*$", "", stem, flags=re.I | re.S).strip() | |
| yield _choice("realworldqa", "realworld", stem, opts, a, _img(r["image"])) | |
| elif a.lower() in ("yes", "no"): | |
| yield _noul("realworldqa", "realworld", q, a.lower() == "yes", _img(r["image"])) | |
| def hallusion(): | |
| for r in _read("lmms-lab/HallusionBench", "data/image-"): | |
| if str(r.get("visual_input")) == "0" or r.get("image") is None: continue | |
| yield _noul("hallusion", f'{r["category"]}/{r["subcategory"]}', r["question"], str(r["gt_answer"]) == "1", _img(r["image"])) | |
| BENCHES = {"mmstar": mmstar, "mmbench": mmbench, "mme": mme, "realworldqa": realworldqa, "hallusion": hallusion} | |
| def build(out): | |
| from kev_vision.sources import encode | |
| rows = [] | |
| for name, fn in BENCHES.items(): | |
| got = [r for r in fn() if r is not None] | |
| for i, r in enumerate(got): r["id"] = f"{name}-{i}"; r["image"] = encode(r["image"], 896) | |
| print(f"{name}: {len(got)} items, {sum(r['type'] == 'noul' for r in got)} yes/no", flush=True) | |
| rows += got | |
| pq.write_table(pa.Table.from_pylist(rows), out, row_group_size=500) | |
| print(f"{len(rows)} items -> {out}", flush=True) | |
| # --- models ------------------------------------------------------------------------------------------------------------- | |
| class SevScorer: | |
| def __init__(self, run, device): | |
| from kev_vision.model import VisionDecisionModel | |
| self.model = VisionDecisionModel(run, device).eval() | |
| self.T = self.model.head.temperature | |
| def logits(self, item, image): | |
| import torch | |
| from kev.api import SystemOneRequest, to_record | |
| q = {"type": item["type"], "instructions": item["question"]} | |
| if item["type"] == "choice": q["criteria"] = json.loads(item["options"]) | |
| state = (item["hint"] + "\n" if item["hint"] else "") + "An image is attached." | |
| rec, _ = to_record(SystemOneRequest.model_validate({"state": state, "questions": {"q": q}})) | |
| rec["image"] = image | |
| with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=str(self.model.device).startswith("cuda")): | |
| return (self.model.forward_records([rec])[0][0].float().cpu().double() / self.T).numpy() | |
| class QwenScorer: | |
| """Zero-shot generative VLM: next-token probabilities over the option letters (or Yes/No).""" | |
| def __init__(self, repo, device): | |
| import torch | |
| from transformers import AutoModelForImageTextToText, AutoProcessor | |
| self.proc = AutoProcessor.from_pretrained(repo, min_pixels=128 * 128, max_pixels=448 * 448) | |
| self.model = AutoModelForImageTextToText.from_pretrained(repo, dtype=torch.bfloat16).to(device).eval() | |
| self.device, self.T = device, 1.0 | |
| tok = self.proc.tokenizer | |
| self.ids = {w: tok.encode(w, add_special_tokens=False)[0] for w in list(LETTERS) + ["Yes", "No"]} | |
| def logits(self, item, image): | |
| import torch | |
| if item["type"] == "choice": | |
| opts = json.loads(item["options"]) | |
| text = (item["hint"] + "\n" if item["hint"] else "") + item["question"] + "\n" + "\n".join(f"{k}. {v}" for k, v in opts.items()) | |
| text += "\nAnswer with the option's letter from the given choices directly." | |
| cands = list(opts) | |
| else: | |
| text, cands = item["question"] + "\nAnswer with Yes or No.", ["No", "Yes"] | |
| msgs = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": text}]}] | |
| try: prompt = self.proc.apply_chat_template(msgs, add_generation_prompt=True, enable_thinking=False) | |
| except TypeError: prompt = self.proc.apply_chat_template(msgs, add_generation_prompt=True) | |
| inputs = self.proc(text=[prompt], images=[image], return_tensors="pt").to(self.device) | |
| with torch.no_grad(): | |
| z = self.model(**inputs).logits[0, -1].float().cpu() | |
| return np.array([z[self.ids[c]].item() for c in cands], dtype=np.float64) | |
| def _metrics(rows): | |
| p = [np.exp(r["z"] - r["z"].max()) / np.exp(r["z"] - r["z"].max()).sum() for r in rows] | |
| y = np.array([r["label"] for r in rows]); pred = np.array([int(np.argmax(x)) for x in p]); conf = np.array([x.max() for x in p]) | |
| ok = (pred == y).astype(float) | |
| brier = float(np.mean([((x - np.eye(len(x))[l]) ** 2).sum() for x, l in zip(p, y)])) | |
| bins = np.minimum((conf * 10).astype(int), 9) | |
| ece = float(sum(abs(ok[bins == b].mean() - conf[bins == b].mean()) * (bins == b).mean() for b in range(10) if (bins == b).any())) | |
| order = np.argsort(-conf); err = np.cumsum(1 - ok[order]) / np.arange(1, len(ok) + 1) | |
| cov = float((np.max(np.nonzero(err <= 0.05)[0]) + 1) / len(ok)) if (err <= 0.05).any() else 0.0 | |
| out = {"n": len(rows), "acc": round(float(ok.mean()), 3), "brier": round(brier, 3), "ece": round(ece, 3), | |
| "confident_errors": round(float(((conf >= 0.9) & (ok == 0)).mean()), 3), "coverage_at_5pct_error": round(cov, 3), | |
| "chance": round(float(np.mean([1 / len(x) for x in p])), 3)} | |
| if all(len(x) == 2 for x in p): | |
| py = np.array([x[1] for x in p]); pos, neg = py[y == 1], py[y == 0] | |
| if len(pos) and len(neg): out["auroc"] = round(float((pos[:, None] > neg[None, :]).mean() + 0.5 * (pos[:, None] == neg[None, :]).mean()), 3) | |
| return out | |
| def evaluate(data, runs, device, out, n=None): | |
| from PIL import Image | |
| items = [r for b in pq.ParquetFile(data).iter_batches(batch_size=200) for r in b.to_pylist()][: n or None] | |
| report = json.loads(Path(out).read_text()) if Path(out).exists() else {} | |
| for run in runs: | |
| if run in report: print(f"{run}: already in {out}", flush=True); continue | |
| scorer = QwenScorer(run.split(":", 1)[1], device) if run.startswith("qwen:") else SevScorer(run, device) | |
| rows = [] | |
| for i, it in enumerate(items): | |
| z = scorer.logits(it, Image.open(io.BytesIO(it["image"])).convert("RGB")) | |
| rows.append({"id": it["id"], "bench": it["bench"], "category": it["category"], "label": it["label"], "z": z}) | |
| if i % 500 == 0: print(f"{run}: {i}/{len(items)}", flush=True) | |
| rep = {"temperature": scorer.T, "all": _metrics(rows)} | |
| by = defaultdict(list) | |
| for r in rows: by[r["bench"]].append(r) | |
| for b, rs in by.items(): | |
| cats = defaultdict(list) | |
| for r in rs: cats[r["category"]].append(r) | |
| rep[b] = {**_metrics(rs), "per_category": {c: _metrics(v)["acc"] for c, v in sorted(cats.items())}} | |
| print(f"{run} {b:>12}: {({k: v for k, v in rep[b].items() if k != 'per_category'})}", flush=True) | |
| report[run] = rep | |
| with open(str(out).replace(".json", ".preds.jsonl"), "a") as f: # per item: re-slice later (e.g. contamination) | |
| for r in rows: f.write(json.dumps({"run": run, "id": r["id"], "bench": r["bench"], "category": r["category"], | |
| "label": r["label"], "z": r["z"].tolist()}) + "\n") | |
| Path(out).parent.mkdir(parents=True, exist_ok=True); Path(out).write_text(json.dumps(report, indent=2)) | |
| del scorer | |
| print(f"saved {out}", flush=True) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| b = sub.add_parser("build"); b.add_argument("--out", required=True) | |
| e = sub.add_parser("eval"); e.add_argument("--data", required=True); e.add_argument("--runs", nargs="+", required=True) | |
| e.add_argument("--device", default="cuda"); e.add_argument("--out", required=True); e.add_argument("--n", type=int, default=None) | |
| a = ap.parse_args() | |
| if a.cmd == "build": build(a.out) | |
| else: evaluate(a.data, a.runs, a.device, a.out, a.n) | |
| if __name__ == "__main__": | |
| main() | |