File size: 9,829 Bytes
47bc842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Stage 0 - build the kernel / MCU-OS C corpus. CPU only (spends no GPU quota).

Mix (by estimated tokens, configurable):
  40% mcu          RTOS / microcontroller OS / firmware / bootloader code
  20% linux_gpu    drivers/gpu, video, accel
  15% linux_cpu    arch/*, cpufreq, cpuidle, irqchip, clocksource, perf, firmware
  25% linux_core   kernel, mm, fs, net, block, pci, usb, dma, include/linux, ...
Outputs (in $WORK/corpus): train.jsonl, heldout.jsonl, stats.json
Known gaps: no near-duplicate removal (exact dedup only); token counts are
byte-based estimates until the real tokenizer is applied in the next stage.
"""
import hashlib, json, os, random, re, shutil, subprocess, sys, time
from collections import Counter, defaultdict
from pathlib import Path

WORK = Path(os.environ.get("WORK", "/kaggle/working"))
SRC, OUT = WORK / "src", WORK / "corpus"
TOKEN_BUDGET = int(os.environ.get("TOKEN_BUDGET", 40_000_000))
BYTES_PER_TOKEN = float(os.environ.get("BYTES_PER_TOKEN", 3.6))  # rough, C code
ONLY = set(filter(None, os.environ.get("ONLY_REPOS", "").split(",")))  # for tests
SEED = 1234
MAX_FILE_BYTES, MIN_FILE_BYTES = 120_000, 300
HELDOUT_MOD = 50  # ~2% of directories held out entirely
SHARE_CAP = 0.35  # no single source may exceed this share of its bucket

WEIGHTS = {"mcu": 0.40, "linux_gpu": 0.20, "linux_cpu": 0.15, "linux_core": 0.25}

# name: (url, license_hint, include_prefixes or None for all)
MCU_REPOS = {
    "freertos": ("https://github.com/FreeRTOS/FreeRTOS-Kernel", "MIT", None),
    "zephyr": ("https://github.com/zephyrproject-rtos/zephyr", "Apache-2.0",
               ["kernel/", "arch/", "drivers/", "soc/", "lib/", "include/", "subsys/"]),
    "nuttx": ("https://github.com/apache/nuttx", "Apache-2.0",
              ["sched/", "arch/", "drivers/", "mm/", "fs/", "libs/", "include/"]),
    "riot": ("https://github.com/RIOT-OS/RIOT", "LGPL-2.1", ["core/", "cpu/", "drivers/", "sys/"]),
    "cmsis": ("https://github.com/ARM-software/CMSIS_6", "Apache-2.0", None),
    "xv6": ("https://github.com/mit-pdos/xv6-public", "MIT", None),
    "contiki-ng": ("https://github.com/contiki-ng/contiki-ng", "BSD-3-Clause", ["os/", "arch/"]),
    "rt-thread": ("https://github.com/RT-Thread/rt-thread", "Apache-2.0",
                  ["src/", "libcpu/", "components/drivers/"]),
    "u-boot": ("https://github.com/u-boot/u-boot", "GPL-2.0", ["arch/", "drivers/", "common/", "lib/", "cmd/"]),
    "opensbi": ("https://github.com/riscv-software-src/opensbi", "BSD-2-Clause", None),
    "sel4": ("https://github.com/seL4/seL4", "GPL-2.0", ["src/", "include/", "libsel4/"]),
    "libopencm3": ("https://github.com/libopencm3/libopencm3", "LGPL-3.0", None),
}
LINUX = ("https://github.com/torvalds/linux", "GPL-2.0")
LINUX_BUCKETS = {
    "linux_gpu": ["drivers/gpu/", "drivers/video/", "drivers/accel/"],
    "linux_cpu": ["arch/x86/", "arch/arm64/", "arch/riscv/", "arch/arm/", "drivers/cpufreq/",
                  "drivers/cpuidle/", "drivers/irqchip/", "drivers/clocksource/", "drivers/perf/",
                  "drivers/firmware/"],
    "linux_core": ["kernel/", "mm/", "fs/", "net/", "block/", "ipc/", "lib/", "security/", "crypto/",
                   "init/", "include/linux/", "drivers/pci/", "drivers/usb/", "drivers/nvme/",
                   "drivers/base/", "drivers/dma/", "drivers/iommu/", "drivers/virtio/",
                   "drivers/tty/", "drivers/char/", "drivers/md/", "drivers/scsi/"],
}
EXTS = {".c", ".h", ".S", ".s"}
SKIP_PATH = re.compile(
    r"(_sh_mask\.h$|_offset\.h$|/asic_reg/|/firmware/.*\.(c|h)$|/(test|tests|selftests|Documentation|"
    r"samples|tools|scripts|third_party|ThirdParty|examples)/|\.dtsi?$|/bsp/|/boards/|/dts/)")
GENERATED = re.compile(r"(auto-?generated|do not edit|generated by|this file is generated)", re.I)
HEXROW = re.compile(r"^\s*(0x[0-9a-fA-F]+\s*,?\s*)+$")
SPDX = re.compile(r"SPDX-License-Identifier:\s*([^\n*]+?)\s*(?:\*/)?\s*$", re.M)


def sh(cmd, cwd=None, tries=3):
    for i in range(tries):
        r = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True)
        if r.returncode == 0:
            return r.stdout.strip()
        print(f"  retry {i+1}: {r.stderr.strip()[:200]}", flush=True)
        time.sleep(3)
    return None


def clone(name, url):
    dst = SRC / name
    if not dst.exists():
        print(f"cloning {name}", flush=True)
        if sh(f"git clone --depth 1 --quiet {url} {dst}") is None:
            return None, None
    return dst, sh("git rev-parse HEAD", cwd=dst)


