File size: 4,418 Bytes
1d7c7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/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()