Datasets:
Download code/run_models.py from spatial-evidence-bench/SpatialEvidenceBench: direct link, hf CLI and curl.
- Browser
- Download file 6.21 kB
-
https://huggingface.co/datasets/spatial-evidence-bench/SpatialEvidenceBench/resolve/5c8b07c8e3679dc7d2dd54b6fae5e27f9d82c4db/code/run_models.py
- Command line
-
hf download hf://datasets/spatial-evidence-bench/SpatialEvidenceBench@5c8b07c8e3679dc7d2dd54b6fae5e27f9d82c4db/code/run_models.py
-
curl -L -o run_models.py https://huggingface.co/datasets/spatial-evidence-bench/SpatialEvidenceBench/resolve/5c8b07c8e3679dc7d2dd54b6fae5e27f9d82c4db/code/run_models.py
6.21 kB
| import argparse | |
| import hashlib | |
| import json | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from PIL import Image | |
| import transformers | |
| AutoModelForCausalLM = transformers.AutoModelForCausalLM | |
| AutoModelForImageTextToText = getattr(transformers, "AutoModelForImageTextToText", None) | |
| AutoProcessor = transformers.AutoProcessor | |
| MODEL_REGISTRY = { | |
| "qwen3vl": {"path": "/repository/models/Qwen3-VL-8B-Instruct", "family": "qwen"}, | |
| "qwen25vl": {"path": "/repository/models/Qwen2.5-VL-7B-Instruct", "family": "qwen"}, | |
| "idefics3": {"path": "/repository/models/Idefics3-8B-Llama3", "family": "idefics3"}, | |
| "internvl3": {"path": "/repository/models/InternVL3-9B-Instruct", "family": "internvl"}, | |
| "molmo2": {"path": "/repository/models/Molmo-7B-D-0924", "family": "molmo"}, | |
| "smolvlm": {"path": "/repository/models/SmolVLM2-2.2B-Instruct", "family": "smolvlm"}, | |
| "phi35v": {"path": "/repository/models/Phi-3.5-vision-instruct", "family": "phi3v"}, | |
| } | |
| MIN_PIXELS = 50176 | |
| MAX_PIXELS = 1048576 | |
| def load(model_key): | |
| entry = MODEL_REGISTRY[model_key] | |
| trust = entry["family"] in ("molmo", "internvl", "phi3v") | |
| processor = AutoProcessor.from_pretrained( | |
| entry["path"], min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS, trust_remote_code=trust | |
| ) | |
| processor._family = entry["family"] | |
| if entry["family"] == "molmo": | |
| model = AutoModelForCausalLM.from_pretrained( | |
| entry["path"], | |
| torch_dtype=torch.bfloat16, | |
| device_map="cuda:0", | |
| trust_remote_code=True, | |
| ) | |
| model.eval() | |
| return processor, model | |
| if entry["family"] == "phi3v": | |
| model = AutoModelForCausalLM.from_pretrained( | |
| entry["path"], | |
| torch_dtype=torch.bfloat16, | |
| device_map="cuda:0", | |
| trust_remote_code=True, | |
| attn_implementation="eager", | |
| ) | |
| model.eval() | |
| return processor, model | |
| model = AutoModelForImageTextToText.from_pretrained( | |
| entry["path"], | |
| torch_dtype=torch.bfloat16, | |
| device_map="cuda:0", | |
| attn_implementation="sdpa", | |
| trust_remote_code=trust, | |
| ) | |
| model.eval() | |
| return processor, model | |
| def yes_no_ids(processor): | |
| tok = processor.tokenizer | |
| ids = {} | |
| for label in ("yes", "no"): | |
| for variant in (label, " " + label, label.capitalize(), " " + label.capitalize()): | |
| encoded = tok.encode(variant, add_special_tokens=False) | |
| if encoded: | |
| ids.setdefault(label, encoded[0]) | |
| break | |
| if "yes" not in ids or "no" not in ids: | |
| raise RuntimeError("无法定位 yes/no 的首 token") | |
| return ids | |
| def run_one(processor, model, ids, image_path, prompt): | |
| image = Image.open(image_path).convert("RGB") | |
| if getattr(processor, "_family", "") == "phi3v": | |
| text = f"<|user|>\n<|image_1|>\n{prompt}<|end|>\n<|assistant|>\n" | |
| inputs = processor(text=text, images=[image], return_tensors="pt").to("cuda:0") | |
| elif getattr(processor, "chat_template", None): | |
| messages = [ | |
| { | |
| "role": "user", | |
| "content": [{"type": "image"}, {"type": "text", "text": prompt}], | |
| } | |
| ] | |
| text = processor.apply_chat_template(messages, add_generation_prompt=True) | |
| inputs = processor(text=[text], images=[image], return_tensors="pt").to("cuda:0") | |
| else: | |
| inputs = processor(images=[image], text=[prompt], return_tensors="pt").to("cuda:0") | |
| model_dtype = next(model.parameters()).dtype | |
| for key, value in list(inputs.items()): | |
| if torch.is_floating_point(value) and value.dtype != model_dtype: | |
| inputs[key] = value.to(model_dtype) | |
| with torch.inference_mode(): | |
| out = model(**inputs) | |
| logits = out.logits[0, -1, :].float() | |
| logprobs = torch.log_softmax(logits, dim=-1) | |
| lp_yes = float(logprobs[ids["yes"]].item()) | |
| lp_no = float(logprobs[ids["no"]].item()) | |
| answer = "yes" if lp_yes >= lp_no else "no" | |
| generated = model.generate(**inputs, max_new_tokens=4, do_sample=False) | |
| new_tokens = generated[0, inputs["input_ids"].shape[1] :] | |
| raw = processor.tokenizer.decode(new_tokens, skip_special_tokens=True) | |
| return { | |
| "answer": answer, | |
| "lp_yes": lp_yes, | |
| "lp_no": lp_no, | |
| "raw_output": raw, | |
| "log_odds": lp_yes - lp_no, | |
| "prompt_tokens": int(inputs["input_ids"].shape[1]), | |
| "reached_cap": bool(new_tokens.shape[0] >= 4), | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--prompts", required=True) | |
| parser.add_argument("--images", required=True) | |
| parser.add_argument("--model-key", required=True, choices=sorted(MODEL_REGISTRY)) | |
| parser.add_argument("--out", required=True) | |
| parser.add_argument("--shard", type=int, default=0) | |
| parser.add_argument("--shards", type=int, default=1) | |
| parser.add_argument("--limit", type=int, default=0) | |
| args = parser.parse_args() | |
| rows = [json.loads(line) for line in Path(args.prompts).open(encoding="utf-8")] | |
| rows = [r for i, r in enumerate(rows) if i % args.shards == args.shard] | |
| if args.limit: | |
| rows = rows[: args.limit] | |
| out = Path(args.out) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| processor, model = load(args.model_key) | |
| ids = yes_no_ids(processor) | |
| images = Path(args.images) | |
| written = 0 | |
| started = time.time() | |
| with out.open("w", encoding="utf-8") as fh: | |
| for row in rows: | |
| result = run_one(processor, model, ids, images / row["image"], row["prompt"]) | |
| record = { | |
| **row, | |
| "model": args.model_key, | |
| **result, | |
| "prompt_sha256": hashlib.sha256(row["prompt"].encode("utf-8")).hexdigest(), | |
| } | |
| fh.write(json.dumps(record, ensure_ascii=False) + "\n") | |
| fh.flush() | |
| written += 1 | |
| if written % 20 == 0: | |
| rate = written / max(1e-6, time.time() - started) | |
| print(f"PROGRESS {written}/{len(rows)} {rate:.2f}/s", flush=True) | |
| print(f"WROTE {out} rows={written}") | |
| if __name__ == "__main__": | |
| main() | |