Datasets:
Download code/run_mathvision_vllm.py from Miiche/vpp-mathvision-seed-variance: direct link, hf CLI and curl.
- Browser
- Download file 8.18 kB
-
https://huggingface.co/datasets/Miiche/vpp-mathvision-seed-variance/resolve/main/code/run_mathvision_vllm.py
- Command line
-
hf download hf://datasets/Miiche/vpp-mathvision-seed-variance/code/run_mathvision_vllm.py
-
curl -L -o run_mathvision_vllm.py https://huggingface.co/datasets/Miiche/vpp-mathvision-seed-variance/resolve/main/code/run_mathvision_vllm.py
8.18 kB
| #!/usr/bin/env python3 | |
| """One seed of the MathVision seed-variance study against a vLLM server. | |
| Thinking mode with the model card's sampling. Per request the outputs keep: | |
| the exact messages, request parameters, reasoning and answer text, the | |
| engine's prompt token ids and generated token ids (for teacher-forced | |
| attention replay), usage, latency, finish reason, and the score. Per-token | |
| log-probabilities (chosen token + top-5) go to token_logprobs.jsonl.gz. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import gzip | |
| import json | |
| import os | |
| import time | |
| from collections import Counter | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from openai import AsyncOpenAI | |
| from video_position_probing import mathvision as mv | |
| from video_position_probing.jsonl import read_jsonl | |
| # Qwen3.5-4B / -9B model cards, thinking mode for general tasks. | |
| SAMPLING = {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0, | |
| "presence_penalty": 1.5, "repetition_penalty": 1.0} | |
| async def main_async(args: argparse.Namespace) -> None: | |
| items = read_jsonl(args.data_dir / "items.jsonl") | |
| if args.limit: | |
| items = items[: args.limit] | |
| out = args.output_dir | |
| out.mkdir(parents=True, exist_ok=True) | |
| raw_path, lp_path = out / "outputs.jsonl", out / "token_logprobs.jsonl.gz" | |
| done = ({r["item_id"] for r in read_jsonl(raw_path, repair_trailing=True) if r.get("status") == "ok"} | |
| if raw_path.exists() else set()) | |
| manifest = { | |
| "created_at": datetime.now(timezone.utc).isoformat(), "model_name": args.model_name, | |
| "model_path": args.model_path, "seed": args.seed, "thinking": True, "sampling": SAMPLING, | |
| "max_tokens": args.max_tokens, "top_logprobs": args.top_logprobs, "system_prompt": mv.SYSTEM_PROMPT, | |
| "dataset": mv.HF_DATASET, "dataset_revision": mv.HF_REVISION, "items": len(items), "resumed": len(done), | |
| "server_args": os.environ.get("VPP_SERVER_ARGS"), | |
| "git": {"commit": os.environ.get("VPP_GIT_COMMIT"), "dirty": os.environ.get("VPP_GIT_DIRTY") == "1"}, | |
| "skypilot": {k: os.environ.get(k) for k in ("SKYPILOT_TASK_ID", "VPP_JOB_NAME", "VPP_ATTEMPT")}, | |
| } | |
| with (out / "run_manifests.jsonl").open("a") as handle: | |
| handle.write(json.dumps(manifest) + "\n") | |
| client = AsyncOpenAI(api_key="EMPTY", base_url=args.api_base, timeout=args.timeout) | |
| semaphore, lock = asyncio.Semaphore(args.concurrency), asyncio.Lock() | |
| sampling = dict(SAMPLING) | |
| extra = {k: sampling.pop(k) for k in ("top_k", "min_p", "repetition_penalty")} | |
| async def run(item: dict) -> None: | |
| if item["item_id"] in done: | |
| return | |
| image = (args.data_dir / item["image"]).resolve() | |
| messages = [ | |
| {"role": "system", "content": mv.SYSTEM_PROMPT}, | |
| {"role": "user", "content": [ | |
| {"type": "image_url", "image_url": {"url": f"file://{image}"}}, | |
| {"type": "text", "text": mv.user_text(item)}, | |
| ]}, | |
| ] | |
| request = {"model": args.model_path, "max_tokens": args.max_tokens, "seed": args.seed, **sampling, | |
| "logprobs": True, "top_logprobs": args.top_logprobs, | |
| "extra_body": {**extra, "chat_template_kwargs": {"enable_thinking": True}, | |
| "return_token_ids": True}} | |
| record = {"item_id": item["item_id"], "id": item["id"], "level": item["level"], "subject": item["subject"], | |
| "gold": item["answer"], "options": item["options"], "image": item["image"], | |
| "image_sha256": item["image_sha256"], "seed": args.seed, "messages": messages, | |
| "request_parameters": request} | |
| async with semaphore: | |
| started = time.perf_counter() | |
| record["started_at"] = datetime.now(timezone.utc).isoformat() | |
| try: | |
| response = await client.chat.completions.create(messages=messages, **request) | |
| choice = response.choices[0] | |
| message = choice.message | |
| answer = message.content or "" | |
| reasoning = getattr(message, "reasoning_content", None) or getattr(message, "reasoning", None) or "" | |
| prediction = mv.extract_answer(answer) or mv.extract_answer(reasoning[-2000:]) | |
| lps = choice.logprobs.content if choice.logprobs and choice.logprobs.content else [] | |
| record.update({ | |
| "status": "ok", "latency_seconds": time.perf_counter() - started, | |
| "reasoning": reasoning, "answer": answer, "prediction": prediction, | |
| "prediction_from": "answer" if mv.extract_answer(answer) else ("reasoning" if prediction else None), | |
| "correct": mv.is_correct(prediction, item["answer"], item["options"]), | |
| "finish_reason": choice.finish_reason, | |
| "usage": response.usage.model_dump(mode="json") if response.usage else None, | |
| "prompt_token_ids": response.prompt_token_ids, | |
| "output_token_ids": getattr(choice, "token_ids", None), | |
| "n_logprob_positions": len(lps), | |
| }) | |
| lp_record = {"item_id": item["item_id"], "seed": args.seed, | |
| "tokens": [p.token for p in lps], "logprobs": [p.logprob for p in lps], | |
| "top": [[[t.token, t.logprob] for t in p.top_logprobs] for p in lps]} | |
| except Exception as exc: # recorded; retried on resume | |
| record.update({"status": "error", "error_type": type(exc).__name__, "error": str(exc), | |
| "latency_seconds": time.perf_counter() - started}) | |
| lp_record = None | |
| async with lock: | |
| with raw_path.open("a", encoding="utf-8") as handle: | |
| handle.write(json.dumps(record, ensure_ascii=False) + "\n") | |
| if lp_record: | |
| with gzip.open(lp_path, "at", encoding="utf-8") as handle: | |
| handle.write(json.dumps(lp_record, ensure_ascii=False) + "\n") | |
| print(json.dumps({k: record.get(k) for k in ("item_id", "status", "prediction", "correct", | |
| "finish_reason", "latency_seconds")}), flush=True) | |
| started = time.perf_counter() | |
| await asyncio.gather(*(run(item) for item in items)) | |
| latest = {r["item_id"]: r for r in read_jsonl(raw_path)} | |
| ok = [latest[i["item_id"]] for i in items if latest.get(i["item_id"], {}).get("status") == "ok"] | |
| summary = { | |
| "model": args.model_name, "seed": args.seed, "items": len(items), "successful": len(ok), | |
| "errors": len(items) - len(ok), "accuracy": sum(r["correct"] for r in ok) / len(items), | |
| "no_answer": sum(r["prediction"] is None for r in ok), | |
| "finish_reasons": dict(Counter(r["finish_reason"] for r in ok)), | |
| "mean_completion_tokens": sum((r["usage"] or {}).get("completion_tokens", 0) for r in ok) / max(1, len(ok)), | |
| "wall_seconds": time.perf_counter() - started, | |
| } | |
| (out / "summary.json").write_text(json.dumps(summary, indent=2) + "\n") | |
| print(json.dumps(summary, indent=2)) | |
| if summary["errors"]: | |
| raise RuntimeError(f"{summary['errors']} requests failed") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--api-base", default="http://127.0.0.1:8000/v1") | |
| parser.add_argument("--model-name", required=True) | |
| parser.add_argument("--model-path", required=True) | |
| parser.add_argument("--data-dir", type=Path, required=True) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument("--seed", type=int, required=True) | |
| parser.add_argument("--max-tokens", type=int, default=38912) | |
| parser.add_argument("--top-logprobs", type=int, default=5) | |
| parser.add_argument("--concurrency", type=int, default=64) | |
| parser.add_argument("--timeout", type=float, default=7200) | |
| parser.add_argument("--limit", type=int, default=0) | |
| return parser.parse_args() | |
| if __name__ == "__main__": | |
| asyncio.run(main_async(parse_args())) | |