dsv4-flash-0731-vision / source /repository /scripts /finalize_text_baseline.py
sigilwen's picture
Back up private DSV4-VL source at 38faa0fcaff0
1d7c7c4 verified
Raw History Blame Contribute Delete
16.1 kB
#!/usr/bin/env python3
"""Finalize the exact-0731 text baseline from sandboxed evaluation artifacts."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
from pathlib import Path
from typing import Any
FORMAT = "dsv4vl-text-baseline-v1"
MODEL_ID = "deepseek-ai/DeepSeek-V4-Flash-0731"
BASE_GENERATION_MODEL = "deepseek-v4-flash-0731-base"
TERMINAL_FORMAT = "dsv4vl-terminal-bench-summary-v2"
TEXT_MODEL_FILES = ("config.json", "model.safetensors.index.json", "tokenizer.json")
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 parse_evalplus(path: Path, expected_solutions: dict[str, str]) -> dict[str, Any]:
payload = json.loads(path.read_text())
evaluations = payload.get("eval")
if not isinstance(evaluations, dict) or len(evaluations) != 164:
raise ValueError(f"EvalPlus must contain 164 tasks, got {0 if not isinstance(evaluations, dict) else len(evaluations)}")
if set(evaluations) != set(expected_solutions):
raise ValueError("EvalPlus task IDs differ from the generated HumanEval+ rows")
if any(not isinstance(rows, list) or len(rows) != 1 for rows in evaluations.values()):
raise ValueError("EvalPlus baseline must contain exactly one completion per task")
for task_id, rows in evaluations.items():
if rows[0].get("solution") != expected_solutions[task_id]:
raise ValueError(
f"EvalPlus solution differs from generated completion: {task_id}"
)
rows = [values[0] for values in evaluations.values()]
base_passed = sum(str(row.get("base_status", "")).lower() == "pass" for row in rows)
plus_passed = sum(
str(row.get("base_status", "")).lower() == "pass"
and str(row.get("plus_status", "")).lower() == "pass"
for row in rows
)
return {
"tasks": 164,
"samples_per_task": 1,
"base_passed": base_passed,
"plus_passed": plus_passed,
"base_pass_at_1": base_passed / 164,
"plus_pass_at_1": plus_passed / 164,
}
def validate_evalplus_receipt(
receipt_path: Path,
samples_path: Path,
results_path: Path,
manifest_path: Path,
manifest: dict[str, Any],
) -> None:
receipt = json.loads(receipt_path.read_text())
config = manifest["text"]["humaneval_plus"]
if (
receipt.get("format") != "dsv4vl-evalplus-sandbox-v1"
or receipt.get("status") != "PASS"
or receipt.get("repo") != config["evalplus_repo"]
or receipt.get("revision") != config["evalplus_revision"]
or receipt.get("dataset_version") != config["version"]
or receipt.get("dataset_gzip_sha256") != config["gzip_sha256"]
or receipt.get("samples", {}).get("sha256") != sha256(samples_path)
or int(receipt.get("samples", {}).get("rows", -1)) != 164
or receipt.get("results", {}).get("sha256") != sha256(results_path)
or int(receipt.get("results", {}).get("tasks", -1)) != 164
or receipt.get("eval_manifest", {}).get("sha256") != sha256(manifest_path)
or not receipt.get("docker_image_id")
):
raise ValueError("EvalPlus sandbox receipt differs from the pinned artifacts")
def parse_generation_output(
path: Path, expected_model: str
) -> tuple[dict[str, str], int]:
rows = [json.loads(line) for line in path.open() if line.strip()]
if len(rows) != 172:
raise ValueError(f"raw text generation must contain 172 rows, got {len(rows)}")
keys = [(str(row.get("suite")), str(row.get("id"))) for row in rows]
if len(keys) != len(set(keys)):
raise ValueError("raw text generation contains duplicate suite/id rows")
if any(row.get("model") != expected_model for row in rows):
raise ValueError("raw text generation contains a different served model")
if any(not isinstance(row.get("raw_completion"), str) for row in rows):
raise ValueError("raw text generation contains a missing completion")
humaneval = [row for row in rows if row.get("suite") == "humaneval_plus"]
long_context = [
row for row in rows if row.get("suite") == "dsv4vl_synthetic_needle_v1"
]
if len(humaneval) != 164 or len(long_context) != 8:
raise ValueError("raw text generation suite counts differ")
task_ids = {str(row.get("task_id")) for row in humaneval}
if task_ids != {str(row.get("id")) for row in humaneval}:
raise ValueError("raw HumanEval+ task_id/id fields differ")
solutions = {str(row["task_id"]): row.get("solution") for row in humaneval}
if any(not isinstance(solution, str) for solution in solutions.values()):
raise ValueError("raw HumanEval+ generation has a missing solution")
return solutions, sum(bool(row.get("correct")) for row in long_context)
def parse_terminal(
path: Path,
manifest: dict[str, Any],
expected_model: str,
expected_manifest_sha256: str,
expected_model_files: dict[str, str] | None = None,
require_model_receipt: bool = False,
) -> dict[str, Any]:
payload = json.loads(path.read_text())
terminal = manifest["text"]["terminal_bench"]
base_image_rows = payload.get("base_images", {}).get("images", [])
expected_base_images = {
"ghcr.io/laude-institute/t-bench/ubuntu-24-04:latest",
"ghcr.io/laude-institute/t-bench/python-3-13:latest",
}
if payload.get("format") != TERMINAL_FORMAT or payload.get("status") != "PASS":
raise ValueError(f"unexpected Terminal-Bench summary format: {payload.get('format')}")
if payload.get("model") != expected_model:
raise ValueError(
f"Terminal-Bench model differs: {payload.get('model')!r} != {expected_model!r}"
)
for key in (
"dataset",
"version",
"repo",
"dataset_revision",
"harness_version",
"harness_revision",
):
if payload.get(key) != terminal[key]:
raise ValueError(f"Terminal-Bench {key} mismatch: {payload.get(key)!r}")
if (
int(payload.get("attempts_per_task", -1)) != 1
or not payload.get("results", {}).get("sha256")
or not payload.get("run_metadata", {}).get("sha256")
or not payload.get("base_images", {}).get("sha256")
or not isinstance(base_image_rows, list)
or {row.get("name") for row in base_image_rows} != expected_base_images
or any(not row.get("id") or not row.get("dockerfile_sha256") for row in base_image_rows)
or payload.get("eval_manifest", {}).get("sha256")
!= expected_manifest_sha256
):
raise ValueError("Terminal-Bench summary lacks pinned raw-run provenance")
tasks = payload.get("tasks")
expected = set(terminal["task_ids"])
if not isinstance(tasks, dict) or set(tasks) != expected:
raise ValueError("Terminal-Bench task set differs from the pinned ten-task subset")
rewards = [float(tasks[task]["reward"]) for task in terminal["task_ids"]]
if any(not 0.0 <= value <= 1.0 for value in rewards):
raise ValueError("Terminal-Bench rewards must be in [0, 1]")
model_receipt = payload.get("model_receipt")
if require_model_receipt:
if (
not isinstance(model_receipt, dict)
or model_receipt.get("format") != "dsv4vl-terminal-server-status-v1"
or model_receipt.get("status") != "READY"
or model_receipt.get("served_model") != expected_model
or not isinstance(model_receipt.get("sha256"), str)
or re.fullmatch(r"[0-9a-f]{64}", model_receipt["sha256"]) is None
or model_receipt.get("model_files") != expected_model_files
):
raise ValueError(
"adapted Terminal-Bench endpoint is not bound to the generated-text model"
)
return {
"tasks": len(rewards),
"passed": sum(value == 1.0 for value in rewards),
"mean_reward": sum(rewards) / len(rewards),
}
def build_report(
generation_path: Path,
evalplus_path: Path,
evalplus_samples_path: Path,
evalplus_receipt_path: Path,
terminal_path: Path,
manifest_path: Path,
*,
format_name: str = FORMAT,
model_id: str = MODEL_ID,
expected_generation_model: str = BASE_GENERATION_MODEL,
) -> dict[str, Any]:
generation = json.loads(generation_path.read_text())
if generation.get("status") != "PASS":
raise ValueError("text generation report did not pass")
if generation.get("model") != expected_generation_model:
raise ValueError(
"text generation report model differs: "
f"{generation.get('model')!r} != {expected_generation_model!r}"
)
if generation.get("suites") != {
"humaneval_plus": 164,
"dsv4vl_synthetic_needle_v1": 8,
}:
raise ValueError(f"generation suite counts differ: {generation.get('suites')}")
if int(generation.get("long_context_total", 0)) != 8:
raise ValueError("long-context baseline is incomplete")
generation_output = Path(str(generation.get("output", "")))
if not generation_output.is_file():
raise ValueError(f"raw text-generation output is missing: {generation_output}")
if generation.get("output_sha256") != sha256(generation_output):
raise ValueError("raw text-generation output SHA-256 differs from its report")
humaneval_solutions, long_context_correct = parse_generation_output(
generation_output, expected_generation_model
)
if int(generation.get("long_context_correct", -1)) != long_context_correct:
raise ValueError("raw long-context score differs from generation report")
run_manifest = Path(str(generation.get("run_manifest", "")))
if not run_manifest.is_file():
raise ValueError(f"text-generation run manifest is missing: {run_manifest}")
if generation.get("run_manifest_sha256") != sha256(run_manifest):
raise ValueError("text-generation run manifest SHA-256 differs from its report")
bound_run = json.loads(run_manifest.read_text())
if (
bound_run.get("format") != "dsv4vl-text-eval-run-v1"
or bound_run.get("served_model") != expected_generation_model
):
raise ValueError("text-generation run manifest has wrong format/model")
model_path = Path(str(bound_run.get("model_path", "")))
if set(bound_run.get("model_files", {})) != set(TEXT_MODEL_FILES):
raise ValueError("text-generation run manifest has incomplete model files")
for name in TEXT_MODEL_FILES:
path = model_path / name
if not path.is_file() or bound_run["model_files"][name] != sha256(path):
raise ValueError(f"text-generation bound model file differs: {path}")
inputs = bound_run.get("inputs")
if not isinstance(inputs, list) or len(inputs) != 2:
raise ValueError("text-generation run manifest must bind two input JSONLs")
for item in inputs:
path = Path(str(item.get("path", "")))
if not path.is_file() or item.get("sha256") != sha256(path):
raise ValueError(f"text-generation bound input differs: {path}")
manifest = json.loads(manifest_path.read_text())
validate_evalplus_receipt(
evalplus_receipt_path,
evalplus_samples_path,
evalplus_path,
manifest_path,
manifest,
)
return {
"format": format_name,
"model_id": model_id,
"generation_model": generation["model"],
"metrics": {
"long_context": {
"correct": int(generation["long_context_correct"]),
"total": 8,
"accuracy": int(generation["long_context_correct"]) / 8,
},
"humaneval_plus": parse_evalplus(evalplus_path, humaneval_solutions),
"terminal_bench": parse_terminal(
terminal_path,
manifest,
expected_generation_model,
sha256(manifest_path),
bound_run["model_files"],
format_name == "dsv4vl-text-adapted-v1",
),
},
"artifacts": {
"generation_output": {
"path": str(generation_output.resolve()),
"sha256": sha256(generation_output),
},
"generation_report": {"path": str(generation_path.resolve()), "sha256": sha256(generation_path)},
"generation_run_manifest": {
"path": str(run_manifest.resolve()),
"sha256": sha256(run_manifest),
},
"evalplus": {"path": str(evalplus_path.resolve()), "sha256": sha256(evalplus_path)},
"evalplus_samples": {
"path": str(evalplus_samples_path.resolve()),
"sha256": sha256(evalplus_samples_path),
},
"evalplus_receipt": {
"path": str(evalplus_receipt_path.resolve()),
"sha256": sha256(evalplus_receipt_path),
},
"terminal_bench": {"path": str(terminal_path.resolve()), "sha256": sha256(terminal_path)},
"eval_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)},
},
}
def markdown(report: dict[str, Any]) -> str:
metrics = report["metrics"]
long_context = metrics["long_context"]
humaneval = metrics["humaneval_plus"]
terminal = metrics["terminal_bench"]
return f"""# {report['model_id']} text evaluation
- Model: `{report['model_id']}`
- Long context: {long_context['correct']}/{long_context['total']} ({long_context['accuracy']:.3f})
- HumanEval+ base pass@1: {humaneval['base_pass_at_1']:.4f}
- HumanEval+ plus pass@1: {humaneval['plus_pass_at_1']:.4f}
- Terminal-Bench 0.1.1 pinned subset: {terminal['passed']}/{terminal['tasks']} passed; mean reward {terminal['mean_reward']:.4f}
HumanEval+ and Terminal-Bench results were imported from isolated runners. See the JSON artifact for immutable source hashes.
"""
def atomic_write(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists():
raise FileExistsError(f"refusing to replace existing baseline: {path}")
temporary = path.with_suffix(path.suffix + f".tmp-{os.getpid()}")
temporary.write_text(content)
os.replace(temporary, path)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--generations", type=Path, required=True, help="*.jsonl.report.json")
parser.add_argument("--evalplus", type=Path, required=True)
parser.add_argument("--evalplus-samples", type=Path, required=True)
parser.add_argument("--evalplus-receipt", type=Path, required=True)
parser.add_argument("--terminal-bench", type=Path, required=True)
parser.add_argument("--manifest", type=Path, default=Path("data/eval_manifest.json"))
parser.add_argument("--output-json", type=Path, required=True)
parser.add_argument("--output-md", type=Path, required=True)
parser.add_argument("--format-name", default=FORMAT)
parser.add_argument("--model-id", default=MODEL_ID)
parser.add_argument("--expected-generation-model", default=BASE_GENERATION_MODEL)
args = parser.parse_args()
existing = [path for path in (args.output_json, args.output_md) if path.exists()]
if existing:
raise FileExistsError(f"refusing to replace existing baseline artifacts: {existing}")
report = build_report(
args.generations,
args.evalplus,
args.evalplus_samples,
args.evalplus_receipt,
args.terminal_bench,
args.manifest,
format_name=args.format_name,
model_id=args.model_id,
expected_generation_model=args.expected_generation_model,
)
atomic_write(args.output_json, json.dumps(report, indent=2) + "\n")
atomic_write(args.output_md, markdown(report))
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()