dsv4-flash-0731-vision / source /repository /scripts /create_vllm_eval_view.py
sigilwen's picture
Back up private DSV4-VL source at 38faa0fcaff0
1d7c7c4 verified
Raw History Blame Contribute Delete
12.9 kB
#!/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()