File size: 12,936 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#!/usr/bin/env python3
"""Create a zero-copy vLLM-specific view of a bound DSV4-VL checkpoint."""

from __future__ import annotations

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


MODEL_ARCHITECTURE = "DSV4VLVllmForConditionalGeneration"
IMAGE_TOKEN = "<|image|>"
GENERATED_CONFIG_FIELDS = (
    "image_token_index",
    "vision_feature_select_strategy",
    "vision_feature_layer",
    "multimodal_projector_bias",
    "quantization_config",
    "expert_dtype",
    "num_nextn_predict_layers",
    "dsv4_compress_ratios",
    "dsv4_num_hash_layers",
    "dsv4_index_topk",
    "dsv4_sliding_window",
    "dsv4_rope_parameters",
    "rope_parameters",
    "max_position_embeddings",
)


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 write_atomic(path: Path, payload: dict) -> None:
    temporary = path.with_suffix(path.suffix + f".tmp-{os.getpid()}")
    temporary.write_text(json.dumps(payload, indent=2) + "\n")
    os.replace(temporary, path)


def linked_source_files(source: Path) -> dict[str, Path]:
    excluded = {
        "config.json",
        "preprocessor_config.json",
        "processor_config.json",
        "vllm_eval_view.json",
    }
    return {
        path.name: path
        for path in source.iterdir()
        if path.is_file() and path.name not in excluded
    }


def remove_proven_incomplete_view(source: Path, output: Path) -> int:
    """Remove only a receipt-less partial view whose files alias the source."""
    if not output.is_dir() or (output / "vllm_eval_view.json").exists():
        raise ValueError("refusing to replace a complete or non-directory vLLM view")
    expected = linked_source_files(source)
    expected_config, expected_preprocessor, expected_processor = expected_payloads(source)
    generated = {
        "config.json": expected_config,
        "preprocessor_config.json": expected_preprocessor,
        "processor_config.json": expected_processor,
    }
    existing = list(output.iterdir())
    for path in existing:
        source_path = expected.get(path.name)
        linked = (
            source_path is not None
            and path.is_file()
            and os.path.samefile(source_path, path)
        )
        generated_exact = (
            path.name in generated
            and path.is_file()
            and json.loads(path.read_text()) == generated[path.name]
        )
        if not linked and not generated_exact:
            raise ValueError(f"partial vLLM view contains an unbound file: {path}")
    for path in existing:
        path.unlink()
    output.rmdir()
    return len(existing)


def link_source_file(source: Path, target: Path, prefer_symlink: bool) -> str:
    if prefer_symlink:
        os.symlink(source, target)
        return "symlink"
    os.link(source, target)
    return "hardlink"


def expected_payloads(source: Path) -> tuple[dict, dict, dict]:
    config = json.loads((source / "config.json").read_text())
    text_config = config["text_config"]
    vision_config = config["vision_config"]
    image_token_id = int(config["image_token_id"])
    # ``--refresh-config`` may target a view generated by an older script.
    # Rebuild every generated field so byte order is canonical rather than
    # inherited from the previous generator.
    for field in GENERATED_CONFIG_FIELDS:
        config.pop(field, None)
    if config.get("model_type") != "dsv4_vl":
        raise ValueError("source is not a DSV4-VL checkpoint")
    if text_config.get("model_type") != "deepseek_v4":
        raise ValueError("source does not contain DeepSeek-V4")
    if vision_config.get("model_type") != "siglip_vision_model":
        raise ValueError("source does not contain SigLIP vision")

    quantization_payload = text_config.get("quantization_config")
    quantization = None
    if quantization_payload is not None:
        quantization = dict(quantization_payload)
        # The composite top-level model_type is dsv4_vl, so vLLM cannot infer
        # its DeepSeek-specific FP4-expert dispatcher from model_type alone.
        quantization["quant_method"] = "deepseek_v4_fp8"
        skipped = set(quantization.get("modules_to_not_convert") or ())
        skipped.update(
            (
                "lm_head",
                "vision_tower",
                "multi_modal_projector",
            )
        )
        quantization["modules_to_not_convert"] = sorted(skipped)
    else:
        # Phase 6 deliberately exports ordinary BF16 tensors after merging the
        # LoRA. vLLM 0.25's native DeepSeek-V4 model routes a missing
        # QuantizationConfig to UnquantizedFusedMoEMethod, including under EP.
        # Fail closed for any other undeclared storage rather than guessing.
        expert_dtype = str(text_config.get("expert_dtype", "")).lower()
        if expert_dtype not in {"bf16", "bfloat16"}:
            raise ValueError(
                "unquantized vLLM views require BF16 expert storage; "
                f"got expert_dtype={expert_dtype!r}"
            )
        config.pop("quantization_config", None)
    rope_parameters = dict(text_config["rope_scaling"])
    # vLLM 0.25's native DeepSeek-V4 implementation consumes the legacy flat
    # 0731 rope block. Transformers 5.14 normalizes that block into a nested
    # {main, compress} mapping when it builds the composite text config, which
    # is incompatible with vLLM's rotary-cache key. Preserve the checkpoint
    # representation out of band and use vLLM's modern key spelling.
    rope_parameters.setdefault(
        "rope_type", rope_parameters.get("type", "default")
    )
    updates = {
        "architectures": [MODEL_ARCHITECTURE],
        "image_token_index": image_token_id,
        "vision_feature_select_strategy": "full",
        "vision_feature_layer": -1,
        "multimodal_projector_bias": True,
    }
    # Preserve the original FP8 view's deterministic JSON order. The Stage-1
    # baseline binds exact bytes, and adding the BF16 branch must not move an
    # existing field even when the parsed JSON would remain equivalent.
    if quantization is not None:
        updates["quantization_config"] = quantization
    updates.update(
        {
            "expert_dtype": text_config["expert_dtype"],
            "num_nextn_predict_layers": text_config["num_nextn_predict_layers"],
            # Transformers 5 normalizes these legacy 0731 fields out of the
            # nested DeepseekV4Config object, while vLLM 0.25 still consumes
            # their exact public-checkpoint representation.
            "dsv4_compress_ratios": list(text_config["compress_ratios"]),
            "dsv4_num_hash_layers": int(text_config["num_hash_layers"]),
            "dsv4_index_topk": int(text_config["index_topk"]),
            "dsv4_sliding_window": int(text_config["sliding_window"]),
            "dsv4_rope_parameters": rope_parameters,
            # vLLM validates the top-level AutoConfig before the out-of-tree
            # model wrapper is instantiated. Expose the same normalized flat
            # block there so vLLM 0.25 never sees Transformers' legacy
            # rope_scaling copy without its required rope_type key.
            "rope_parameters": rope_parameters,
            # Transformers validates the top-level composite config's
            # ``rope_parameters`` inside ``PretrainedConfig.__init__``.  The
            # validator reads this companion field before DSV4VLConfig has
            # constructed its nested text config, so mirror the authoritative
            # language value at the composite level as well.
            "max_position_embeddings": int(
                text_config["max_position_embeddings"]
            ),
        }
    )
    config.update(updates)

    preprocessor = json.loads((source / "preprocessor_config.json").read_text())
    preprocessor.update(
        {
            "processor_class": "LlavaProcessor",
            "patch_size": int(vision_config["patch_size"]),
            "vision_feature_select_strategy": "full",
            "image_token": IMAGE_TOKEN,
            "num_additional_image_tokens": 0,
        }
    )
    processor = {
        "processor_class": "LlavaProcessor",
        "patch_size": int(vision_config["patch_size"]),
        "vision_feature_select_strategy": "full",
        "image_token": IMAGE_TOKEN,
        "num_additional_image_tokens": 0,
    }
    return config, preprocessor, processor


