#!/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()