dsv4-flash-0731-vision / source /repository /scripts /export_humaneval_samples.py
sigilwen's picture
Back up private DSV4-VL source at 38faa0fcaff0
1d7c7c4 verified
Raw History Blame Contribute Delete
4.42 kB
#!/usr/bin/env python3
"""Export exact model-generated HumanEval+ solutions for an isolated runner."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
from typing import Any
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 payload(generations: Path) -> tuple[bytes, dict[str, Any]]:
rows = [json.loads(line) for line in generations.open() if line.strip()]
humaneval = [row for row in rows if row.get("suite") == "humaneval_plus"]
if len(humaneval) != 164:
raise ValueError(f"expected 164 HumanEval+ generations, got {len(humaneval)}")
task_ids = [str(row.get("task_id")) for row in humaneval]
if len(task_ids) != len(set(task_ids)):
raise ValueError("HumanEval+ generations contain duplicate task IDs")
if any(str(row.get("id")) != task_id for row, task_id in zip(humaneval, task_ids)):
raise ValueError("HumanEval+ id/task_id fields differ")
samples = []
for row, task_id in zip(humaneval, task_ids):
solution = row.get("solution")
if not isinstance(solution, str) or not solution.strip():
raise ValueError(f"HumanEval+ generation has no solution: {task_id}")
samples.append({"task_id": task_id, "solution": solution})
raw = b"".join(
(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n").encode()
for row in samples
)
return raw, {
"format": "dsv4vl-evalplus-samples-v1",
"source_generations": str(generations.resolve()),
"source_generations_sha256": sha256(generations),
"tasks": len(samples),
"task_ids": task_ids,
"model": humaneval[0].get("model"),
}
def export(generations: Path, output: Path, resume: bool) -> dict[str, Any]:
raw, manifest = payload(generations)
manifest_path = output.with_suffix(output.suffix + ".manifest.json")
expected = {
**manifest,
"output": str(output.resolve()),
"output_sha256": hashlib.sha256(raw).hexdigest(),
}
if output.exists() or manifest_path.exists():
if not resume:
raise FileExistsError(f"refusing incomplete/existing sandbox artifact: {output}")
if output.exists() and (not output.is_file() or output.read_bytes() != raw):
raise ValueError("existing HumanEval+ sandbox artifact differs from generations")
if manifest_path.exists() and (
not manifest_path.is_file()
or json.loads(manifest_path.read_text()) != expected
):
raise ValueError("existing HumanEval+ sandbox artifact differs from generations")
# Repair a crash between the two atomic commits, but only from the
# exact bytes deterministically derived from the bound generations.
if not output.exists():
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_suffix(output.suffix + f".tmp-{os.getpid()}")
temporary.write_bytes(raw)
os.replace(temporary, output)
if not manifest_path.exists():
temporary_manifest = manifest_path.with_suffix(
manifest_path.suffix + f".tmp-{os.getpid()}"
)
temporary_manifest.write_text(json.dumps(expected, indent=2) + "\n")
os.replace(temporary_manifest, manifest_path)
return expected
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_suffix(output.suffix + f".tmp-{os.getpid()}")
temporary.write_bytes(raw)
os.replace(temporary, output)
temporary_manifest = manifest_path.with_suffix(
manifest_path.suffix + f".tmp-{os.getpid()}"
)
temporary_manifest.write_text(json.dumps(expected, indent=2) + "\n")
os.replace(temporary_manifest, manifest_path)
return expected
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--generations", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--resume", action="store_true")
args = parser.parse_args()
print(json.dumps(export(args.generations, args.output, args.resume), indent=2))
if __name__ == "__main__":
main()