#!/usr/bin/env python3 """CyberData 2: cut the nested releases Small (15,000) ⊂ Medium (25,000) ⊂ Large (65,000) ⊂ Full (everything) from build/assembled_all.jsonl. Selection (deterministic): rows of each SOURCE are ordered by a hash of their group (so code-fix triples etc. stay together), and a tier takes a PREFIX of that order per source. Prefix lengths grow with the tier, so the smaller tier is always inside the larger one. How big each source's prefix is: proportional to a goal-driven target SHARE per source (see SHARES), capped at what exists, with a floor of the previous tier's prefix. The train/valid split of a row is fixed (by group hash) and identical in every tier.""" import collections, csv, json, math, os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from lib import * BUILD, OUT = os.path.join(HERE, "build"), os.path.join(HERE, "out") TIERS = [("small", 15000), ("medium", 25000), ("large", 65000), ("full", None)] # Goal-driven target shares for Small / Medium / Large (Full takes everything). Agentic coding ~29%, code writing + vulnerability finding ~37%, cyber reasoning ~9%, # security knowledge ~21%. A source is capped at what exists; the surplus is redistributed in proportion to the other shares. SHARES = {"swe-hero": 0.115, "openswe": 0.115, "Humanlearning/CyberSecurity_OWASP-sft-dataset": 0.05, "agentforge": 0.01, "primevul": 0.085, "hitoshura25/cvefixes": 0.115, "sigmahq/sigma": 0.075, "CyberNative/Code_Vulnerability_Security_DPO": 0.04, "jcordon5/cybersecurity-rules": 0.01, "mitre/cwe": 0.045, "Leopo1d/OpenVul-rejection-sampling": 0.09, "mitre/attack": 0.04, "mitre/capec": 0.01, "cisa/kev": 0.018, "reloading0101/threat-intelligence-dataset": 0.055, "mrmoor/cyber-threat-intelligence": 0.02, "nuhmanpk/cybersecurity-controls-instructions": 0.015, "Trendyol/Trendyol-Cybersecurity-Instruction-Tuning-Dataset": 0.03, "AlicanKiraz0/Cybersecurity-Dataset-Fenrir-v2.1": 0.02} meta = [json.loads(l) for l in open(os.path.join(BUILD, "assembled_meta.jsonl"), encoding="utf-8")] by_src = collections.defaultdict(list) for m in meta: by_src[m["source"]].append(m) for s in by_src: by_src[s].sort(key=lambda m: (prio(m["group"], "tier"), m["id"])) avail = {s: len(v) for s, v in by_src.items()} missing = set(by_src) - set(SHARES); assert not missing, f"sources without a share: {missing}" tot = sum(SHARES[s] for s in by_src); weight = {s: SHARES[s] / tot for s in by_src} print("pool", sum(avail.values()), {s: avail[s] for s in avail}, flush=True) take = {} # tier -> {source: prefix length} prev = {s: 0 for s in by_src} for name, target in TIERS: if target is None: take[name] = dict(avail); prev = dict(avail); continue def k(lam): return {s: min(avail[s], max(prev[s], round(lam * weight[s]))) for s in by_src} # lam = tier size scale; share-proportional with caps and nesting floors lo, hi = 0.0, 1e6 for _ in range(200): mid = (lo + hi) / 2 if sum(k(mid).values()) < target: lo = mid else: hi = mid t = k(hi) extra = sum(t.values()) - target # trim overshoot from the sources with the most headroom above the floor while extra > 0: s = max((s for s in t if t[s] > prev[s]), key=lambda s: t[s] - prev[s]); t[s] -= 1; extra -= 1 short = target - sum(t.values()) while short > 0: s = max((s for s in t if t[s] < avail[s]), key=lambda s: weight[s] - t[s]); t[s] += 1; short -= 1 assert sum(t.values()) == target, (name, sum(t.values()), target) take[name] = t; prev = t print(f"{name}: {target} rows ->", {s: t[s] for s in sorted(t)}, flush=True) tier_of = {} # row id -> smallest tier index that contains it for ti, (name, _) in enumerate(TIERS): for s, k in take[name].items(): for m in by_src[s][:k]: tier_of.setdefault(m["id"], ti) for name, _ in TIERS: os.makedirs(os.path.join(OUT, f"cyberdata-2-{name}"), exist_ok=True) fh = {} for name, _ in TIERS: d = os.path.join(OUT, f"cyberdata-2-{name}") fh[name] = {"train": open(os.path.join(d, "train.jsonl"), "w", encoding="utf-8"), "valid": open(os.path.join(d, "valid.jsonl"), "w", encoding="utf-8")} index = {name: [] for name, _ in TIERS} n = 0 with open(os.path.join(BUILD, "assembled_all.jsonl"), encoding="utf-8") as f: for line in f: r = json.loads(line); ti = tier_of.get(r["id"]) if ti is None: continue out = json.dumps({"messages": r["messages"]}, ensure_ascii=False) + "\n" for tj in range(ti, len(TIERS)): name = TIERS[tj][0]; fh[name][r["split"]].write(out) index[name].append((r["id"], r["source"], r["task"], r["provenance"], r["split"], r["group"])) n += 1 for d in fh.values(): for h in d.values(): h.close() for name, target in TIERS: d = os.path.join(OUT, f"cyberdata-2-{name}"); ix = index[name] with open(os.path.join(d, "row_index.csv"), "w", newline="") as f: w = csv.writer(f); w.writerow(["id", "source", "task", "provenance", "split", "group"]); w.writerows(sorted(ix)) st = {"tier": name, "rows": len(ix), "train": sum(1 for r in ix if r[4] == "train"), "valid": sum(1 for r in ix if r[4] == "valid"), "by_provenance": dict(collections.Counter(r[3] for r in ix)), "by_source": dict(collections.Counter(r[1] for r in ix)), "by_task": dict(collections.Counter(r[2] for r in ix)), "bytes": {x: os.path.getsize(os.path.join(d, f"{x}.jsonl")) for x in ("train", "valid")}} json.dump(st, open(os.path.join(d, "stats.json"), "w"), indent=1) assert target is None or len(ix) == target, (name, len(ix), target) print(f"{name:7s} rows {st['rows']:>7} train {st['train']:>7} valid {st['valid']:>6} | " + ", ".join(f"{k} {v}" for k, v in sorted(st['by_provenance'].items(), key=lambda x: -x[1]))) print("SIZES_DONE")