#!/usr/bin/env python3 """Require the final DSV4-VL export to clearly beat Stage-1 vision scores.""" from __future__ import annotations import argparse import hashlib import json import os from pathlib import Path from typing import Any FORMAT = "dsv4vl-vision-regression-v1" EXPECTED_ROWS = {"mmbench_en_dev": 4329, "textvqa_val": 5000, "mme": 2374} def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def check_report( report: dict[str, Any], label: str ) -> tuple[dict[str, Any], dict[str, Any]]: if report.get("format") != "dsv4vl-vision-eval-v1" or report.get("status") != "PASS": raise ValueError(f"{label} vision report has unexpected format/status") results = report.get("results", {}) actual = {suite: int(results.get(suite, {}).get("rows", -1)) for suite in EXPECTED_ROWS} if actual != EXPECTED_ROWS: raise ValueError(f"{label} vision report row counts differ: {actual}") if int(results["mme"].get("incomplete_pairs", -1)) != 0: raise ValueError(f"{label} MME report has incomplete pairs") inputs = report.get("evaluation_inputs") manifest = report.get("eval_manifest", {}).get("sha256") if ( not isinstance(inputs, list) or len(inputs) != 3 or any(set(item) != {"path", "sha256"} for item in inputs) or not manifest ): raise ValueError(f"{label} vision report lacks bound evaluation provenance") return results, {"evaluation_inputs": inputs, "eval_manifest_sha256": manifest} def metric(name: str, before: float, after: float, required_gain: float) -> dict[str, Any]: gain = after - before return { "name": name, "stage1": before, "final": after, "gain": gain, "required_gain": required_gain, "pass": gain >= required_gain - 1e-12, } def compare(stage1: dict[str, Any], final: dict[str, Any]) -> dict[str, Any]: before, before_provenance = check_report(stage1, "Stage-1") after, after_provenance = check_report(final, "final") if before_provenance != after_provenance: raise ValueError("Stage-1/final vision reports use different holdouts") checks = [ metric( "mmbench_static_accuracy", float(before["mmbench_en_dev"]["static_accuracy"]), float(after["mmbench_en_dev"]["static_accuracy"]), 0.01, ), metric( "textvqa_exact_match", float(before["textvqa_val"]["exact_match"]), float(after["textvqa_val"]["exact_match"]), 0.01, ), metric( "mme_total_score", float(before["mme"]["total_score"]), float(after["mme"]["total_score"]), 10.0, ), ] return { "format": FORMAT, "status": "PASS" if all(item["pass"] for item in checks) else "FAIL", "policy": "final must gain >=1 point on MMBench/TextVQA and >=10 MME points", "checks": checks, } def markdown(report: dict[str, Any]) -> str: lines = [ "# DSV4-VL final vision improvement", "", f"Status: **{report['status']}**", "", "| Metric | Stage 1 | Final | Gain | Required | Pass |", "|---|---:|---:|---:|---:|:---:|", ] for item in report["checks"]: lines.append( f"| {item['name']} | {item['stage1']:.6f} | {item['final']:.6f} | " f"{item['gain']:+.6f} | {item['required_gain']:.6f} | " f"{'yes' if item['pass'] else 'no'} |" ) return "\n".join(lines) + "\n" def atomic_write(path: Path, content: str) -> None: if path.exists(): raise FileExistsError(f"refusing to replace vision comparison artifact: {path}") path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + f".tmp-{os.getpid()}") temporary.write_text(content) os.replace(temporary, path) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--stage1", type=Path, required=True) parser.add_argument("--final", type=Path, required=True) parser.add_argument("--output-json", type=Path, required=True) parser.add_argument("--output-md", type=Path, required=True) args = parser.parse_args() if args.output_json.exists() or args.output_md.exists(): raise FileExistsError("refusing to replace existing vision comparison outputs") report = compare(json.loads(args.stage1.read_text()), json.loads(args.final.read_text())) report["reports"] = { "stage1": {"path": str(args.stage1.resolve()), "sha256": sha256(args.stage1)}, "final": {"path": str(args.final.resolve()), "sha256": sha256(args.final)}, } atomic_write(args.output_json, json.dumps(report, indent=2) + "\n") atomic_write(args.output_md, markdown(report)) print(json.dumps(report, indent=2)) if report["status"] != "PASS": raise SystemExit(2) if __name__ == "__main__": main()