def verify_view(source: Path, output: Path) -> dict:
    expected_config, expected_preprocessor, expected_processor = expected_payloads(
        source
    )
    for name, expected in (
        ("config.json", expected_config),
        ("preprocessor_config.json", expected_preprocessor),
        ("processor_config.json", expected_processor),
    ):
        path = output / name
        if json.loads(path.read_text()) != expected:
            raise ValueError(f"vLLM view has stale {name}")

    source_files = linked_source_files(source)
    for name, source_path in source_files.items():
        output_path = output / name
        if not output_path.is_file() or not os.path.samefile(source_path, output_path):
            raise ValueError(f"vLLM view is not hard-linked to source: {name}")

    source_receipt_names = [
        "config.json",
        "model.safetensors.index.json",
        "modeling_dsv4_vl.py",
    ]
    if (source / "vision-projector.safetensors").is_file():
        source_receipt_names.append("vision-projector.safetensors")
    view_receipt_names = [
        "config.json",
        "preprocessor_config.json",
        "processor_config.json",
        "model.safetensors.index.json",
    ]
    if (output / "vision-projector.safetensors").is_file():
        view_receipt_names.append("vision-projector.safetensors")
    return {
        "format": "dsv4vl-vllm-eval-view-v1",
        "source": str(source.resolve()),
        "source_model_files": {
            name: sha256(source / name) for name in source_receipt_names
        },
        "view_model_files": {
            name: sha256(output / name) for name in view_receipt_names
        },
        "architecture": MODEL_ARCHITECTURE,
        "status": "PASS",
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--source", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--verify-existing", action="store_true")
    parser.add_argument("--refresh-config", action="store_true")
    parser.add_argument("--replace-incomplete", action="store_true")
    parser.add_argument("--prefer-symlinks", action="store_true")
    args = parser.parse_args()
    source = args.source.resolve()
    output = args.output.resolve()

    if args.verify_existing and args.refresh_config:
        parser.error("--verify-existing and --refresh-config are mutually exclusive")
    if (args.verify_existing or args.refresh_config) and (
        args.replace_incomplete or args.prefer_symlinks
    ):
        parser.error(
            "--replace-incomplete/--prefer-symlinks apply only when creating a view"
        )

    if args.verify_existing:
        receipt = verify_view(source, output)
    elif args.refresh_config:
        if not output.is_dir():
            raise FileNotFoundError(output)
        config, preprocessor, processor = expected_payloads(source)
        write_atomic(output / "config.json", config)
        write_atomic(output / "preprocessor_config.json", preprocessor)
        write_atomic(output / "processor_config.json", processor)
        receipt = verify_view(source, output)
        write_atomic(output / "vllm_eval_view.json", receipt)
    else:
        removed_incomplete = 0
        if output.exists() and any(output.iterdir()) and args.replace_incomplete:
            removed_incomplete = remove_proven_incomplete_view(source, output)
        if output.exists() and any(output.iterdir()):
            raise FileExistsError(output)
        output.mkdir(parents=True, exist_ok=True)
        link_modes = set()
        for path in linked_source_files(source).values():
            link_modes.add(
                link_source_file(path, output / path.name, args.prefer_symlinks)
            )
        config, preprocessor, processor = expected_payloads(source)
        write_atomic(output / "config.json", config)
        write_atomic(output / "preprocessor_config.json", preprocessor)
        write_atomic(output / "processor_config.json", processor)
        receipt = verify_view(source, output)
        receipt["link_modes"] = sorted(link_modes)
        receipt["removed_incomplete_files"] = removed_incomplete
        write_atomic(output / "vllm_eval_view.json", receipt)

    print(json.dumps(receipt, indent=2))


if __name__ == "__main__":
    main()