ruthvikanne commited on
Commit
47bc842
·
verified ·
1 Parent(s): 046cd3b

Upload folder using huggingface_hub

Browse files
LICENSES.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "linux-doc": {
3
+ "declared": "GPL-2.0",
4
+ "license_files": [
5
+ "LICENSES",
6
+ "COPYING"
7
+ ],
8
+ "commit": "c339f4010dea8b0d754f84ace70cd1b089878ef8",
9
+ "url": "https://github.com/torvalds/linux"
10
+ },
11
+ "zephyr-doc": {
12
+ "declared": "Apache-2.0",
13
+ "license_files": [
14
+ "LICENSE",
15
+ "LICENSES"
16
+ ],
17
+ "commit": "5d2ed837a8c996b60a7d2b76cab0e3f9e98efbdc",
18
+ "url": "https://github.com/zephyrproject-rtos/zephyr"
19
+ },
20
+ "nuttx-doc": {
21
+ "declared": "Apache-2.0",
22
+ "license_files": [
23
+ "LICENSE"
24
+ ],
25
+ "commit": "b029862b3e10ae19620632acf296cdf3da6302ce",
26
+ "url": "https://github.com/apache/nuttx"
27
+ },
28
+ "u-boot-doc": {
29
+ "declared": "GPL-2.0",
30
+ "license_files": [
31
+ "COPYING"
32
+ ],
33
+ "commit": "03e45557e1f38a39a0c80fe30483130ff376cf92",
34
+ "url": "https://github.com/u-boot/u-boot"
35
+ },
36
+ "riscv-isa-manual": {
37
+ "declared": "CC-BY-4.0",
38
+ "license_files": [
39
+ "LICENSE"
40
+ ],
41
+ "commit": "e17d92a1cbc06d5281d483eed670a010c27aa26c",
42
+ "url": "https://github.com/riscv/riscv-isa-manual"
43
+ },
44
+ "sel4-doc": {
45
+ "declared": "GPL-2.0",
46
+ "license_files": [
47
+ "LICENSE.md",
48
+ "LICENSES"
49
+ ],
50
+ "commit": "97bd522e831086fbc68dbc0fef0ab0eefc710eae",
51
+ "url": "https://github.com/seL4/seL4"
52
+ }
53
+ }
README.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: [en]
3
+ pretty_name: Kernel and MCU-OS C pool (code + design docs)
4
+ task_categories: [text-generation]
5
+ tags: [code, c, linux-kernel, rtos, embedded, domain-adaptation]
6
+ configs:
7
+ - config_name: default
8
+ data_files:
9
+ - {split: train, path: "data/train-*.parquet"}
10
+ - {split: heldout, path: "data/heldout-*.parquet"}
11
+ ---
12
+ # Kernel and MCU-OS C pool
13
+
14
+ Unmixed pool of C/assembly source and design documentation for domain-adaptive training of a kernel-level coding model.
15
+ Apply the mix at sampling time using the `bucket` column.
16
+
17
+ | bucket | content | est. tokens (train) |
18
+ |---|---|---|
19
+ | mcu | FreeRTOS, Zephyr, NuttX, RIOT, CMSIS, xv6, Contiki-NG, RT-Thread, U-Boot, OpenSBI, seL4, libopencm3 | ~116.5M |
20
+ | linux_gpu | drivers/gpu, video, accel | ~25.3M |
21
+ | linux_cpu | arch/*, cpufreq, cpuidle, irqchip, clocksource, perf, firmware | ~7.7M |
22
+ | linux_core | kernel, mm, fs, net, block, pci, usb, dma, include/linux ... | ~45.2M |
23
+ | docs | Linux Documentation/, Zephyr doc/, NuttX Documentation/, U-Boot doc/, RISC-V ISA manual, seL4 docs | ~14.4M |
24
+
25
+ Token counts are byte-based estimates (3.6 bytes/token), not tokenizer counts.
26
+
27
+ ## Columns
28
+ `text`, `path`, `bucket`, `source`, `spdx` (per-file SPDX tag if present, else the repository licence), `repo_license`, `commit` (upstream commit the file came from), `def_heavy` (file is >60% `#define` lines, typically register headers; consider down-sampling), `n_bytes`.
29
+
30
+ ## Splits
31
+ `heldout` holds about 2% of directories (hash of the first 5 path components), so no directory appears in both splits.
32
+ Caution: heldout is skewed toward `mcu` (about 19 percent of files in the pool but most of heldout tokens); evaluate per bucket.
33
+
34
+ ## Filters
35
+ Exact dedup (whitespace-normalised SHA-1 only; no near-duplicate removal), 300 B to 120 KB per code file (500 B to 150 KB for docs), generated-file and hex-table filters, test/sample/scripts/dts/board paths skipped for code, non-ASCII ratio limits.
36
+
37
+ ## Licences (read before use)
38
+ Content keeps its upstream licences, mostly GPL-2.0 variants (Linux, U-Boot, seL4), Apache-2.0 (Zephyr, NuttX, RT-Thread, CMSIS), MIT, BSD, LGPL, and CC-BY-4.0 (RISC-V ISA manual). Per-file SPDX tags are preserved in `spdx`; see `LICENSES.json` for the upstream commit and licence files per documentation source.
39
+ Whether training on GPL code makes a model a derivative work is legally unsettled. This dataset does not resolve that; you are responsible for your use and for the licence terms when redistributing the data or derived weights.
40
+
41
+ ## Not included
42
+ Commercial textbooks. Open-licensed books (e.g. LDD3, Mastering the FreeRTOS Real Time Kernel) are not yet added; their licences must be verified at source first.
build_dataset.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Full-scale pool builder for the kernel / MCU-OS corpus (Hugging Face dataset layout).
3
+
4
+ Unlike prep_corpus.py this does NOT cap by token budget or mix weights: it keeps every file that passes the
5
+ quality filters and labels it with a `bucket`, so any mix (e.g. 40% mcu / 60% linux, + docs) can be applied at
6
+ sampling time. Held-out split = ~2% of directories, hashed (same rule as prep_corpus.py).
7
+ Output: $OUT/data/{train,heldout}-NNNNN.parquet, $OUT/stats.json, $OUT/LICENSES.json
8
+ """
9
+ import hashlib, json, os, re, shutil, subprocess, sys, time
10
+ from collections import Counter, defaultdict
11
+ from pathlib import Path
12
+ import importlib.util
13
+
14
+ HERE = Path(__file__).parent
15
+ spec = importlib.util.spec_from_file_location("pc", os.environ.get("PREP", str(HERE / "prep_corpus.py")))
16
+ pc = importlib.util.module_from_spec(spec); spec.loader.exec_module(pc)
17
+
18
+ WORK = Path(os.environ.get("WORK", HERE / "work")); SRC = WORK / "src"
19
+ OUT = Path(os.environ.get("OUT", HERE / "hf_dataset")); (OUT / "data").mkdir(parents=True, exist_ok=True)
20
+ SRC.mkdir(parents=True, exist_ok=True)
21
+ ONLY = set(filter(None, os.environ.get("ONLY_REPOS", "").split(",")))
22
+ SHARD_ROWS = 4000
23
+
24
+ # docs: repo -> (url, license, [path prefixes], [extensions])
25
+ DOC_SOURCES = {
26
+ "linux-doc": ("https://github.com/torvalds/linux", "GPL-2.0", ["Documentation/"], {".rst", ".txt"}),
27
+ "zephyr-doc": ("https://github.com/zephyrproject-rtos/zephyr", "Apache-2.0", ["doc/"], {".rst", ".md"}),
28
+ "nuttx-doc": ("https://github.com/apache/nuttx", "Apache-2.0", ["Documentation/"], {".rst", ".md"}),
29
+ "u-boot-doc": ("https://github.com/u-boot/u-boot", "GPL-2.0", ["doc/"], {".rst", ".txt", ".md"}),
30
+ "riscv-isa-manual": ("https://github.com/riscv/riscv-isa-manual", "CC-BY-4.0", ["src/"], {".adoc"}),
31
+ "sel4-doc": ("https://github.com/seL4/seL4", "GPL-2.0", ["manual/", "docs/"], {".md", ".rst", ".tex"}),
32
+ }
33
+ DOC_SKIP = re.compile(r"(/translations/|/devicetree/bindings/|/_build/|/\.|/images/|/generated/)")
34
+
35
+
36
+ def log(*a):
37
+ print(time.strftime("%H:%M:%S"), *a, flush=True)
38
+
39
+
40
+ def doc_ok(rel, text):
41
+ if DOC_SKIP.search("/" + rel):
42
+ return False
43
+ n = len(text.encode("utf-8", "ignore"))
44
+ if not (500 <= n <= 150_000):
45
+ return False
46
+ lines = text.splitlines()
47
+ if not lines or max(len(l) for l in lines) > 3000:
48
+ return False
49
+ if sum(ord(c) > 127 for c in text) / len(text) > 0.1:
50
+ return False
51
+ return True
52
+
53
+
54
+ def main():
55
+ rows, failed, lic_seen = [], [], {}
56
+
57
+ def add(r, lic_file_text=None):
58
+ r["n_bytes"] = len(r["text"].encode())
59
+ rows.append(r)
60
+
61
+ # ---- code pool
62
+ for name, (url, lic, prefixes) in pc.MCU_REPOS.items():
63
+ if ONLY and name not in ONLY:
64
+ continue
65
+ d, sha = pc.clone(name, url)
66
+ if d is None:
67
+ failed.append(name); continue
68
+ tmp = []
69
+ pc.scan(d, prefixes, "mcu", name, lic, sha, tmp)
70
+ for r in tmp:
71
+ r["repo_license"] = lic; add(r)
72
+ log("code", name, len(tmp))
73
+ if not ONLY or "linux" in ONLY:
74
+ d, sha = pc.clone("linux", pc.LINUX[0])
75
+ if d is None:
76
+ failed.append("linux")
77
+ else:
78
+ for bucket, prefixes in pc.LINUX_BUCKETS.items():
79
+ tmp = []
80
+ pc.scan(d, prefixes, bucket, "linux", pc.LINUX[1], sha, tmp)
81
+ for r in tmp:
82
+ r["source"] = "/".join(r["path"].split("/")[:3]); r["repo_license"] = pc.LINUX[1]; add(r)
83
+ log("code linux", bucket, len(tmp))
84
+
85
+ # ---- design-doc pool
86
+ for key, (url, lic, prefixes, exts) in DOC_SOURCES.items():
87
+ if ONLY and key.split("-doc")[0] not in ONLY and "docs" not in ONLY:
88
+ continue
89
+ repo = key.replace("-doc", "")
90
+ d, sha = pc.clone(repo if repo != "riscv-isa-manual" else "riscv-isa-manual", url)
91
+ if d is None:
92
+ failed.append(key); continue
93
+ lf = [p.name for p in d.glob("LICENSE*")] + [p.name for p in d.glob("COPYING*")]
94
+ lic_seen[key] = {"declared": lic, "license_files": lf, "commit": sha, "url": url}
95
+ n = 0
96
+ for p in d.rglob("*"):
97
+ if p.suffix not in exts or not p.is_file() or ".git" in p.parts:
98
+ continue
99
+ rel = p.relative_to(d).as_posix()
100
+ if not any(rel.startswith(x) for x in prefixes):
101
+ continue
102
+ try:
103
+ text = p.read_text("utf-8")
104
+ except (UnicodeDecodeError, OSError):
105
+ continue
106
+ if not doc_ok(rel, text):
107
+ continue
108
+ add({"text": text, "path": f"{key}/{rel}", "bucket": "docs", "source": key, "spdx": lic,
109
+ "commit": sha, "def_heavy": False, "repo_license": lic}); n += 1
110
+ log("docs", key, n)
111
+
112
+ log("records before dedup", len(rows))
113
+ seen, uniq = set(), []
114
+ for r in rows:
115
+ h = hashlib.sha1(re.sub(r"\s+", " ", r["text"]).encode()).hexdigest()
116
+ if h not in seen:
117
+ seen.add(h); uniq.append(r)
118
+ log("after exact dedup", len(uniq))
119
+
120
+ import pyarrow as pa, pyarrow.parquet as pq
121
+ splits = {"train": [], "heldout": []}
122
+ for r in uniq:
123
+ dkey = "/".join(r["path"].split("/")[:5])
124
+ splits["heldout" if int(hashlib.md5(dkey.encode()).hexdigest(), 16) % pc.HELDOUT_MOD == 0 else "train"].append(r)
125
+ cols = ["text", "path", "bucket", "source", "spdx", "repo_license", "commit", "def_heavy", "n_bytes"]
126
+ stats = {"failed": failed, "bytes_per_token_assumed": 3.6}
127
+ for name, rs in splits.items():
128
+ for i in range(0, len(rs), SHARD_ROWS):
129
+ chunk = rs[i:i + SHARD_ROWS]
130
+ pq.write_table(pa.table({c: [x[c] for x in chunk] for c in cols}),
131
+ OUT / "data" / f"{name}-{i // SHARD_ROWS:05d}.parquet", compression="zstd")
132
+ tot, cnt, lic, dh = Counter(), Counter(), Counter(), Counter()
133
+ for x in rs:
134
+ tot[x["bucket"]] += x["n_bytes"]; cnt[x["bucket"]] += 1; lic[x["spdx"]] += 1
135
+ if x["def_heavy"]:
136
+ dh[x["bucket"]] += x["n_bytes"]
137
+ stats[name] = {"files": dict(cnt), "est_tokens_M": {k: round(v / 3.6 / 1e6, 2) for k, v in tot.items()},
138
+ "est_tokens_total_M": round(sum(tot.values()) / 3.6 / 1e6, 2),
139
+ "def_heavy_est_tokens_M": {k: round(v / 3.6 / 1e6, 2) for k, v in dh.items()},
140
+ "top_spdx": lic.most_common(15)}
141
+ (OUT / "stats.json").write_text(json.dumps(stats, indent=1))
142
+ (OUT / "LICENSES.json").write_text(json.dumps(lic_seen, indent=1))
143
+ print("DATASET_STATS=" + json.dumps(stats))
144
+ if os.environ.get("CLEAN_SRC", "1") == "1":
145
+ shutil.rmtree(SRC, ignore_errors=True)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()
data/heldout-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3975bbcf3022d3ba9a42b70ccf2bd44e6a4f2c60ef2e53776a53311778e6dc33
3
+ size 3852026
data/train-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af6f6e23f533d77c71a873e89e7d6d5729fa1fabff6b4b526d99e07c75c29bbb
3
+ size 5295762
data/train-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f3bcd093bae79b80d35ac5ddb50acb56a64261437731d3ecf35317d91b17680
3
+ size 9839278
data/train-00002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:435e0495dacb301bba405f5c15fa23947d5a1d912a11caf04d6ce54f51988fe3
3
+ size 9239549
data/train-00003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f8490e607315c5e0d2e6c2dfe194171489474fe02735e5a80adf45529bbd874
3
+ size 8971431
data/train-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26c4aad0ef56c1b810bc24bf2f4b8e56e3e9fb1f1f53d3ec0d33fa5d0b4a8a45
3
+ size 8872075
data/train-00005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4af9ec72c53b22d05c26a740007fc4a8eb1571be06e95ab7e6eee482aeb6ca94
3
+ size 5446032
data/train-00006.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:667e54629ca1a5a465055117b67fb120a870c74fd332c85dec899e4e0bb421f3
3
+ size 6365114
data/train-00007.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a6547f3168a33a590ec24d5001d54bb64dfb2dadcb5ee28ea4a5d81749e12e3
3
+ size 6491067
data/train-00008.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82872a1b5e942c189db206e7410529f1080a2862cc3c082e58bdd9c941d84b1f
3
+ size 10479589
data/train-00009.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd553472fe38b31c3cfd6439375989374a9b7b9db20057ef253d902a0b20d8b4
3
+ size 5191617
data/train-00010.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7cbeab947d10022093a3fe6c2f1922e1543b5cd1fa702c233a1735fc3125b148
3
+ size 9918393
data/train-00011.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:231a8060de37510ea1145dda3749f024d8defe2685cfcbc77a491c334dfb6e71
3
+ size 9574404
data/train-00012.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc0cf6463e0ce17f59c2dd072eb90ab1c25b1b53e1ecd88c7065a10720aa408f
3
+ size 8460866
data/train-00013.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b0ff3d654839ea8ae324feb6967a311031ce426e2e012fe9d3c8a795e8c5e86
3
+ size 10423160
data/train-00014.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34258fbeaf2586528317a414a3bb0021a4ae00e10ea5a2a73c90cd429cc88239
3
+ size 20006791
data/train-00015.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b529786ae4b2b35d6895dec217473712134c7eb641f8568a33729a7f0375f5ad
3
+ size 16702072
data/train-00016.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5246b1ec0619b59916adb1eb8e27672f686f4d303c620cf33f52f7c5ffe4651
3
+ size 10999676
data/train-00017.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a7036ac8f6b6ac915cd1dfac312f816d40b376fc28eb06ae068328ff98c464d
3
+ size 1934739
prep_corpus.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Stage 0 - build the kernel / MCU-OS C corpus. CPU only (spends no GPU quota).
3
+
4
+ Mix (by estimated tokens, configurable):
5
+ 40% mcu RTOS / microcontroller OS / firmware / bootloader code
6
+ 20% linux_gpu drivers/gpu, video, accel
7
+ 15% linux_cpu arch/*, cpufreq, cpuidle, irqchip, clocksource, perf, firmware
8
+ 25% linux_core kernel, mm, fs, net, block, pci, usb, dma, include/linux, ...
9
+ Outputs (in $WORK/corpus): train.jsonl, heldout.jsonl, stats.json
10
+ Known gaps: no near-duplicate removal (exact dedup only); token counts are
11
+ byte-based estimates until the real tokenizer is applied in the next stage.
12
+ """
13
+ import hashlib, json, os, random, re, shutil, subprocess, sys, time
14
+ from collections import Counter, defaultdict
15
+ from pathlib import Path
16
+
17
+ WORK = Path(os.environ.get("WORK", "/kaggle/working"))
18
+ SRC, OUT = WORK / "src", WORK / "corpus"
19
+ TOKEN_BUDGET = int(os.environ.get("TOKEN_BUDGET", 40_000_000))
20
+ BYTES_PER_TOKEN = float(os.environ.get("BYTES_PER_TOKEN", 3.6)) # rough, C code
21
+ ONLY = set(filter(None, os.environ.get("ONLY_REPOS", "").split(","))) # for tests
22
+ SEED = 1234
23
+ MAX_FILE_BYTES, MIN_FILE_BYTES = 120_000, 300
24
+ HELDOUT_MOD = 50 # ~2% of directories held out entirely
25
+ SHARE_CAP = 0.35 # no single source may exceed this share of its bucket
26
+
27
+ WEIGHTS = {"mcu": 0.40, "linux_gpu": 0.20, "linux_cpu": 0.15, "linux_core": 0.25}
28
+
29
+ # name: (url, license_hint, include_prefixes or None for all)
30
+ MCU_REPOS = {
31
+ "freertos": ("https://github.com/FreeRTOS/FreeRTOS-Kernel", "MIT", None),
32
+ "zephyr": ("https://github.com/zephyrproject-rtos/zephyr", "Apache-2.0",
33
+ ["kernel/", "arch/", "drivers/", "soc/", "lib/", "include/", "subsys/"]),
34
+ "nuttx": ("https://github.com/apache/nuttx", "Apache-2.0",
35
+ ["sched/", "arch/", "drivers/", "mm/", "fs/", "libs/", "include/"]),
36
+ "riot": ("https://github.com/RIOT-OS/RIOT", "LGPL-2.1", ["core/", "cpu/", "drivers/", "sys/"]),
37
+ "cmsis": ("https://github.com/ARM-software/CMSIS_6", "Apache-2.0", None),
38
+ "xv6": ("https://github.com/mit-pdos/xv6-public", "MIT", None),
39
+ "contiki-ng": ("https://github.com/contiki-ng/contiki-ng", "BSD-3-Clause", ["os/", "arch/"]),
40
+ "rt-thread": ("https://github.com/RT-Thread/rt-thread", "Apache-2.0",
41
+ ["src/", "libcpu/", "components/drivers/"]),
42
+ "u-boot": ("https://github.com/u-boot/u-boot", "GPL-2.0", ["arch/", "drivers/", "common/", "lib/", "cmd/"]),
43
+ "opensbi": ("https://github.com/riscv-software-src/opensbi", "BSD-2-Clause", None),
44
+ "sel4": ("https://github.com/seL4/seL4", "GPL-2.0", ["src/", "include/", "libsel4/"]),
45
+ "libopencm3": ("https://github.com/libopencm3/libopencm3", "LGPL-3.0", None),
46
+ }
47
+ LINUX = ("https://github.com/torvalds/linux", "GPL-2.0")
48
+ LINUX_BUCKETS = {
49
+ "linux_gpu": ["drivers/gpu/", "drivers/video/", "drivers/accel/"],
50
+ "linux_cpu": ["arch/x86/", "arch/arm64/", "arch/riscv/", "arch/arm/", "drivers/cpufreq/",
51
+ "drivers/cpuidle/", "drivers/irqchip/", "drivers/clocksource/", "drivers/perf/",
52
+ "drivers/firmware/"],
53
+ "linux_core": ["kernel/", "mm/", "fs/", "net/", "block/", "ipc/", "lib/", "security/", "crypto/",
54
+ "init/", "include/linux/", "drivers/pci/", "drivers/usb/", "drivers/nvme/",
55
+ "drivers/base/", "drivers/dma/", "drivers/iommu/", "drivers/virtio/",
56
+ "drivers/tty/", "drivers/char/", "drivers/md/", "drivers/scsi/"],
57
+ }
58
+ EXTS = {".c", ".h", ".S", ".s"}
59
+ SKIP_PATH = re.compile(
60
+ r"(_sh_mask\.h$|_offset\.h$|/asic_reg/|/firmware/.*\.(c|h)$|/(test|tests|selftests|Documentation|"
61
+ r"samples|tools|scripts|third_party|ThirdParty|examples)/|\.dtsi?$|/bsp/|/boards/|/dts/)")
62
+ GENERATED = re.compile(r"(auto-?generated|do not edit|generated by|this file is generated)", re.I)
63
+ HEXROW = re.compile(r"^\s*(0x[0-9a-fA-F]+\s*,?\s*)+$")
64
+ SPDX = re.compile(r"SPDX-License-Identifier:\s*([^\n*]+?)\s*(?:\*/)?\s*$", re.M)
65
+
66
+
67
+ def sh(cmd, cwd=None, tries=3):
68
+ for i in range(tries):
69
+ r = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True)
70
+ if r.returncode == 0:
71
+ return r.stdout.strip()
72
+ print(f" retry {i+1}: {r.stderr.strip()[:200]}", flush=True)
73
+ time.sleep(3)
74
+ return None
75
+
76
+
77
+ def clone(name, url):
78
+ dst = SRC / name
79
+ if not dst.exists():
80
+ print(f"cloning {name}", flush=True)
81
+ if sh(f"git clone --depth 1 --quiet {url} {dst}") is None:
82
+ return None, None
83
+ return dst, sh("git rev-parse HEAD", cwd=dst)
84
+
85
+
86
+ def define_ratio(text):
87
+ lines = [l for l in text.splitlines() if l.strip()]
88
+ return sum(l.lstrip().startswith("#define") for l in lines) / max(1, len(lines))
89
+
90
+
91
+ def accept(rel, text):
92
+ if SKIP_PATH.search("/" + rel):
93
+ return False
94
+ n = len(text.encode("utf-8", "ignore"))
95
+ if not (MIN_FILE_BYTES <= n <= MAX_FILE_BYTES):
96
+ return False
97
+ if GENERATED.search(text[:1500]):
98
+ return False
99
+ lines = text.splitlines()
100
+ if not lines or max(len(l) for l in lines) > 2000:
101
+ return False
102
+ if sum(bool(HEXROW.match(l)) for l in lines) / len(lines) > 0.4:
103
+ return False
104
+ if sum(ord(c) > 127 for c in text) / len(text) > 0.05:
105
+ return False
106
+ return True
107
+
108
+
109
+ def scan(root, prefixes, bucket, source, lic_hint, sha, out):
110
+ for p in root.rglob("*"):
111
+ if p.suffix not in EXTS or not p.is_file() or ".git" in p.parts:
112
+ continue
113
+ rel = p.relative_to(root).as_posix()
114
+ if prefixes and not any(rel.startswith(x) for x in prefixes):
115
+ continue
116
+ try:
117
+ text = p.read_text("utf-8")
118
+ except (UnicodeDecodeError, OSError):
119
+ continue
120
+ if not accept(rel, text):
121
+ continue
122
+ m = SPDX.search(text[:600])
123
+ out.append({"text": text, "path": f"{source}/{rel}", "bucket": bucket, "source": source,
124
+ "spdx": (m.group(1) if m else lic_hint), "commit": sha,
125
+ "def_heavy": define_ratio(text) > 0.6})
126
+
127
+
128
+ def main():
129
+ random.seed(SEED)
130
+ SRC.mkdir(parents=True, exist_ok=True)
131
+ OUT.mkdir(parents=True, exist_ok=True)
132
+ cands, failed = [], []
133
+ for name, (url, lic, prefixes) in MCU_REPOS.items():
134
+ if ONLY and name not in ONLY:
135
+ continue
136
+ d, sha = clone(name, url)
137
+ if d is None:
138
+ failed.append(name); continue
139
+ scan(d, prefixes, "mcu", name, lic, sha, cands)
140
+ if not ONLY or "linux" in ONLY:
141
+ d, sha = clone("linux", LINUX[0])
142
+ if d is None:
143
+ failed.append("linux")
144
+ else:
145
+ for bucket, prefixes in LINUX_BUCKETS.items():
146
+ # source = first two path components so GPU/arch/etc. are balanced
147
+ tmp = []
148
+ scan(d, prefixes, bucket, "linux", LINUX[1], sha, tmp)
149
+ for r in tmp:
150
+ parts = r["path"].split("/")
151
+ r["source"] = "/".join(parts[:3])
152
+ cands.extend(tmp)
153
+ print(f"candidates before dedup: {len(cands)}", flush=True)
154
+
155
+ seen, uniq = set(), []
156
+ for r in cands:
157
+ h = hashlib.sha1(re.sub(r"\s+", " ", r["text"]).encode()).hexdigest()
158
+ if h not in seen:
159
+ seen.add(h); uniq.append(r)
160
+ print(f"after exact dedup: {len(uniq)}", flush=True)
161
+
162
+ train, held = [], []
163
+ by_bucket = defaultdict(lambda: defaultdict(list))
164
+ for r in uniq:
165
+ d = "/".join(r["path"].split("/")[:5])
166
+ if int(hashlib.md5(d.encode()).hexdigest(), 16) % HELDOUT_MOD == 0:
167
+ held.append(r)
168
+ else:
169
+ by_bucket[r["bucket"]][r["source"]].append(r)
170
+
171
+ for bucket, srcs in by_bucket.items():
172
+ budget = TOKEN_BUDGET * WEIGHTS[bucket] * BYTES_PER_TOKEN
173
+ # #define-heavy register headers: keep only ~15% so they don't dominate
174
+ for k in srcs:
175
+ srcs[k] = [r for r in srcs[k] if not r["def_heavy"] or random.random() < 0.15]
176
+ random.shuffle(srcs[k])
177
+ used, per = 0, Counter()
178
+ queues = {k: v for k, v in srcs.items() if v}
179
+ while queues and used < budget:
180
+ for k in list(queues):
181
+ if per[k] > SHARE_CAP * budget:
182
+ del queues[k]; continue
183
+ r = queues[k].pop()
184
+ b = len(r["text"].encode())
185
+ train.append(r); used += b; per[k] += b
186
+ if not queues[k]:
187
+ del queues[k]
188
+ if used >= budget:
189
+ break
190
+ print(f"{bucket}: {used/BYTES_PER_TOKEN/1e6:.1f}M est. tokens "
191
+ f"(target {TOKEN_BUDGET*WEIGHTS[bucket]/1e6:.1f}M)", flush=True)
192
+
193
+ random.shuffle(train)
194
+ for name, rows in (("train", train), ("heldout", held)):
195
+ with open(OUT / f"{name}.jsonl", "w") as f:
196
+ for r in rows:
197
+ r = {k: v for k, v in r.items() if k != "def_heavy"}
198
+ f.write(json.dumps(r) + "\n")
199
+ stats = {"failed_repos": failed, "budget_tokens": TOKEN_BUDGET, "bytes_per_token_assumed": BYTES_PER_TOKEN}
200
+ for name, rows in (("train", train), ("heldout", held)):
201
+ tot = Counter(); n = Counter(); lic = Counter()
202
+ for r in rows:
203
+ tot[r["bucket"]] += len(r["text"].encode()); n[r["bucket"]] += 1; lic[r["spdx"]] += 1
204
+ s = sum(tot.values()) or 1
205
+ stats[name] = {"files": dict(n), "est_tokens_M": {k: round(v / BYTES_PER_TOKEN / 1e6, 2) for k, v in tot.items()},
206
+ "share": {k: round(v / s, 3) for k, v in tot.items()},
207
+ "top_licenses": lic.most_common(12)}
208
+ (OUT / "stats.json").write_text(json.dumps(stats, indent=2))
209
+ print(json.dumps(stats, indent=2))
210
+ if os.environ.get("CLEAN_SRC", "1") == "1":
211
+ shutil.rmtree(SRC, ignore_errors=True) # keep notebook output small
212
+
213
+
214
+ if __name__ == "__main__":
215
+ main()
stats.json ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "failed": [],
3
+ "bytes_per_token_assumed": 3.6,
4
+ "train": {
5
+ "files": {
6
+ "mcu": 40849,
7
+ "linux_gpu": 7409,
8
+ "linux_cpu": 3758,
9
+ "linux_core": 11042,
10
+ "docs": 5917
11
+ },
12
+ "est_tokens_M": {
13
+ "mcu": 116.51,
14
+ "linux_gpu": 25.31,
15
+ "linux_cpu": 7.69,
16
+ "linux_core": 45.18,
17
+ "docs": 14.36
18
+ },
19
+ "est_tokens_total_M": 209.06,
20
+ "def_heavy_est_tokens_M": {
21
+ "mcu": 13.9,
22
+ "linux_gpu": 0.92,
23
+ "linux_cpu": 0.22,
24
+ "linux_core": 0.75
25
+ },
26
+ "top_spdx": [
27
+ [
28
+ "Apache-2.0",
29
+ 26976
30
+ ],
31
+ [
32
+ "GPL-2.0",
33
+ 16361
34
+ ],
35
+ [
36
+ "GPL-2.0-only",
37
+ 6082
38
+ ],
39
+ [
40
+ "GPL-2.0+",
41
+ 5291
42
+ ],
43
+ [
44
+ "LGPL-2.1-only",
45
+ 3038
46
+ ],
47
+ [
48
+ "GPL-2.0-or-later",
49
+ 2693
50
+ ],
51
+ [
52
+ "MIT",
53
+ 2674
54
+ ],
55
+ [
56
+ "BSD-3-Clause",
57
+ 2051
58
+ ],
59
+ [
60
+ "LGPL-3.0",
61
+ 973
62
+ ],
63
+ [
64
+ "LGPL-2.1",
65
+ 751
66
+ ],
67
+ [
68
+ "BSD-2-Clause",
69
+ 476
70
+ ],
71
+ [
72
+ "Apache-2.0 OR GPL-2.0-or-later",
73
+ 287
74
+ ],
75
+ [
76
+ "GPL-2.0 OR MIT",
77
+ 209
78
+ ],
79
+ [
80
+ "CC-BY-4.0",
81
+ 123
82
+ ],
83
+ [
84
+ "GPL-2.0+ OR BSD-3-Clause",
85
+ 119
86
+ ]
87
+ ]
88
+ },
89
+ "heldout": {
90
+ "files": {
91
+ "mcu": 885,
92
+ "linux_gpu": 54,
93
+ "linux_cpu": 74,
94
+ "linux_core": 241,
95
+ "docs": 204
96
+ },
97
+ "est_tokens_M": {
98
+ "mcu": 2.93,
99
+ "linux_gpu": 0.15,
100
+ "linux_cpu": 0.29,
101
+ "linux_core": 0.9,
102
+ "docs": 0.45
103
+ },
104
+ "est_tokens_total_M": 4.72,
105
+ "def_heavy_est_tokens_M": {
106
+ "mcu": 0.41,
107
+ "linux_cpu": 0.0,
108
+ "linux_core": 0.01
109
+ },
110
+ "top_spdx": [
111
+ [
112
+ "Apache-2.0",
113
+ 681
114
+ ],
115
+ [
116
+ "GPL-2.0",
117
+ 315
118
+ ],
119
+ [
120
+ "BSD-3-Clause",
121
+ 116
122
+ ],
123
+ [
124
+ "GPL-2.0+",
125
+ 103
126
+ ],
127
+ [
128
+ "GPL-2.0-only",
129
+ 92
130
+ ],
131
+ [
132
+ "LGPL-2.1-only",
133
+ 65
134
+ ],
135
+ [
136
+ "GPL-2.0-or-later",
137
+ 44
138
+ ],
139
+ [
140
+ "MIT",
141
+ 11
142
+ ],
143
+ [
144
+ "BSD-2-Clause",
145
+ 9
146
+ ],
147
+ [
148
+ "LGPL-3.0",
149
+ 6
150
+ ],
151
+ [
152
+ "GPL-2.0+ OR BSD-3-Clause",
153
+ 3
154
+ ],
155
+ [
156
+ "GPL-2.0 OR MIT",
157
+ 3
158
+ ],
159
+ [
160
+ "LGPL-2.1",
161
+ 2
162
+ ],
163
+ [
164
+ "CC-BY-4.0",
165
+ 2
166
+ ],
167
+ [
168
+ "OAR",
169
+ 1
170
+ ]
171
+ ]
172
+ }
173
+ }