File size: 8,275 Bytes
7230edc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python3
"""Build the public KernelZero CUDA SFT dataset from the exact training files."""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import re
import statistics
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq


STAGES = [
    {
        "name": "stage1",
        "sft": "resources/modules/turn1/cudallm_24k_sft_v1.json",
        "sources": [
            "resources/modules/turn1/cudallm_modules_distilled_0_40000_checked_passed.jsonl",
            "resources/modules/turn1/cudallm_modules_distilled_40000_90000_checked_passed.jsonl",
        ],
    },
    {
        "name": "stage2",
        "sft": "resources/modules/turn3/cudallm_19k_sft_t2t3.json",
        "sources": [
            "resources/modules/turn2/cudallm_modules_distilled_0_40000_2_checked_passed.jsonl",
            "resources/modules/turn2/cudallm_modules_distilled_40000_90000_2_checked_passed.jsonl",
            "resources/modules/turn3/cudallm_modules_distilled_0_40000_3_distilled_checked_passed.jsonl",
            "resources/modules/turn3/cudallm_modules_distilled_40000_90000_3_distilled_checked_passed.jsonl",
        ],
    },
]


def read_jsonl(path: Path):
    with path.open(encoding="utf-8") as handle:
        for line_no, line in enumerate(handle, 1):
            if line.strip():
                try:
                    yield json.loads(line)
                except json.JSONDecodeError as exc:
                    raise ValueError(f"Invalid JSON in {path}:{line_no}") from exc


def extract_cuda_code(answer: str) -> tuple[str, bool]:
    answer = answer.strip()
    match = re.fullmatch(r"```(?:python)?\s*\n?(.*?)\n?```", answer, flags=re.DOTALL)
    if match:
        return match.group(1).strip(), True
    return answer, False


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--num-shards", type=int, default=8)
    args = parser.parse_args()

    root = args.root.resolve()
    output = args.output.resolve()
    data_dir = output / "data"
    data_dir.mkdir(parents=True, exist_ok=True)

    records: list[dict] = []
    stage_counts: dict[str, int] = {}
    output_mismatches: list[dict] = []
    missing_speedup: list[dict] = []
    unfenced_answers: list[dict] = []

    for stage in STAGES:
        source_by_index: dict[int, dict] = {}
        for relative in stage["sources"]:
            source_path = root / relative
            for item in read_jsonl(source_path):
                index = int(item["index"])
                if index in source_by_index:
                    raise ValueError(f"Duplicate source index in {stage['name']}: {index}")
                source_by_index[index] = item

        with (root / stage["sft"]).open(encoding="utf-8") as handle:
            sft_rows = json.load(handle)

        stage_counts[stage["name"]] = len(sft_rows)
        if len(sft_rows) != len(source_by_index):
            raise ValueError(
                f"Count mismatch for {stage['name']}: "
                f"SFT={len(sft_rows)} source={len(source_by_index)}"
            )

        for sft in sft_rows:
            index = int(sft["index"])
            source = source_by_index.get(index)
            if source is None:
                raise ValueError(f"Missing source for {stage['name']} index={index}")

            response = source.get("response") or {}
            reasoning = str(response.get("reasoning", "")).strip()
            answer = str(response.get("answer", "")).strip()
            reconstructed_output = f"<think>{reasoning}</think>\n{answer}"
            if reconstructed_output != sft["output"]:
                output_mismatches.append({"stage": stage["name"], "index": index})

            result = source.get("result") or {}
            message = result.get("msg") or {}
            speedup = message.get("speedup") if isinstance(message, dict) else None
            if not isinstance(speedup, (int, float)) or not math.isfinite(float(speedup)):
                missing_speedup.append({"stage": stage["name"], "index": index})
                continue

            cuda_code, fenced = extract_cuda_code(answer)
            if not fenced:
                unfenced_answers.append({"stage": stage["name"], "index": index})

            operators = source.get("ops", "[]")
            if isinstance(operators, str):
                try:
                    operators = json.loads(operators)
                except json.JSONDecodeError:
                    operators = [operators]
            operators = [str(op) for op in operators]

            records.append(
                {
                    "input": sft["instruction"],
                    "output": sft["output"],
                    "torch_module": str(source["module"]),
                    "cuda_code": cuda_code,
                    "speedup": float(speedup),
                    "operators": operators,
                    "source_stage": stage["name"],
                    "source_index": index,
                }
            )

    if output_mismatches:
        raise ValueError(f"Output mismatches: {len(output_mismatches)}")
    if missing_speedup:
        raise ValueError(f"Missing or invalid speedups: {len(missing_speedup)}")
    if len(records) != 43_302:
        raise ValueError(f"Expected 43,302 records, found {len(records)}")

    identities = {(row["source_stage"], row["source_index"]) for row in records}
    if len(identities) != len(records):
        raise ValueError("Duplicate source identities")
    full_hashes = {
        hashlib.sha256(
            (row["input"] + "\0" + row["output"] + "\0" + row["torch_module"]).encode()
        ).hexdigest()
        for row in records
    }
    if len(full_hashes) != len(records):
        raise ValueError("Duplicate training records")

    schema = pa.schema(
        [
            ("input", pa.string()),
            ("output", pa.string()),
            ("torch_module", pa.string()),
            ("cuda_code", pa.string()),
            ("speedup", pa.float64()),
            ("operators", pa.list_(pa.string())),
            ("source_stage", pa.string()),
            ("source_index", pa.int64()),
        ]
    )

    shard_size = math.ceil(len(records) / args.num_shards)
    shard_paths: list[Path] = []
    for shard_id in range(args.num_shards):
        start = shard_id * shard_size
        end = min(len(records), start + shard_size)
        if start >= end:
            break
        table = pa.Table.from_pylist(records[start:end], schema=schema)
        path = data_dir / f"train-{shard_id:05d}-of-{args.num_shards:05d}.parquet"
        pq.write_table(table, path, compression="zstd", compression_level=9)
        shard_paths.append(path)

    speedups = [row["speedup"] for row in records]
    report = {
        "record_count": len(records),
        "stage_counts": stage_counts,
        "unique_source_identities": len(identities),
        "unique_training_records": len(full_hashes),
        "output_mismatches": len(output_mismatches),
        "missing_speedup": len(missing_speedup),
        "unfenced_answers": len(unfenced_answers),
        "empty_fields": {
            field: sum(not row[field] for row in records)
            for field in ("input", "output", "torch_module", "cuda_code")
        },
        "speedup": {
            "min": min(speedups),
            "max": max(speedups),
            "mean": statistics.fmean(speedups),
            "median": statistics.median(speedups),
        },
        "shards": [
            {"path": str(path.relative_to(output)), "bytes": path.stat().st_size, "sha256": sha256(path)}
            for path in shard_paths
        ],
    }
    (output / "validation_report.json").write_text(
        json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
    )
    print(json.dumps(report, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()