File size: 7,895 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
#!/usr/bin/env python3
"""Create a zero-copy HF evaluation view with a trained projector overlay.

The 48 immutable 0731 language shards are hardlinked. Only the ~900 MB shard
containing frozen SigLIP2 plus the four projector tensors is rewritten.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import shutil
from pathlib import Path

import torch
from safetensors import safe_open
from safetensors.torch import load_file, save_file


CHECKPOINT_TO_HF = {
    "chunk0.visual.multi_modal_projector.linear_1.weight": "multi_modal_projector.linear_1.weight",
    "chunk0.visual.multi_modal_projector.linear_1.bias": "multi_modal_projector.linear_1.bias",
    "chunk0.visual.multi_modal_projector.linear_2.weight": "multi_modal_projector.linear_2.weight",
    "chunk0.visual.multi_modal_projector.linear_2.bias": "multi_modal_projector.linear_2.bias",
}
VISION_SHARD = "vision-projector.safetensors"


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 load_projector(projector_path: Path) -> dict[str, torch.Tensor]:
    projector = load_file(str(projector_path), device="cpu")
    if set(projector) != set(CHECKPOINT_TO_HF):
        raise ValueError(
            f"projector key mismatch: expected={sorted(CHECKPOINT_TO_HF)}, "
            f"actual={sorted(projector)}"
        )
    for key, tensor in projector.items():
        if tensor.dtype != torch.bfloat16 or not bool(torch.isfinite(tensor).all()):
            raise ValueError(f"invalid trained projector tensor: {key}")
    return projector


def link_tree(source: Path, target: Path, excluded: set[str]) -> None:
    target.mkdir(parents=True)
    for child in source.iterdir():
        if child.name in excluded:
            continue
        destination = target / child.name
        if child.is_dir():
            shutil.copytree(child, destination, copy_function=os.link, symlinks=True)
        elif child.is_symlink():
            destination.symlink_to(os.readlink(child))
        else:
            os.link(child, destination)


def create_view(source: Path, projector_path: Path, output: Path) -> dict:
    source = source.resolve()
    projector_path = projector_path.resolve()
    output = output.resolve()
    if output.exists():
        raise FileExistsError(f"refusing to replace existing view: {output}")
    if not (source / VISION_SHARD).is_file():
        raise FileNotFoundError(source / VISION_SHARD)
    temporary = output.with_name(output.name + f".tmp-{os.getpid()}")
    if temporary.exists():
        raise FileExistsError(temporary)

    projector = load_projector(projector_path)
    try:
        link_tree(source, temporary, {VISION_SHARD})
        visual = load_file(str(source / VISION_SHARD), device="cpu")
        for checkpoint_key, hf_key in CHECKPOINT_TO_HF.items():
            expected = visual.get(hf_key)
            actual = projector[checkpoint_key]
            if expected is None or tuple(expected.shape) != tuple(actual.shape):
                raise ValueError(
                    f"projector shape mismatch for {hf_key}: "
                    f"source={None if expected is None else tuple(expected.shape)}, "
                    f"checkpoint={tuple(actual.shape)}"
                )
            visual[hf_key] = actual
        with safe_open(source / VISION_SHARD, framework="pt", device="cpu") as reader:
            metadata = reader.metadata() or {"format": "pt"}
        save_file(visual, temporary / VISION_SHARD, metadata=metadata)

        index = json.loads((temporary / "model.safetensors.index.json").read_text())
        for hf_key in CHECKPOINT_TO_HF.values():
            if index["weight_map"].get(hf_key) != VISION_SHARD:
                raise ValueError(f"index does not map {hf_key} to {VISION_SHARD}")
        language_shards = sorted(
            name for name in set(index["weight_map"].values()) if name != VISION_SHARD
        )
        for shard in language_shards:
            if os.stat(source / shard).st_ino != os.stat(temporary / shard).st_ino:
                raise AssertionError(f"language shard was copied instead of hardlinked: {shard}")
        manifest = {
            "format": "dsv4vl-projector-eval-view-v1",
            "source": str(source),
            "projector": str(projector_path),
            "projector_sha256": sha256(projector_path),
            "rewritten_shard": VISION_SHARD,
            "rewritten_shard_sha256": sha256(temporary / VISION_SHARD),
            "model_index_sha256": sha256(temporary / "model.safetensors.index.json"),
            "hardlinked_language_shards": len(language_shards),
            "projector_tensors": list(CHECKPOINT_TO_HF.values()),
        }
        (temporary / "projector_eval_view.json").write_text(json.dumps(manifest, indent=2) + "\n")
        os.replace(temporary, output)
        return manifest
    except BaseException:
        if temporary.exists():
            shutil.rmtree(temporary)
        raise


def verify_view(source: Path, projector_path: Path, output: Path) -> dict:
    source = source.resolve()
    projector_path = projector_path.resolve()
    output = output.resolve()
    manifest_path = output / "projector_eval_view.json"
    manifest = json.loads(manifest_path.read_text())
    if (
        manifest.get("format") != "dsv4vl-projector-eval-view-v1"
        or Path(str(manifest.get("source", ""))).resolve() != source
        or Path(str(manifest.get("projector", ""))).resolve() != projector_path
        or manifest.get("rewritten_shard") != VISION_SHARD
        or manifest.get("projector_tensors") != list(CHECKPOINT_TO_HF.values())
    ):
        raise ValueError("projector evaluation view provenance differs")
    projector = load_projector(projector_path)
    shard = output / VISION_SHARD
    index = output / "model.safetensors.index.json"
    if manifest.get("projector_sha256") != sha256(projector_path):
        raise ValueError("projector changed after evaluation-view creation")
    if manifest.get("rewritten_shard_sha256") != sha256(shard):
        raise ValueError("rewritten vision shard changed after evaluation-view creation")
    if manifest.get("model_index_sha256") != sha256(index):
        raise ValueError("evaluation-view model index changed")

    with safe_open(shard, framework="pt", device="cpu") as reader:
        for checkpoint_key, hf_key in CHECKPOINT_TO_HF.items():
            if not torch.equal(projector[checkpoint_key], reader.get_tensor(hf_key)):
                raise ValueError(f"evaluation-view projector tensor differs: {hf_key}")
    weight_map = json.loads(index.read_text())["weight_map"]
    language_shards = sorted(
        name for name in set(weight_map.values()) if name != VISION_SHARD
    )
    if len(language_shards) != int(manifest.get("hardlinked_language_shards", -1)):
        raise ValueError("evaluation-view language-shard count changed")
    for name in language_shards:
        if os.stat(source / name).st_ino != os.stat(output / name).st_ino:
            raise ValueError(f"evaluation-view language shard is not hardlinked: {name}")
    return {"status": "PASS", **manifest}


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--model", type=Path, required=True)
    parser.add_argument("--projector", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--verify-existing", action="store_true")
    args = parser.parse_args()
    if args.verify_existing:
        report = verify_view(args.model, args.projector, args.output)
    else:
        report = create_view(args.model, args.projector, args.output)
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()