Datasets:
File size: 8,180 Bytes
65b8e03 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | #!/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()))
|