File size: 4,819 Bytes
676defa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build leakage-controlled splits of the CircuitQA corpus.

S1  sample-level      (random split by sample; a design may appear in several partitions)
S2  design-disjoint   (no source_file shared between train and test)
S3  repo-disjoint     (no upstream repository shared between train and test)

Also emits a frozen stratified n=500 evaluation sample from the S3 test set,
used for BOTH CircuitQA and every baseline model so numbers are comparable.
"""
import json, collections, random, os

SRC = "training/data/v7_clean"
OUT = "revision/splits"
SEED = 42
CATS = ["structural_analysis","design_quality","functional_behavior",
        "code_understanding","optimization","cross_stage"]

def repo_of(sf):
    p = (sf or "").split("/")
    return "/".join(p[:2]) if len(p) > 1 else (sf or "unknown")

rows = []
for split in ("train","val","test"):
    with open(f"{SRC}/{split}.jsonl") as f:
        for line in f:
            d = json.loads(line)
            d["_repo"] = repo_of(d.get("source_file"))
            rows.append(d)
print(f"loaded {len(rows)} samples")

by_repo = collections.defaultdict(list)
for d in rows: by_repo[d["_repo"]].append(d)
sizes = {r: len(v) for r, v in by_repo.items()}
total = len(rows)

# ---- S3: repo-disjoint. Prefer several mid-sized repos over one large one,
# so the held-out set spans multiple design styles rather than one vendor's.
rng = random.Random(SEED)
ranked = sorted(sizes, key=lambda r: -sizes[r])
mid = [r for r in ranked if 300 <= sizes[r] <= 3000]          # candidate pool
rng.shuffle(mid)

def take(pool, target, used):
    sel, n = [], 0
    for r in pool:
        if r in used: continue
        if n >= target * 0.90: break
        if n + sizes[r] > target * 1.20: continue
        sel.append(r); n += sizes[r]
    return sel, n

used = set()
test_repos, n_te = take(mid, total*0.10, used); used |= set(test_repos)
val_repos,  n_va = take(mid, total*0.10, used); used |= set(val_repos)
train_repos = [r for r in ranked if r not in used]

s3 = {"train": [d for r in train_repos for d in by_repo[r]],
      "val":   [d for r in val_repos  for d in by_repo[r]],
      "test":  [d for r in test_repos for d in by_repo[r]]}

# ---- S2: design-disjoint. Hold out whole source_files, stratified by category.
files = sorted({d["source_file"] for d in rows})
rng2 = random.Random(SEED); rng2.shuffle(files)
n_f = len(files)
te_f = set(files[:int(n_f*0.10)]); va_f = set(files[int(n_f*0.10):int(n_f*0.20)])
s2 = {"train": [], "val": [], "test": []}
for d in rows:
    k = "test" if d["source_file"] in te_f else "val" if d["source_file"] in va_f else "train"
    s2[k].append(d)

def report(name, s):
    print(f"\n=== {name} ===")
    for k in ("train","val","test"):
        cc = collections.Counter(d["category"] for d in s[k])
        nf = len({d["source_file"] for d in s[k]})
        print(f"  {k:5s} n={len(s[k]):6d} ({100*len(s[k])/total:4.1f}%) designs={nf:5d} cats={len(cc)}/6")
    tr_r = {d["_repo"] for d in s["train"]}; te_r = {d["_repo"] for d in s["test"]}
    tr_f = {d["source_file"] for d in s["train"]}; te_f2 = {d["source_file"] for d in s["test"]}
    tr_m = {d["module_name"] for d in s["train"]}; te_m = {d["module_name"] for d in s["test"]}
    print(f"  LEAK repo overlap   : {len(tr_r & te_r)}")
    print(f"  LEAK design overlap : {len(tr_f & te_f2)}")
    print(f"  LEAK module overlap : {len(tr_m & te_m)} / {len(te_m)}")

report("S2 design-disjoint", s2)
report("S3 repo-disjoint", s3)

os.makedirs(OUT, exist_ok=True)
for tag, s in (("s2_design_disjoint", s2), ("s3_repo_disjoint", s3)):
    for k in ("train","val","test"):
        with open(f"{OUT}/{tag}.{k}.jsonl","w") as f:
            for d in s[k]:
                d = {kk: vv for kk, vv in d.items() if kk != "_repo"}
                f.write(json.dumps(d) + "\n")

# ---- frozen stratified n=500 evaluation sample from S3 test
rng3 = random.Random(SEED)
pool = collections.defaultdict(list)
for d in s3["test"]: pool[d["category"]].append(d)
present = [c for c in CATS if pool[c]]
FLOOR, N = 50, 500
alloc = {c: FLOOR for c in present}
rem = N - FLOOR*len(present)
tot_rest = sum(len(pool[c]) for c in present)
for c in present:
    alloc[c] += int(rem * len(pool[c]) / tot_rest)
sample = []
for c in present:
    k = min(alloc[c], len(pool[c]))
    sample += rng3.sample(pool[c], k)
rng3.shuffle(sample)
with open(f"{OUT}/eval_sample_n{len(sample)}.jsonl","w") as f:
    for d in sample:
        d = {kk: vv for kk, vv in d.items() if kk != "_repo"}
        f.write(json.dumps(d) + "\n")
cc = collections.Counter(d["category"] for d in sample)
print(f"\n=== frozen eval sample: n={len(sample)} ===")
for c in CATS:
    if cc[c]: print(f"  {c:22s} {cc[c]:4d}")
print(f"\nheld-out TEST repos (S3): {test_repos}")
print(f"held-out VAL  repos (S3): {val_repos}")