def define_ratio(text):
    lines = [l for l in text.splitlines() if l.strip()]
    return sum(l.lstrip().startswith("#define") for l in lines) / max(1, len(lines))


def accept(rel, text):
    if SKIP_PATH.search("/" + rel):
        return False
    n = len(text.encode("utf-8", "ignore"))
    if not (MIN_FILE_BYTES <= n <= MAX_FILE_BYTES):
        return False
    if GENERATED.search(text[:1500]):
        return False
    lines = text.splitlines()
    if not lines or max(len(l) for l in lines) > 2000:
        return False
    if sum(bool(HEXROW.match(l)) for l in lines) / len(lines) > 0.4:
        return False
    if sum(ord(c) > 127 for c in text) / len(text) > 0.05:
        return False
    return True


def scan(root, prefixes, bucket, source, lic_hint, sha, out):
    for p in root.rglob("*"):
        if p.suffix not in EXTS or not p.is_file() or ".git" in p.parts:
            continue
        rel = p.relative_to(root).as_posix()
        if prefixes and not any(rel.startswith(x) for x in prefixes):
            continue
        try:
            text = p.read_text("utf-8")
        except (UnicodeDecodeError, OSError):
            continue
        if not accept(rel, text):
            continue
        m = SPDX.search(text[:600])
        out.append({"text": text, "path": f"{source}/{rel}", "bucket": bucket, "source": source,
                    "spdx": (m.group(1) if m else lic_hint), "commit": sha,
                    "def_heavy": define_ratio(text) > 0.6})


def main():
    random.seed(SEED)
    SRC.mkdir(parents=True, exist_ok=True)
    OUT.mkdir(parents=True, exist_ok=True)
    cands, failed = [], []
    for name, (url, lic, prefixes) in MCU_REPOS.items():
        if ONLY and name not in ONLY:
            continue
        d, sha = clone(name, url)
        if d is None:
            failed.append(name); continue
        scan(d, prefixes, "mcu", name, lic, sha, cands)
    if not ONLY or "linux" in ONLY:
        d, sha = clone("linux", LINUX[0])
        if d is None:
            failed.append("linux")
        else:
            for bucket, prefixes in LINUX_BUCKETS.items():
                # source = first two path components so GPU/arch/etc. are balanced
                tmp = []
                scan(d, prefixes, bucket, "linux", LINUX[1], sha, tmp)
                for r in tmp:
                    parts = r["path"].split("/")
                    r["source"] = "/".join(parts[:3])
                cands.extend(tmp)
    print(f"candidates before dedup: {len(cands)}", flush=True)

    seen, uniq = set(), []
    for r in cands:
        h = hashlib.sha1(re.sub(r"\s+", " ", r["text"]).encode()).hexdigest()
        if h not in seen:
            seen.add(h); uniq.append(r)
    print(f"after exact dedup: {len(uniq)}", flush=True)

    train, held = [], []
    by_bucket = defaultdict(lambda: defaultdict(list))
    for r in uniq:
        d = "/".join(r["path"].split("/")[:5])
        if int(hashlib.md5(d.encode()).hexdigest(), 16) % HELDOUT_MOD == 0:
            held.append(r)
        else:
            by_bucket[r["bucket"]][r["source"]].append(r)

    for bucket, srcs in by_bucket.items():
        budget = TOKEN_BUDGET * WEIGHTS[bucket] * BYTES_PER_TOKEN
        # #define-heavy register headers: keep only ~15% so they don't dominate
        for k in srcs:
            srcs[k] = [r for r in srcs[k] if not r["def_heavy"] or random.random() < 0.15]
            random.shuffle(srcs[k])
        used, per = 0, Counter()
        queues = {k: v for k, v in srcs.items() if v}
        while queues and used < budget:
            for k in list(queues):
                if per[k] > SHARE_CAP * budget:
                    del queues[k]; continue
                r = queues[k].pop()
                b = len(r["text"].encode())
                train.append(r); used += b; per[k] += b
                if not queues[k]:
                    del queues[k]
                if used >= budget:
                    break
        print(f"{bucket}: {used/BYTES_PER_TOKEN/1e6:.1f}M est. tokens "
              f"(target {TOKEN_BUDGET*WEIGHTS[bucket]/1e6:.1f}M)", flush=True)

    random.shuffle(train)
    for name, rows in (("train", train), ("heldout", held)):
        with open(OUT / f"{name}.jsonl", "w") as f:
            for r in rows:
                r = {k: v for k, v in r.items() if k != "def_heavy"}
                f.write(json.dumps(r) + "\n")
    stats = {"failed_repos": failed, "budget_tokens": TOKEN_BUDGET, "bytes_per_token_assumed": BYTES_PER_TOKEN}
    for name, rows in (("train", train), ("heldout", held)):
        tot = Counter(); n = Counter(); lic = Counter()
        for r in rows:
            tot[r["bucket"]] += len(r["text"].encode()); n[r["bucket"]] += 1; lic[r["spdx"]] += 1
        s = sum(tot.values()) or 1
        stats[name] = {"files": dict(n), "est_tokens_M": {k: round(v / BYTES_PER_TOKEN / 1e6, 2) for k, v in tot.items()},
                       "share": {k: round(v / s, 3) for k, v in tot.items()},
                       "top_licenses": lic.most_common(12)}
    (OUT / "stats.json").write_text(json.dumps(stats, indent=2))
    print(json.dumps(stats, indent=2))
    if os.environ.get("CLEAN_SRC", "1") == "1":
        shutil.rmtree(SRC, ignore_errors=True)  # keep notebook output small


if __name__ == "__main__":
    main()