File size: 6,754 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
#!/usr/bin/env python3
"""Create a zero-copy DeepSeek-V4 text-only view of the merged VLM export.

The merged checkpoint keeps DeepSeek's native text tensor names alongside
`vision_tower.*` and `multi_modal_projector.*`. A filtered index plus a plain
DeepSeek-V4 config lets text-only serving/evaluation use the adapted language
weights without copying another 500+ GB or teaching the server about the VLM
wrapper. Weight shards are hard-linked (symlink fallback).
"""

from __future__ import annotations

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


VISUAL_PREFIXES = ("vision_tower.", "multi_modal_projector.")


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 link(source: Path, target: Path) -> str:
    try:
        os.link(source, target)
        return "hardlink"
    except OSError:
        os.symlink(source, target)
        return "symlink"


def text_config(wrapper_config: dict[str, Any]) -> dict[str, Any]:
    if wrapper_config.get("model_type") != "dsv4_vl":
        raise ValueError(f"expected dsv4_vl wrapper, got {wrapper_config.get('model_type')}")
    config = dict(wrapper_config["text_config"])
    if config.get("model_type") != "deepseek_v4":
        raise ValueError(f"nested config is not DeepSeek V4: {config.get('model_type')}")
    config["architectures"] = ["DeepseekV4ForCausalLM"]
    config["expert_dtype"] = "bfloat16"
    config["torch_dtype"] = "bfloat16"
    config.pop("quantization_config", None)
    config["num_nextn_predict_layers"] = 0
    for key in list(config):
        if key.startswith("dspark_"):
            config.pop(key)
    return config


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--model", required=True, type=Path, help="merged DSV4-VL BF16 export")
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--model-verification", type=Path)
    parser.add_argument("--expected-text-weights", type=int)
    parser.add_argument("--min-text-weights", type=int, default=34_000)
    parser.add_argument("--min-visual-weights", type=int, default=400)
    parser.add_argument("--min-shard-bytes", type=int, default=500_000_000_000)
    args = parser.parse_args()
    model, output = args.model.resolve(), args.output.resolve()
    if output.exists() or output.is_symlink():
        raise FileExistsError(f"refusing to replace existing output: {output}")

    wrapper_config = json.loads((model / "config.json").read_text())
    config = text_config(wrapper_config)
    source_index = json.loads((model / "model.safetensors.index.json").read_text())
    source_map = source_index["weight_map"]
    if args.model_verification is not None:
        verification = json.loads(args.model_verification.read_text())
        if (
            verification.get("format") != "dsv4vl-export-verification-v1"
            or verification.get("status") != "PASS"
            or Path(str(verification.get("model", ""))).resolve() != model
            or int(verification.get("weight_count", -1)) != len(source_map)
        ):
            raise ValueError("text view model differs from its export verification")
    weight_map = {
        name: shard
        for name, shard in source_map.items()
        if not name.startswith(VISUAL_PREFIXES)
    }
    if len(weight_map) < args.min_text_weights:
        raise AssertionError(f"implausibly few text tensors: {len(weight_map)}")
    visual_weight_count = len(source_map) - len(weight_map)
    if visual_weight_count < args.min_visual_weights:
        raise AssertionError(f"implausibly few visual tensors: {visual_weight_count}")
    if (
        args.expected_text_weights is not None
        and len(weight_map) != args.expected_text_weights
    ):
        raise AssertionError(
            "text tensor count differs from the sealed topology: "
            f"{len(weight_map)} != {args.expected_text_weights}"
        )
    if any(name.startswith(VISUAL_PREFIXES) for name in weight_map):
        raise AssertionError("visual tensor escaped filtered index")
    if any(".lora_A." in name or ".lora_B." in name for name in weight_map):
        raise AssertionError("text view contains unmerged LoRA tensors")
    roots = {name.split(".", 1)[0] for name in weight_map}
    required_roots = {"embed", "layers", "norm", "head"}
    if not required_roots.issubset(roots):
        raise AssertionError(f"text tensor roots differ: missing={sorted(required_roots - roots)}")

    shard_names = sorted(set(weight_map.values()))
    missing = [name for name in shard_names if not (model / name).is_file()]
    if missing:
        raise FileNotFoundError(f"merged export is missing shards: {missing[:10]}")
    shard_bytes = sum((model / name).stat().st_size for name in shard_names)
    if shard_bytes < args.min_shard_bytes:
        raise AssertionError(f"text shard set is implausibly small: {shard_bytes}")

    output.mkdir(parents=True)
    link_modes = set()
    for shard_name in shard_names:
        link_modes.add(link(model / shard_name, output / shard_name))
    for pattern in ("tokenizer*", "generation_config.json"):
        for source in model.glob(pattern):
            if source.is_file():
                shutil.copy2(source, output / source.name)
    if (model / "encoding").is_dir():
        shutil.copytree(model / "encoding", output / "encoding")

    (output / "config.json").write_text(json.dumps(config, indent=2) + "\n")
    index = {
        "metadata": {
            "format": "dsv4-text-view-v1",
            "source": str(model),
            "text_weight_count": len(weight_map),
        },
        "weight_map": weight_map,
    }
    (output / "model.safetensors.index.json").write_text(json.dumps(index, indent=2) + "\n")
    tokenizer_path = output / "tokenizer.json"
    manifest = {
        "format": "dsv4-text-view-v1",
        "source": str(model),
        "output": str(output),
        "weight_count": len(weight_map),
        "visual_weight_count": visual_weight_count,
        "shard_count": len(shard_names),
        "shard_bytes": shard_bytes,
        "link_modes": sorted(link_modes),
        "tokenizer_sha256": sha256(tokenizer_path),
        "model_verification_sha256": (
            sha256(args.model_verification)
            if args.model_verification is not None
            else None
        ),
    }
    (output / "text_view_manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
    print(json.dumps({"status": "PASS", **manifest}, indent=2))


if __name__ == "__main__":
    main()