dsv4-flash-0731-vision / source /repository /scripts /bind_vision_eval_run.py
sigilwen's picture
Back up private DSV4-VL source at 38faa0fcaff0
1d7c7c4 verified
Raw History Blame Contribute Delete
8.58 kB
#!/usr/bin/env python3
"""Bind resumable vision results to one exact model and input set."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
from typing import Any
MODEL_FILES = ("config.json", "model.safetensors.index.json", "modeling_dsv4_vl.py")
PROJECTOR_VIEW_MANIFEST = "projector_eval_view.json"
VLLM_VIEW_MANIFEST = "vllm_eval_view.json"
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 model_files(model: Path) -> list[Path]:
paths = [model / name for name in MODEL_FILES]
view = model / PROJECTOR_VIEW_MANIFEST
if view.is_file():
payload = json.loads(view.read_text())
if payload.get("format") != "dsv4vl-projector-eval-view-v1":
raise ValueError("invalid projector evaluation view manifest")
shard_name = str(payload.get("rewritten_shard", ""))
if not shard_name or Path(shard_name).name != shard_name:
raise ValueError("projector evaluation view has an unsafe shard name")
paths.extend((view, model / shard_name))
vllm_view = model / VLLM_VIEW_MANIFEST
if vllm_view.is_file():
payload = json.loads(vllm_view.read_text())
if (
payload.get("format") != "dsv4vl-vllm-eval-view-v1"
or payload.get("status") != "PASS"
):
raise ValueError("invalid vLLM evaluation view manifest")
expected = payload.get("view_model_files")
if not isinstance(expected, dict) or not expected:
raise ValueError("vLLM evaluation view has no model-file receipts")
for name, digest in expected.items():
if Path(name).name != name or not isinstance(digest, str):
raise ValueError("vLLM evaluation view has an unsafe model-file receipt")
path = model / name
if not path.is_file() or sha256(path) != digest:
raise ValueError(f"vLLM evaluation view file differs: {path}")
paths.append(path)
paths.append(vllm_view)
# A projector view nested inside a vLLM view can reference the same shard
# as the vLLM receipt. Keep the binding canonical and duplicate-free.
return list(dict.fromkeys(paths))
def validate_export_shard_receipts(payload: dict[str, Any], model: Path) -> None:
index = json.loads((model / "model.safetensors.index.json").read_text())
expected = set(index.get("weight_map", {}).values())
if not expected:
raise ValueError("export index contains no model shards")
receipts = payload.get("shards")
if (
not isinstance(receipts, list)
or len(receipts) != int(payload.get("shard_count", -1))
or {item.get("name") for item in receipts if isinstance(item, dict)} != expected
):
raise ValueError("model verification lacks the exact export shard set")
total = 0
for item in receipts:
if set(item) != {"name", "bytes", "sha256"}:
raise ValueError("model verification has an invalid shard receipt")
name = item["name"]
if Path(name).name != name or not isinstance(item["sha256"], str) or len(item["sha256"]) != 64:
raise ValueError("model verification has an unsafe shard receipt")
path = model / name
if not path.is_file() or path.stat().st_size != int(item["bytes"]):
raise ValueError(f"verified export shard is missing or resized: {path}")
total += int(item["bytes"])
if total != int(payload.get("shard_bytes", -1)):
raise ValueError("model verification shard byte total differs")
def accepted_verification_models(model: Path) -> set[Path]:
"""Return model roots an export receipt may legitimately identify.
A vLLM evaluation view is a deterministic zero-copy view whose manifest
binds its source export. The export verifier naturally names that source,
not the derived view directory. Ordinary model directories remain strict
and accept only themselves.
"""
accepted = {model.resolve()}
view = model / VLLM_VIEW_MANIFEST
if not view.is_file():
return accepted
payload = json.loads(view.read_text())
if (
payload.get("format") != "dsv4vl-vllm-eval-view-v1"
or payload.get("status") != "PASS"
):
raise ValueError("invalid vLLM evaluation view manifest")
source_value = payload.get("source")
if not isinstance(source_value, str) or not source_value:
raise ValueError("vLLM evaluation view does not bind its source export")
source = Path(source_value).resolve()
if not source.is_dir():
raise ValueError("vLLM evaluation view source export is missing")
source_files = payload.get("source_model_files")
if not isinstance(source_files, dict) or not source_files:
raise ValueError("vLLM evaluation view has no source-model receipts")
for name, digest in source_files.items():
if (
not isinstance(name, str)
or Path(name).name != name
or not isinstance(digest, str)
or len(digest) != 64
):
raise ValueError("vLLM evaluation view has an unsafe source receipt")
path = source / name
if not path.is_file() or sha256(path) != digest:
raise ValueError(f"vLLM evaluation source file differs: {path}")
accepted.add(source)
return accepted
def fingerprint(
model: Path, inputs: list[Path], model_verification: Path | None = None
) -> dict[str, Any]:
model = model.resolve()
required = model_files(model)
for path in required + inputs:
if not path.is_file():
raise FileNotFoundError(path)
result = {
"format": "dsv4vl-vision-eval-run-v1",
"model": str(model),
"model_files": {
path.name: sha256(path) for path in required
},
"inputs": [
{"path": str(path.resolve()), "sha256": sha256(path)} for path in inputs
],
}
if model_verification is not None:
model_verification = model_verification.resolve()
payload = json.loads(model_verification.read_text())
if (
payload.get("format") != "dsv4vl-export-verification-v1"
or payload.get("status") != "PASS"
or Path(str(payload.get("model", ""))).resolve()
not in accepted_verification_models(model)
):
raise ValueError("model verification does not accept the selected model")
validate_export_shard_receipts(payload, model)
result["model_verification"] = {
"path": str(model_verification),
"sha256": sha256(model_verification),
}
return result
def bind(
model: Path,
inputs: list[Path],
results: Path,
manifest: Path,
model_verification: Path | None = None,
) -> dict[str, Any]:
expected = fingerprint(model, inputs, model_verification)
if manifest.exists():
actual = json.loads(manifest.read_text())
if actual != expected:
raise ValueError(
"vision evaluation run manifest differs from the selected model/inputs"
)
return {"status": "PASS", "reused": True, **expected}
if results.exists() and results.stat().st_size:
raise FileExistsError(
f"refusing unbound pre-existing vision results without {manifest}: {results}"
)
manifest.parent.mkdir(parents=True, exist_ok=True)
temporary = manifest.with_suffix(manifest.suffix + f".tmp-{os.getpid()}")
temporary.write_text(json.dumps(expected, indent=2) + "\n")
os.replace(temporary, manifest)
return {"status": "PASS", "reused": False, **expected}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=Path, required=True)
parser.add_argument("--inputs", nargs="+", type=Path, required=True)
parser.add_argument("--results", type=Path, required=True)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--model-verification", type=Path)
args = parser.parse_args()
print(
json.dumps(
bind(
args.model,
args.inputs,
args.results,
args.manifest,
args.model_verification,
),
indent=2,
)
)
if __name__ == "__main__":
main()