File size: 8,579 Bytes
1d7c7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/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()