Datasets:
Download scripts/build_dataset.py from kcxain/KernelZero-CUDA-SFT: direct link, hf CLI and curl.
- Browser
- Download file 8.28 kB
-
https://huggingface.co/datasets/kcxain/KernelZero-CUDA-SFT/resolve/main/scripts/build_dataset.py
- Command line
-
hf download hf://datasets/kcxain/KernelZero-CUDA-SFT/scripts/build_dataset.py
-
curl -L -o build_dataset.py https://huggingface.co/datasets/kcxain/KernelZero-CUDA-SFT/resolve/main/scripts/build_dataset.py
8.28 kB
| #!/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() | |