#!/usr/bin/env python3 """Assemble the verified DSV4-VL release report and model card.""" from __future__ import annotations import argparse import hashlib import json import math import os import shutil from collections import defaultdict from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] EXPECTED_VISION_ROWS = {"mmbench_en_dev": 4329, "textvqa_val": 5000, "mme": 2374} BASE_TEXT_MODEL = "deepseek-ai/DeepSeek-V4-Flash-0731" ADAPTED_TEXT_MODEL = "deepseek-ai/DeepSeek-V4-Flash-0731-vision-adapted-bf16" BASE_GENERATION_MODEL = "deepseek-v4-flash-0731-base" ADAPTED_GENERATION_MODEL = "deepseek-v4-flash-0731-vision-adapted-bf16" PUBLICATION_FILES = ( "research-paper.md", "technical-report.md", "experiment-ledger.md", "accomplishments-and-next-plan.md", "publication_state.json", ) PUBLICATION_ASSETS = ("figures/stage2-training-curves.svg",) PUBLICATION_PATHS = PUBLICATION_FILES + PUBLICATION_ASSETS 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 read_json(path: Path) -> dict[str, Any]: return json.loads(path.read_text()) def require_file_binding(binding: Any, path: Path, label: str) -> None: if not isinstance(binding, dict) or set(binding) != {"path", "sha256"}: raise ValueError(f"{label} has no exact file binding") if Path(str(binding["path"])).resolve() != path.resolve(): raise ValueError(f"{label} path differs from the selected report") if binding["sha256"] != sha256(path): raise ValueError(f"{label} SHA-256 differs from the selected report") def require_file_binding_path(binding: Any, label: str) -> Path: if not isinstance(binding, dict) or set(binding) != {"path", "sha256"}: raise ValueError(f"{label} has no exact file binding") path = Path(str(binding["path"])).resolve() require_file_binding(binding, path, label) return path def require_numeric_check( check: dict[str, Any], *, before_key: str, after_key: str, before: float, after: float, limit_key: str, limit: float, ) -> None: actual_before = float(check.get(before_key, float("nan"))) actual_after = float(check.get(after_key, float("nan"))) actual_limit = float(check.get(limit_key, float("nan"))) if ( not all(math.isfinite(value) for value in (actual_before, actual_after, actual_limit)) or not math.isclose(actual_before, before, rel_tol=0, abs_tol=1e-12) or not math.isclose(actual_after, after, rel_tol=0, abs_tol=1e-12) or not math.isclose(actual_limit, limit, rel_tol=0, abs_tol=1e-12) or not bool(check.get("pass")) ): raise ValueError(f"comparison check differs from source metrics: {check.get('name')}") def response(row: dict[str, Any], *keys: str) -> str: for key in keys: value = row.get(key) if isinstance(value, str) and value.strip(): return value.strip() raise ValueError(f"release smoke row has no response: {row.get('suite')} {row.get('id')}") def vision_smoke(path: Path) -> tuple[list[dict[str, Any]], dict[str, int]]: grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) for line in path.open(): if line.strip(): row = json.loads(line) grouped[str(row.get("suite"))].append(row) counts = {suite: len(grouped.get(suite, [])) for suite in EXPECTED_VISION_ROWS} if counts != EXPECTED_VISION_ROWS: raise ValueError(f"final vision result counts differ: {counts}") selected = grouped["mmbench_en_dev"][:4] + grouped["textvqa_val"][:4] mme_by_question: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in grouped["mme"]: mme_by_question[str(row.get("question_id"))].append(row) pair = next((rows for rows in mme_by_question.values() if len(rows) == 2), None) if pair is None: raise ValueError("final vision results contain no complete MME pair") selected.extend(pair) for row in selected: response(row, "response", "raw_completion", "prediction") return [ { "suite": row["suite"], "id": row["id"], "response": response(row, "response", "raw_completion", "prediction"), } for row in selected ], counts def text_smoke(path: Path) -> tuple[list[dict[str, Any]], dict[str, int]]: rows = [json.loads(line) for line in path.open() if line.strip()] grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in rows: grouped[str(row.get("suite"))].append(row) counts = {suite: len(values) for suite, values in grouped.items()} if counts != {"humaneval_plus": 164, "dsv4vl_synthetic_needle_v1": 8}: raise ValueError(f"adapted text generation counts differ: {counts}") selected = grouped["humaneval_plus"][:5] + grouped["dsv4vl_synthetic_needle_v1"][:5] for row in selected: response(row, "raw_completion") return [ { "suite": row["suite"], "id": row["id"], "response": response(row, "raw_completion"), } for row in selected ], counts def validate_reports(paths: dict[str, Path], model: Path) -> dict[str, dict[str, Any]]: reports = {name: read_json(path) for name, path in paths.items()} export = reports["export_verification"] merged_lora_checks = export.get("merged_lora_checks") merged_lora_topology = { (item.get("layer"), item.get("module")) for item in merged_lora_checks or [] if isinstance(item, dict) } expected_merged_lora_topology = { (layer, module) for layer in (0, 21, 42) for module in ("wq_a", "wq_b", "wkv", "wo_b") } if ( export.get("format") != "dsv4vl-export-verification-v1" or export.get("status") != "PASS" or Path(export.get("model", "")).resolve() != model.resolve() or export.get("adapter_lora_tensors") != 344 or export.get("adapter_auxiliary_tensors") != 86 or len(export.get("projector_tensors", [])) != 4 or not isinstance(merged_lora_checks, list) or len(merged_lora_checks) != len(expected_merged_lora_topology) or merged_lora_topology != expected_merged_lora_topology or any( int(item.get("effective_samples", -1)) != int(item.get("samples", -2)) or int(item.get("samples", 0)) <= 0 or float(item.get("max_abs_error", float("inf"))) > float(item.get("tolerance", -1)) for item in merged_lora_checks or [] ) ): raise ValueError("export verification report is not the exact accepted topology") source_verification_path = require_file_binding_path( export.get("source_verification"), "Phase-6 source verification" ) source_verification = read_json(source_verification_path) if ( source_verification.get("format") != "dsv4vl-phase6-source-inputs-v1" or source_verification.get("status") != "PASS" or Path(str(source_verification.get("hf_init", {}).get("path", ""))).resolve() != Path(str(export.get("source", ""))).resolve() or Path(str(source_verification.get("mcore", {}).get("path", ""))).resolve() != Path(str(export.get("mcore", ""))).resolve() or int(source_verification.get("hf_init", {}).get("language_shards", -1)) != 48 or int(source_verification.get("hf_init", {}).get("visual_tensors", -1)) != 452 or int(source_verification.get("mcore", {}).get("state_entries", -1)) != 24_541 or int(source_verification.get("mcore", {}).get("storage_entries", -1)) != 57_522 ): raise ValueError("Phase-6 source verification is not bound to the export source") index = read_json(model / "model.safetensors.index.json") expected_shards = set(index.get("weight_map", {}).values()) if not expected_shards: raise ValueError("final export index contains no model shards") shard_receipts = export.get("shards") if ( not isinstance(shard_receipts, list) or len(shard_receipts) != int(export.get("shard_count", -1)) or {item.get("name") for item in shard_receipts if isinstance(item, dict)} != expected_shards ): raise ValueError("export verification lacks the exact model shard set") shard_bytes = 0 for item in shard_receipts: if set(item) != {"name", "bytes", "sha256"}: raise ValueError("export verification has an invalid shard receipt") name = item["name"] if Path(name).name != name: raise ValueError("export verification has an unsafe shard name") shard = model / name if ( not shard.is_file() or shard.stat().st_size != int(item["bytes"]) or sha256(shard) != item["sha256"] ): raise ValueError(f"export shard changed after verification: {shard}") shard_bytes += int(item["bytes"]) if shard_bytes != int(export.get("shard_bytes", -1)): raise ValueError("export shard byte total differs from verification") vision_provenance = [] for name in ("stage1_vision", "final_vision"): report = reports[name] if report.get("format") != "dsv4vl-vision-eval-v1" or report.get("status") != "PASS": raise ValueError(f"{name} report did not pass") rows = {suite: report["results"][suite]["rows"] for suite in EXPECTED_VISION_ROWS} if rows != EXPECTED_VISION_ROWS: raise ValueError(f"{name} report is incomplete") if int(report["results"]["mme"].get("incomplete_pairs", -1)) != 0: raise ValueError(f"{name} report contains incomplete MME pairs") inputs = report.get("evaluation_inputs") manifest = report.get("eval_manifest", {}).get("sha256") if ( not isinstance(inputs, list) or len(inputs) != 3 or any(set(item) != {"path", "sha256"} for item in inputs) or not manifest ): raise ValueError(f"{name} report lacks bound evaluation provenance") raw_artifacts = report.get("input_artifacts") if not isinstance(raw_artifacts, list) or len(raw_artifacts) != 1: raise ValueError(f"{name} report lacks its raw generation binding") raw_path = Path(str(raw_artifacts[0].get("path", ""))).resolve() require_file_binding( raw_artifacts[0], raw_path, f"{name} raw vision generations" ) if report.get("inputs") != [str(raw_path)]: raise ValueError(f"{name} report names a different raw result file") run_path = require_file_binding_path( report.get("run_manifest"), f"{name} run manifest" ) run = read_json(run_path) if ( run.get("format") != "dsv4vl-vision-eval-run-v1" or run.get("inputs") != inputs ): raise ValueError(f"{name} run manifest differs from the score report") if name == "final_vision": require_file_binding( run.get("model_verification"), paths["export_verification"], "final vision export verification", ) vision_provenance.append((inputs, manifest)) if vision_provenance[0] != vision_provenance[1]: raise ValueError("Stage-1/final vision reports use different holdouts") vision_comparison = reports["vision_improvement"] if ( vision_comparison.get("format") != "dsv4vl-vision-regression-v1" or vision_comparison.get("status") != "PASS" ): raise ValueError("final model did not pass the Stage-1 vision improvement gate") require_file_binding( vision_comparison.get("reports", {}).get("stage1"), paths["stage1_vision"], "vision comparison Stage-1 report", ) require_file_binding( vision_comparison.get("reports", {}).get("final"), paths["final_vision"], "vision comparison final report", ) vision_checks = {item.get("name"): item for item in vision_comparison.get("checks", [])} expected_vision_checks = { "mmbench_static_accuracy", "textvqa_exact_match", "mme_total_score" } if set(vision_checks) != expected_vision_checks or len(vision_comparison.get("checks", [])) != 3: raise ValueError("vision comparison check topology differs") stage1 = reports["stage1_vision"]["results"] final = reports["final_vision"]["results"] for name, suite, metric, required_gain in ( ("mmbench_static_accuracy", "mmbench_en_dev", "static_accuracy", 0.01), ("textvqa_exact_match", "textvqa_val", "exact_match", 0.01), ("mme_total_score", "mme", "total_score", 10.0), ): if name not in vision_checks: raise ValueError(f"vision comparison omitted {name}") if float(final[suite][metric]) - float(stage1[suite][metric]) < required_gain - 1e-12: raise ValueError(f"vision source metrics fail required gain: {name}") require_numeric_check( vision_checks[name], before_key="stage1", after_key="final", before=float(stage1[suite][metric]), after=float(final[suite][metric]), limit_key="required_gain", limit=required_gain, ) base = reports["text_baseline"] adapted = reports["text_adapted"] if ( base.get("format") != "dsv4vl-text-baseline-v1" or base.get("model_id") != BASE_TEXT_MODEL or base.get("generation_model") != BASE_GENERATION_MODEL or adapted.get("format") != "dsv4vl-text-adapted-v1" or adapted.get("model_id") != ADAPTED_TEXT_MODEL or adapted.get("generation_model") != ADAPTED_GENERATION_MODEL ): raise ValueError("text reports have unexpected model provenance") if ( not base.get("artifacts", {}).get("eval_manifest", {}).get("sha256") or base["artifacts"]["eval_manifest"]["sha256"] != adapted.get("artifacts", {}).get("eval_manifest", {}).get("sha256") ): raise ValueError("base/adapted text reports use different eval manifests") text_comparison = reports["text_regression"] if ( text_comparison.get("format") != "dsv4vl-text-regression-v1" or text_comparison.get("status") != "PASS" or text_comparison.get("base_model") != BASE_TEXT_MODEL or text_comparison.get("adapted_model") != ADAPTED_TEXT_MODEL ): raise ValueError("final model did not pass exact pre/post text regression") require_file_binding( text_comparison.get("reports", {}).get("base"), paths["text_baseline"], "text comparison base report", ) require_file_binding( text_comparison.get("reports", {}).get("adapted"), paths["text_adapted"], "text comparison adapted report", ) text_checks = {item.get("name"): item for item in text_comparison.get("checks", [])} expected_text_checks = { "long_context_accuracy", "humaneval_base_pass_at_1", "humaneval_plus_pass_at_1", "terminal_bench_mean_reward", } if set(text_checks) != expected_text_checks or len(text_comparison.get("checks", [])) != 4: raise ValueError("text comparison check topology differs") bm, am = base["metrics"], adapted["metrics"] text_metrics = ( ( "long_context_accuracy", float(bm["long_context"]["accuracy"]), float(am["long_context"]["accuracy"]), max(0.03, 1 / int(bm["long_context"]["total"])), ), ( "humaneval_base_pass_at_1", float(bm["humaneval_plus"]["base_pass_at_1"]), float(am["humaneval_plus"]["base_pass_at_1"]), 0.03, ), ( "humaneval_plus_pass_at_1", float(bm["humaneval_plus"]["plus_pass_at_1"]), float(am["humaneval_plus"]["plus_pass_at_1"]), 0.03, ), ( "terminal_bench_mean_reward", float(bm["terminal_bench"]["mean_reward"]), float(am["terminal_bench"]["mean_reward"]), max(0.03, 1 / int(bm["terminal_bench"]["tasks"])), ), ) for name, before, after, tolerance in text_metrics: if name not in text_checks: raise ValueError(f"text comparison omitted {name}") if after - before < -tolerance - 1e-12: raise ValueError(f"text source metrics exceed allowed regression: {name}") require_numeric_check( text_checks[name], before_key="before", after_key="after", before=before, after=after, limit_key="maximum_allowed_drop", limit=tolerance, ) return reports def model_card( reports: dict[str, dict[str, Any]], export: dict[str, Any], release_state: dict[str, Any], ) -> str: stage1 = reports["stage1_vision"]["results"] final = reports["final_vision"]["results"] text = reports["text_adapted"]["metrics"] release_mode = release_state.get("release_mode", "planned-completion") release_iteration = int(release_state["stage2"]["final_checkpoint"]) planned_target = int(release_state.get("planned_target_steps", release_iteration)) release_note = ( f"This is an explicitly labeled **early-stop release at optimizer step " f"{release_iteration:,}**. The original schedule targeted {planned_target:,} " f"steps; the remaining {planned_target - release_iteration:,} steps were not run." if release_mode == "early-stop" else f"Stage 2 completed its planned {planned_target:,}-step schedule." ) return f"""# DSV4-VL — DeepSeek-V4-Flash-0731 with vision This model grafts a frozen Google SigLIP2 SO400M 384px vision tower and a trained two-layer GELU projector onto the exact deepseek-ai/DeepSeek-V4-Flash-0731 language model. Stage 2 merges an attention-only r64/alpha128 LoRA trained with the MoE router and every routed/shared expert frozen. {release_note} ## Verified artifacts - Export: BF16, {export['weight_count']} tensors, {export['shard_count']} shards - Projector: 4 tensors, SHA-256 {export['projector_sha256']} - Stage-2 adapter: 344 LoRA + 86 frozen hybrid-control tensors, SHA-256 {export['adapter_sha256']} - Phase-6 source receipt: SHA-256 {export['source_verification']['sha256']} - Tokenizer/vocabulary: unchanged from DeepSeek-V4-Flash-0731 ## Vision evaluation | Suite | Stage 1 | Final | |---|---:|---:| | MMBench EN dev | {stage1['mmbench_en_dev']['static_accuracy']:.6f} | {final['mmbench_en_dev']['static_accuracy']:.6f} | | TextVQA val | {stage1['textvqa_val']['exact_match']:.6f} | {final['textvqa_val']['exact_match']:.6f} | | MME | {stage1['mme']['total_score']:.3f} | {final['mme']['total_score']:.3f} | ## Text preservation - Long-context accuracy: {text['long_context']['accuracy']:.4f} - HumanEval base pass@1: {text['humaneval_plus']['base_pass_at_1']:.4f} - HumanEval+ pass@1: {text['humaneval_plus']['plus_pass_at_1']:.4f} - Terminal-Bench mean reward: {text['terminal_bench']['mean_reward']:.4f} All metric inputs, model views, and result files are hash-bound under the evaluation directory. The release requires a passing vision-improvement report and a passing pre/post text-regression report. ## Inference and limitations - Images are fixed at 384x384 and expand to 729 vision tokens each. - The vision tower is frozen; only the projector and Stage-2 attention adapter were trained. - DSpark/speculative decoding was not adapted for image inputs and must remain disabled for multimodal inference. - The merged export intentionally contains zero MTP layers and declares no source FP4 quantization. Use the separate text-only view for text serving. - AnyRes/tiling is not included; small text in dense documents or screenshots may require the documented v1.5 upgrade. """ def finalize( model: Path, report_paths: dict[str, Path], final_vision_results: Path, adapted_text_generations: Path, publication_root: Path | None = None, ) -> dict[str, Any]: model = model.resolve() for name in ("config.json", "model.safetensors.index.json", "tokenizer.json"): if not (model / name).is_file(): raise FileNotFoundError(model / name) reports = validate_reports(report_paths, model) multimodal, vision_counts = vision_smoke(final_vision_results) text, text_counts = text_smoke(adapted_text_generations) adapted_generation = reports["text_adapted"].get("artifacts", {}).get( "generation_output" ) require_file_binding( adapted_generation, adapted_text_generations, "adapted text raw generations", ) final_result_inputs = reports["final_vision"].get("inputs") if final_result_inputs != [str(final_vision_results.resolve())]: raise ValueError("final vision report does not name the selected raw result file") final_result_artifacts = reports["final_vision"].get("input_artifacts") if not isinstance(final_result_artifacts, list) or len(final_result_artifacts) != 1: raise ValueError("final vision report lacks the raw result file binding") require_file_binding( final_result_artifacts[0], final_vision_results, "final vision raw results", ) evaluation = model / "evaluation" documentation = model / "documentation" card_path = model / "MODEL_CARD.md" release_path = model / "release_manifest.json" if ( evaluation.exists() or documentation.exists() or card_path.exists() or release_path.exists() ): raise FileExistsError("refusing to replace existing release artifacts") evaluation.mkdir() copied = {} for name, source in report_paths.items(): target = evaluation / f"{name.upper()}.json" shutil.copy2(source, target) copied[name] = {"path": str(target), "sha256": sha256(target)} source_inputs = require_file_binding_path( reports["export_verification"]["source_verification"], "Phase-6 source verification", ) source_inputs_target = evaluation / "PHASE6_SOURCE_INPUTS.json" shutil.copy2(source_inputs, source_inputs_target) copied["phase6_source_inputs"] = { "path": str(source_inputs_target), "sha256": sha256(source_inputs_target), } documentation.mkdir() publications = {} publication_root = (publication_root or ROOT / "docs").resolve() release_state = read_json(publication_root / "publication_state.json") for name in PUBLICATION_PATHS: source = publication_root / name if not source.is_file() or source.stat().st_size == 0: raise FileNotFoundError(f"final publication is missing: {source}") target = documentation / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, target) publications[name] = {"path": str(target), "sha256": sha256(target)} smoke = { "format": "dsv4vl-release-smoke-v1", "status": "PASS", "multimodal_rows": len(multimodal), "text_rows": len(text), "vision_result_counts": vision_counts, "text_result_counts": text_counts, "multimodal": multimodal, "text": text, } smoke_path = evaluation / "SMOKE_REPORT.json" smoke_path.write_text(json.dumps(smoke, indent=2) + "\n") card_path.write_text( model_card(reports, reports["export_verification"], release_state) ) release_mode = release_state.get("release_mode", "planned-completion") release_iteration = int(release_state["stage2"]["final_checkpoint"]) planned_target = int(release_state.get("planned_target_steps", release_iteration)) release = { "format": "dsv4vl-release-v1", "status": "PASS", "model": str(model), "release_contract": { "release_mode": release_mode, "release_iteration": release_iteration, "planned_target_iteration": planned_target, "untrained_planned_iterations": planned_target - release_iteration, }, "model_files": { name: sha256(model / name) for name in ("config.json", "model.safetensors.index.json", "tokenizer.json") }, "model_shards": reports["export_verification"]["shards"], "projector": { "path": reports["export_verification"]["projector"], "sha256": reports["export_verification"]["projector_sha256"], }, "adapter": { "path": reports["export_verification"]["adapter"], "sha256": reports["export_verification"]["adapter_sha256"], }, "phase6_source_inputs": copied["phase6_source_inputs"], "reports": copied, "publications": publications, "smoke_report": {"path": str(smoke_path), "sha256": sha256(smoke_path)}, "model_card": {"path": str(card_path), "sha256": sha256(card_path)}, "final_vision_results": { "path": str(final_vision_results.resolve()), "sha256": sha256(final_vision_results), }, "adapted_text_generations": { "path": str(adapted_text_generations.resolve()), "sha256": sha256(adapted_text_generations), }, } temporary = release_path.with_suffix(release_path.suffix + f".tmp-{os.getpid()}") temporary.write_text(json.dumps(release, indent=2) + "\n") os.replace(temporary, release_path) print("DSV4VL_RELEASE_BUNDLE=PASS") return release def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--model", type=Path, required=True) parser.add_argument("--export-verification", type=Path, required=True) parser.add_argument("--stage1-vision", type=Path, required=True) parser.add_argument("--final-vision", type=Path, required=True) parser.add_argument("--vision-improvement", type=Path, required=True) parser.add_argument("--text-baseline", type=Path, required=True) parser.add_argument("--text-adapted", type=Path, required=True) parser.add_argument("--text-regression", type=Path, required=True) parser.add_argument("--final-vision-results", type=Path, required=True) parser.add_argument("--adapted-text-generations", type=Path, required=True) parser.add_argument("--publication-root", type=Path, default=ROOT / "docs") args = parser.parse_args() report_paths = { name: getattr(args, name) for name in ( "export_verification", "stage1_vision", "final_vision", "vision_improvement", "text_baseline", "text_adapted", "text_regression", ) } finalize( args.model, report_paths, args.final_vision_results, args.adapted_text_generations, args.publication_root, ) if __name__ == "__main__": main()