File size: 4,888 Bytes
81663e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""Materialize the fixed train/test tasks from corrected, pinned Harbor datasets."""

from __future__ import annotations

import argparse
import hashlib
import json
import shutil
from pathlib import Path

import tomllib

ROOT = Path(__file__).resolve().parent


def task_rows(split):
    return json.loads((ROOT / "data" / f"{split}.json").read_text())


def write_json(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2) + "\n")


DATASETS = {
    "train": (
        "FineEnvs/SmolDataEnvs-harbor-train",
        "4719635555de1666f374d847baebb500d368e493",
    ),
    "test": (
        "FineEnvs/SmolDataEnvs-harbor-test",
        "b130595b579fc6026ad5762925a9a3b40e72f5bb",
    ),
}
GRADER_SHA256 = "16f906e9248fa8b7e1141939e425e88e59d52d65e98e360bbacef3720a43629f"


def prepare(destination, sources=None):
    import tomli_w
    from huggingface_hub import snapshot_download

    destination = Path(destination).resolve()
    manifests = {}
    for split in ("train", "test"):
        rows = task_rows(split)
        repo, revision = DATASETS[split]
        source = (sources or {}).get(split)
        if source is None:
            source = snapshot_download(
                repo,
                repo_type="dataset",
                revision=revision,
                allow_patterns=[f"tasks/{r['name']}/*" for r in rows],
                max_workers=16,
            )
        source = Path(source)
        tasks = []
        for row in rows:
            folder = source / "tasks" / row["name"]
            instruction = (folder / "instruction.md").read_bytes()
            if hashlib.sha256(instruction).hexdigest() != row["instruction_sha256"]:
                raise ValueError(
                    f"Historical task instruction changed: {split}/{row['name']}"
                )
            grader = (folder / "tests/grader.py").read_bytes()
            if hashlib.sha256(grader).hexdigest() != GRADER_SHA256:
                raise ValueError(
                    f"Expected corrected numeric-only Harbor grader: {folder}"
                )
            target = destination / "datasets" / split / "tasks" / row["name"]
            target.mkdir(parents=True, exist_ok=True)
            for rel in (
                "instruction.md",
                "task.toml",
                "environment/Dockerfile",
                "environment/pull_bucket.py",
                "tests/grader.py",
                "tests/test.sh",
            ):
                dst = target / rel
                dst.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(folder / rel, dst)
            spec = tomllib.loads((target / "task.toml").read_text())
            spec["environment"]["memory_mb"] = 4096
            spec["environment"]["cpus"] = 1
            # Cluster user IDs may not exist inside Daytona's user namespace.
            spec["environment"].setdefault("env", {})["TAR_OPTIONS"] = "--no-same-owner"
            (target / "task.toml").write_text(tomli_w.dumps(spec))
            hashes = {
                str(f.relative_to(destination / "datasets" / split)): hashlib.sha256(
                    f.read_bytes()
                ).hexdigest()
                for f in sorted(target.rglob("*"))
                if f.is_file()
            }
            tasks.append({**row, "file_hashes": hashes})
        local = (sources or {}).get(split)
        manifest = {
            "source_dataset": repo,
            "source_revision": None if local else revision,
            "expected_hub_revision": revision,
            "local_source": str(local) if local else None,
            "task_count": len(tasks),
            "tasks": tasks,
        }
        write_json(destination / f"{split}_manifest.json", manifest)
        manifests[split] = manifest
    train = {r["source"] for r in manifests["train"]["tasks"]}
    test = {r["source"] for r in manifests["test"]["tasks"]}
    notebooks = [
        {r.get("notebook") for r in manifests[s]["tasks"]} - {None}
        for s in ("train", "test")
    ]
    if train & test or notebooks[0] & notebooks[1]:
        raise ValueError("Train/test overlap")
    write_json(
        destination / "ready.json",
        {
            "train": len(train),
            "test": len(test),
            "grader_sha256": GRADER_SHA256,
            "train_test_overlap": 0,
        },
    )
    return manifests


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--output", type=Path, default=ROOT / "prepared")
    p.add_argument("--train-source", type=Path)
    p.add_argument("--test-source", type=Path)
    a = p.parse_args()
    result = prepare(
        a.output,
        {s: v for s, v in (("train", a.train_source), ("test", a.test_source)) if v},
    )
    print(json.dumps({s: m["task_count"] for s, m in result.items()}))