kernel-mcu-c-pool / build_dataset.py
ruthvikanne's picture
Upload folder using huggingface_hub
47bc842 verified
Raw History Blame Contribute Delete
6.75 kB
#!/usr/bin/env python3
"""Full-scale pool builder for the kernel / MCU-OS corpus (Hugging Face dataset layout).
Unlike prep_corpus.py this does NOT cap by token budget or mix weights: it keeps every file that passes the
quality filters and labels it with a `bucket`, so any mix (e.g. 40% mcu / 60% linux, + docs) can be applied at
sampling time. Held-out split = ~2% of directories, hashed (same rule as prep_corpus.py).
Output: $OUT/data/{train,heldout}-NNNNN.parquet, $OUT/stats.json, $OUT/LICENSES.json
"""
import hashlib, json, os, re, shutil, subprocess, sys, time
from collections import Counter, defaultdict
from pathlib import Path
import importlib.util
HERE = Path(__file__).parent
spec = importlib.util.spec_from_file_location("pc", os.environ.get("PREP", str(HERE / "prep_corpus.py")))
pc = importlib.util.module_from_spec(spec); spec.loader.exec_module(pc)
WORK = Path(os.environ.get("WORK", HERE / "work")); SRC = WORK / "src"
OUT = Path(os.environ.get("OUT", HERE / "hf_dataset")); (OUT / "data").mkdir(parents=True, exist_ok=True)
SRC.mkdir(parents=True, exist_ok=True)
ONLY = set(filter(None, os.environ.get("ONLY_REPOS", "").split(",")))
SHARD_ROWS = 4000
# docs: repo -> (url, license, [path prefixes], [extensions])
DOC_SOURCES = {
"linux-doc": ("https://github.com/torvalds/linux", "GPL-2.0", ["Documentation/"], {".rst", ".txt"}),
"zephyr-doc": ("https://github.com/zephyrproject-rtos/zephyr", "Apache-2.0", ["doc/"], {".rst", ".md"}),
"nuttx-doc": ("https://github.com/apache/nuttx", "Apache-2.0", ["Documentation/"], {".rst", ".md"}),
"u-boot-doc": ("https://github.com/u-boot/u-boot", "GPL-2.0", ["doc/"], {".rst", ".txt", ".md"}),
"riscv-isa-manual": ("https://github.com/riscv/riscv-isa-manual", "CC-BY-4.0", ["src/"], {".adoc"}),
"sel4-doc": ("https://github.com/seL4/seL4", "GPL-2.0", ["manual/", "docs/"], {".md", ".rst", ".tex"}),
}
DOC_SKIP = re.compile(r"(/translations/|/devicetree/bindings/|/_build/|/\.|/images/|/generated/)")
def log(*a):
print(time.strftime("%H:%M:%S"), *a, flush=True)
def doc_ok(rel, text):
if DOC_SKIP.search("/" + rel):
return False
n = len(text.encode("utf-8", "ignore"))
if not (500 <= n <= 150_000):
return False
lines = text.splitlines()
if not lines or max(len(l) for l in lines) > 3000:
return False
if sum(ord(c) > 127 for c in text) / len(text) > 0.1:
return False
return True
def main():
rows, failed, lic_seen = [], [], {}
def add(r, lic_file_text=None):
r["n_bytes"] = len(r["text"].encode())
rows.append(r)
# ---- code pool
for name, (url, lic, prefixes) in pc.MCU_REPOS.items():
if ONLY and name not in ONLY:
continue
d, sha = pc.clone(name, url)
if d is None:
failed.append(name); continue
tmp = []
pc.scan(d, prefixes, "mcu", name, lic, sha, tmp)
for r in tmp:
r["repo_license"] = lic; add(r)
log("code", name, len(tmp))
if not ONLY or "linux" in ONLY:
d, sha = pc.clone("linux", pc.LINUX[0])
if d is None:
failed.append("linux")
else:
for bucket, prefixes in pc.LINUX_BUCKETS.items():
tmp = []
pc.scan(d, prefixes, bucket, "linux", pc.LINUX[1], sha, tmp)
for r in tmp:
r["source"] = "/".join(r["path"].split("/")[:3]); r["repo_license"] = pc.LINUX[1]; add(r)
log("code linux", bucket, len(tmp))
# ---- design-doc pool
for key, (url, lic, prefixes, exts) in DOC_SOURCES.items():
if ONLY and key.split("-doc")[0] not in ONLY and "docs" not in ONLY:
continue
repo = key.replace("-doc", "")
d, sha = pc.clone(repo if repo != "riscv-isa-manual" else "riscv-isa-manual", url)
if d is None:
failed.append(key); continue
lf = [p.name for p in d.glob("LICENSE*")] + [p.name for p in d.glob("COPYING*")]
lic_seen[key] = {"declared": lic, "license_files": lf, "commit": sha, "url": url}
n = 0
for p in d.rglob("*"):
if p.suffix not in exts or not p.is_file() or ".git" in p.parts:
continue
rel = p.relative_to(d).as_posix()
if not any(rel.startswith(x) for x in prefixes):
continue
try:
text = p.read_text("utf-8")
except (UnicodeDecodeError, OSError):
continue
if not doc_ok(rel, text):
continue
add({"text": text, "path": f"{key}/{rel}", "bucket": "docs", "source": key, "spdx": lic,
"commit": sha, "def_heavy": False, "repo_license": lic}); n += 1
log("docs", key, n)
log("records before dedup", len(rows))
seen, uniq = set(), []
for r in rows:
h = hashlib.sha1(re.sub(r"\s+", " ", r["text"]).encode()).hexdigest()
if h not in seen:
seen.add(h); uniq.append(r)
log("after exact dedup", len(uniq))
import pyarrow as pa, pyarrow.parquet as pq
splits = {"train": [], "heldout": []}
for r in uniq:
dkey = "/".join(r["path"].split("/")[:5])
splits["heldout" if int(hashlib.md5(dkey.encode()).hexdigest(), 16) % pc.HELDOUT_MOD == 0 else "train"].append(r)
cols = ["text", "path", "bucket", "source", "spdx", "repo_license", "commit", "def_heavy", "n_bytes"]
stats = {"failed": failed, "bytes_per_token_assumed": 3.6}
for name, rs in splits.items():
for i in range(0, len(rs), SHARD_ROWS):
chunk = rs[i:i + SHARD_ROWS]
pq.write_table(pa.table({c: [x[c] for x in chunk] for c in cols}),
OUT / "data" / f"{name}-{i // SHARD_ROWS:05d}.parquet", compression="zstd")
tot, cnt, lic, dh = Counter(), Counter(), Counter(), Counter()
for x in rs:
tot[x["bucket"]] += x["n_bytes"]; cnt[x["bucket"]] += 1; lic[x["spdx"]] += 1
if x["def_heavy"]:
dh[x["bucket"]] += x["n_bytes"]
stats[name] = {"files": dict(cnt), "est_tokens_M": {k: round(v / 3.6 / 1e6, 2) for k, v in tot.items()},
"est_tokens_total_M": round(sum(tot.values()) / 3.6 / 1e6, 2),
"def_heavy_est_tokens_M": {k: round(v / 3.6 / 1e6, 2) for k, v in dh.items()},
"top_spdx": lic.most_common(15)}
(OUT / "stats.json").write_text(json.dumps(stats, indent=1))
(OUT / "LICENSES.json").write_text(json.dumps(lic_seen, indent=1))
print("DATASET_STATS=" + json.dumps(stats))
if os.environ.get("CLEAN_SRC", "1") == "1":
shutil.rmtree(SRC, ignore_errors=True)
if __name__ == "__main__":
main()