IslamMesabah's picture
Upload folder using huggingface_hub
bcb32e0 verified
Raw History Blame Contribute Delete
8.34 kB
"""
Minimal MYOPIA evaluation harness.
Runs a vision-language model behind any OpenAI-compatible chat endpoint on one
MYOPIA split, either zero-shot or by walking the released decision tree one
question at a time, and scores the result. Prompts, answer parsing and image
encoding follow the paper's primary condition (no history, no descriptions).
# tree-based inference on GTSRB with GPT-4o via OpenRouter
export OPENROUTER_API_KEY=...
python evaluate.py run --dataset gtsrb --method tree \
--model openai/gpt-4o --base-url https://openrouter.ai/api/v1 \
--api-key-env OPENROUTER_API_KEY --out gtsrb_tree_gpt4o.jsonl
# accuracy of a predictions file
python evaluate.py score gtsrb_tree_gpt4o.jsonl
`--source` is either a local copy of the benchmark (default: the folder this
script ships in) or a Hugging Face dataset id. Runs resume: image ids already
present in `--out` are skipped.
"""
import argparse
import base64
import io
import json
import os
import re
import time
from pathlib import Path
DATASET_NAMES = {"gtsrb": "GTSRB", "mnist": "MNIST", "cifar10": "CIFAR-10", "mscoco": "MSCOCO"}
LOCAL_ROOT = Path(__file__).resolve().parent.parent
# ----------------------------------------------------------------- loading
def resolve(source, filename):
"""Path to `filename` inside a local benchmark copy or a Hub dataset repo."""
if Path(source).is_dir():
return Path(source) / filename
from huggingface_hub import hf_hub_download
return Path(hf_hub_download(source, filename, repo_type="dataset"))
def load_split(source, key):
from datasets import load_dataset
return load_dataset("parquet", data_files=str(resolve(source, f"data/{key}/test.parquet")), split="train")
def load_json(source, filename):
return json.loads(resolve(source, filename).read_text())
def encode_image(example):
"""Base64 JPEG, as in the paper's harness. MSCOCO images are fetched by URL."""
from PIL import Image
image = example["image"]
if image is None:
import requests
response = requests.get(example["image_url"], timeout=60)
response.raise_for_status()
image = Image.open(io.BytesIO(response.content))
buf = io.BytesIO()
image.convert("RGB").save(buf, format="JPEG")
return base64.b64encode(buf.getvalue()).decode("utf-8")
# --------------------------------------------------------------- inference
class Model:
def __init__(self, model, base_url, api_key, temperature, max_tokens):
from openai import OpenAI
self.client = OpenAI(base_url=base_url, api_key=api_key)
self.model = model
self.temperature = temperature
self.max_tokens = max_tokens
def ask(self, text, image_b64):
completion = self.client.chat.completions.create(
model=self.model,
temperature=self.temperature,
max_tokens=self.max_tokens,
messages=[{"role": "user", "content": [
{"type": "text", "text": text},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}},
]}],
)
return completion.choices[0].message.content or ""
def zero_shot(model, image_b64, prompt_template, class_names):
class_names_str = ", ".join(f"{i}: {class_names[str(i)]}" for i in sorted(int(k) for k in class_names))
response = model.ask(prompt_template.replace("{class_names_str}", class_names_str), image_b64)
# First integer in the response; -1 if absent or not a valid class id.
match = re.search(r"^\D*(\d+)", response)
if match and str(int(match.group(1))) in class_names:
return int(match.group(1)), response
return -1, response
def tree_walk(model, image_b64, tree, sleep):
"""Ask each node's question until a leaf is reached; -1 if an answer cannot be parsed."""
node, path = tree["root"], []
while "question" in node:
response = model.ask(tree["node_prompt"].format(question=node["question"], answers=node["answers"]), image_b64)
# Longest answers first so e.g. "no entry" is not matched as "no".
answers = sorted(node["answers"], key=len, reverse=True)
match = re.search("(" + "|".join(rf"\b{re.escape(a.lower())}\b" for a in answers) + ")", response.lower())
if not match:
path.append({"question": node["question"], "answer": response.strip()})
return -1, path
answer = next(a for a in answers if a.lower() == match.group(1))
path.append({"question": node["question"], "answer": answer})
node = node["children"][answer]
time.sleep(sleep)
return node["label"], path
def run(args):
split = load_split(args.source, args.dataset)
class_names = load_json(args.source, f"data/{args.dataset}/class_names.json")
tree = load_json(args.source, f"trees/{args.dataset}.json")
prompts = load_json(args.source, f"prompts/{DATASET_NAMES[args.dataset]}/zs_prompts.json")["prompts"]
model = Model(args.model, args.base_url, os.environ.get(args.api_key_env, ""), args.temperature, args.max_tokens)
out = Path(args.out)
done = set()
if out.exists():
done = {json.loads(line)["image_id"] for line in out.read_text().splitlines() if line.strip()}
todo = [i for i, image_id in enumerate(split["image_id"]) if image_id not in done][: args.limit]
print(f"{args.dataset}: {len(done)} done, running {len(todo)}")
with out.open("a") as f:
for n, i in enumerate(todo, 1):
example = split[i]
image_b64 = encode_image(example)
if args.method == "tree":
prediction, output = tree_walk(model, image_b64, tree, args.sleep)
else:
prediction, output = zero_shot(model, image_b64, prompts[args.prompt_id], class_names)
f.write(json.dumps({
"image_id": example["image_id"], "label": example["label"], "prediction": prediction,
"method": args.method, "model": args.model, "output": output,
}, ensure_ascii=False) + "\n")
f.flush()
if n % 25 == 0:
print(f" {n}/{len(todo)}")
score(argparse.Namespace(predictions=[str(out)]))
# ----------------------------------------------------------------- scoring
def score(args):
for path in args.predictions:
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
correct = sum(r["prediction"] == r["label"] for r in rows)
invalid = sum(r["prediction"] == -1 for r in rows)
print(f"{path}: accuracy {100 * correct / max(len(rows), 1):.2f}% "
f"({correct}/{len(rows)}), unparseable {invalid}")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="command", required=True)
r = sub.add_parser("run", help="run a model on one split")
r.add_argument("--dataset", choices=sorted(DATASET_NAMES), required=True)
r.add_argument("--method", choices=["tree", "zero_shot"], required=True)
r.add_argument("--model", required=True, help="model name as the endpoint expects it")
r.add_argument("--base-url", required=True, help="OpenAI-compatible endpoint")
r.add_argument("--api-key-env", default="OPENAI_API_KEY", help="environment variable holding the API key")
r.add_argument("--source", default=str(LOCAL_ROOT), help="local benchmark folder or Hugging Face dataset id")
r.add_argument("--out", required=True, help="predictions JSONL (appended to, resumable)")
r.add_argument("--temperature", type=float, default=0.7)
r.add_argument("--max-tokens", type=int, default=100)
r.add_argument("--prompt-id", type=int, default=0, choices=range(10), help="zero-shot paraphrase (paper: 0)")
r.add_argument("--sleep", type=float, default=1.0, help="seconds between tree questions")
r.add_argument("--limit", type=int, help="evaluate at most this many new images")
r.set_defaults(func=run)
s = sub.add_parser("score", help="score one or more predictions files")
s.add_argument("predictions", nargs="+")
s.set_defaults(func=score)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()