Download impl/src/pipeline/step07_splits.py from pramodkachare/Cyber: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/step07_splits.py
- Command line
-
hf download hf://datasets/pramodkachare/Cyber/impl/src/pipeline/step07_splits.py
-
curl -L -o step07_splits.py https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/step07_splits.py
12.5 kB
| """STEP 07 (v2, after adversarial review): frozen split protocols P1-P5, leak flags, evaluability matrix, assertions. | |
| Population: first occurrence of each (feature-set-A hash, Attack) pair (step 05 `is_first_A`). | |
| Split codes in data/splits.parquet: 0 train, 1 val, 2 test, -1 not used. | |
| p1 random, stratified within (source, Attack): 70/15/15 (optimistic reference only) | |
| p2 per-class chronological: within (source, Attack) by flow start; first 70% / next 15% / last 15%; rows within EMBARGO | |
| of a boundary dropped, EMBARGO = min(5 min, 1% of the stream's span). Windows differ per class, so with feature set A | |
| the absolute timestamp can separate classes: headline P2 scores use feature set B (A = shortcut study). | |
| p3 source-IP group split inside (source, Attack). Counted as evaluable only with >=5 train and >=5 test source IPs and a | |
| top-IP share <= 50% (review finding); otherwise a case study. Destination IPs are NOT grouped (session straddling remains). | |
| p4_<src> shared-class LOSO (classes passing MIN_TRAIN/MIN_TEST); p4_cse has a single evaluable class (Benign): flagged degenerate. | |
| p4b_<src> binary LOSO: all flows of the held-out source are test; label = benign vs attack at evaluation time | |
| p5_<src> family LOSO with taxonomy v1 (ATT&CK-grounded, from step 07a) ; p5v0_<src> the same with provisional taxonomy v0 | |
| Leak flags (data/split_flags.parquet: protocol, row_id, lk): for TEST rows only. lk = 1: the row's feature-set-B hash occurs in the | |
| protocol's train set WITH THE SAME label (exact B duplicate = leakage); lk = 2: it occurs only with a DIFFERENT label (irreducible | |
| label conflict). Rows absent from the file are clean. B/C-feature scores must use clean test rows only. | |
| Outputs: data/splits.parquet, data/split_flags.parquet, artifacts/step07/{taxonomy tables, family_by_source.csv, evaluability_matrix.csv, | |
| p3_ip_stats.csv, protocol_summary.json, assertions.json} | |
| """ | |
| import csv | |
| from .common import * | |
| NAME = "step07" | |
| MIN_TRAIN, MIN_TEST = 100, 50 | |
| MIN_IPS, MAX_TOP_IP = 5, 0.5 | |
| EMBARGO_MS = 300_000 | |
| KEYS = os.path.join(DATA, "dedup_keys.parquet") | |
| SPLITS = os.path.join(DATA, "splits.parquet") | |
| FLAGS = os.path.join(DATA, "split_flags.parquet") | |
| TAX_V1 = os.path.join(ART, "step07a", "taxonomy_v1.csv") | |
| S = f"read_parquet('{PARQUET_SRC}')" | |
| K = f"read_parquet('{KEYS}')" | |
| def _w(path, header, rows): | |
| with open(path, "w", newline="") as f: | |
| w = csv.writer(f); w.writerow(header); w.writerows(rows) | |
| def load_v1(): | |
| if not os.path.exists(TAX_V1): | |
| raise SystemExit("taxonomy_v1.csv missing: run step 07a first") | |
| with open(TAX_V1) as f: | |
| m = {r["Attack"]: r["family"] for r in csv.DictReader(f)} | |
| m["Benign"] = "BENIGN" | |
| return m | |
| def run(force=False): | |
| out = step_dir(NAME); con = connect() | |
| fam0, fam1 = FAMILY_OF, load_v1() | |
| classes = [r[0] for r in con.execute(f"SELECT DISTINCT Attack FROM {S}").fetchall()] | |
| assert set(classes) == set(fam0) == set(fam1), "taxonomies do not cover all classes" | |
| con.execute("CREATE TABLE tax(Attack VARCHAR, f0 VARCHAR, f1 VARCHAR)") | |
| con.executemany("INSERT INTO tax VALUES (?, ?, ?)", [(a, fam0[a], fam1[a]) for a in classes]) | |
| con.execute(f"""CREATE TABLE pop AS SELECT s.row_id, s.source, s.Attack, t.f0, t.f1, (s.Attack <> 'Benign')::INT bin, | |
| s.FLOW_START_MILLISECONDS ts, s.IPV4_SRC_ADDR sip, k.hA, k.hB, k.conflictA, k.conflictB | |
| FROM {S} s JOIN {K} k USING (row_id) JOIN tax t USING (Attack) WHERE k.is_first_A""") | |
| npop = con.execute("SELECT count(*) FROM pop").fetchone()[0] | |
| print("population", npop) | |
| fams1 = sorted(set(fam1.values())); fams0 = sorted(set(fam0.values())) | |
| cnt = {} | |
| for key, col in (("Attack", "Attack"), ("f1", "f1"), ("f0", "f0")): | |
| cnt[key] = {(a, s): c for a, s, c in con.execute(f"SELECT {col}, source, count(*) FROM pop GROUP BY ALL").fetchall()} | |
| for tag, fams, key in (("v1", fams1, "f1"), ("v0", fams0, "f0")): | |
| _w(os.path.join(out, f"family_by_source_{tag}.csv"), ["family"] + SOURCES + ["n_sources"], | |
| [[f] + [cnt[key].get((f, s), 0) for s in SOURCES] + [sum(cnt[key].get((f, s), 0) > 0 for s in SOURCES)] for f in fams]) | |
| def evaluable(table, keys, s): | |
| res = [] | |
| for k in keys: | |
| te = table.get((k, s), 0); tr = sum(table.get((k, o), 0) for o in SOURCES if o != s) | |
| if te >= MIN_TEST and tr >= MIN_TRAIN: res.append(k) | |
| return res | |
| q = lambda xs: ", ".join("'" + x.replace("'", "''") + "'" for x in xs) or "''" | |
| ts_b = f"""(SELECT source, Attack, min(ts) t0, max(ts) t1, quantile_cont(ts, 0.70) b70, quantile_cont(ts, 0.85) b85, | |
| least({EMBARGO_MS}, 0.01 * (max(ts) - min(ts))) emb FROM pop GROUP BY ALL)""" | |
| cols = ["CASE WHEN u1 <= 0.70 THEN 0 WHEN u1 <= 0.85 THEN 1 ELSE 2 END::TINYINT AS p1", | |
| "CASE WHEN ts <= b70 - emb THEN 0 WHEN ts > b70 + emb AND ts <= b85 - emb THEN 1 WHEN ts > b85 + emb THEN 2 ELSE -1 END::TINYINT AS p2", | |
| "CASE WHEN ug <= 0.70 THEN 0 WHEN ug <= 0.85 THEN 1 ELSE 2 END::TINYINT AS p3"] | |
| lists = {} | |
| tv = "CASE WHEN (hash(row_id, 4242) % 100) < 10 THEN 1 ELSE 0 END" | |
| for s in SOURCES: | |
| sh = SRC_SHORT[s] | |
| ev_c = evaluable(cnt["Attack"], classes, s); ev_f1 = evaluable(cnt["f1"], fams1, s); ev_f0 = evaluable(cnt["f0"], fams0, s) | |
| lists[sh] = {"classes": ev_c, "families_v1": ev_f1, "families_v0": ev_f0} | |
| cols.append(f"""CASE WHEN source = '{s}' THEN (CASE WHEN Attack IN ({q(ev_c)}) THEN 2 ELSE -1 END) | |
| ELSE (CASE WHEN Attack IN ({q(ev_c)}) THEN {tv} ELSE -1 END) END::TINYINT AS p4_{sh}""") | |
| cols.append(f"CASE WHEN source = '{s}' THEN 2 ELSE {tv} END::TINYINT AS p4b_{sh}") | |
| for tag, key, ev in (("p5", "f1", ev_f1), ("p5v0", "f0", ev_f0)): | |
| cols.append(f"""CASE WHEN source = '{s}' THEN (CASE WHEN {key} IN ({q(ev)}) THEN 2 ELSE -1 END) | |
| ELSE (CASE WHEN {key} IN ({q(ev)}) THEN {tv} ELSE -1 END) END::TINYINT AS {tag}_{sh}""") | |
| with timed("build splits"): | |
| con.execute(f"""CREATE TABLE sp AS SELECT row_id, source, Attack, f0, f1, bin::VARCHAR bins, sip, hB, conflictB, {', '.join(cols)} FROM ( | |
| SELECT p.*, row_number() OVER (PARTITION BY p.source, p.Attack ORDER BY hash(p.row_id, {SEED})) * 1.0 / count(*) OVER (PARTITION BY p.source, p.Attack) u1, | |
| (hash(p.sip, {SEED}) % 1000000) / 1000000.0 ug, b.b70, b.b85, b.emb | |
| FROM pop p JOIN {ts_b} b USING (source, Attack))""") | |
| protos = ["p1", "p2", "p3"] + [f"{p}_{SRC_SHORT[s]}" for p in ("p4", "p4b", "p5", "p5v0") for s in SOURCES] | |
| label_of = lambda p: {"p4b": "bins", "p5": "f1", "p5v0": "f0"}.get(p.split("_")[0], "Attack") | |
| # ---- leak flags, test rows only | |
| con.execute("CREATE TABLE fl(protocol VARCHAR, row_id BIGINT, lk TINYINT)") | |
| with timed("leak flags"): | |
| for p in protos: | |
| L = label_of(p) | |
| con.execute(f"CREATE OR REPLACE TABLE trh AS SELECT DISTINCT hB FROM sp WHERE {p} = 0") | |
| con.execute(f"CREATE OR REPLACE TABLE trl AS SELECT DISTINCT hB, {L} lab FROM sp WHERE {p} = 0") | |
| con.execute(f"""INSERT INTO fl SELECT '{p}', t.row_id, | |
| CASE WHEN l.hB IS NOT NULL THEN 1 ELSE 2 END::TINYINT | |
| FROM (SELECT row_id, hB, {L} lab FROM sp WHERE {p} = 2) t | |
| JOIN trh h ON h.hB = t.hB LEFT JOIN trl l ON l.hB = t.hB AND l.lab = t.lab""") | |
| with timed("write splits and flags"): | |
| con.execute(f"COPY (SELECT row_id, {', '.join(protos)} FROM sp ORDER BY row_id) TO '{SPLITS}' (FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 1000000)") | |
| con.execute(f"COPY (SELECT * FROM fl ORDER BY protocol, row_id) TO '{FLAGS}' (FORMAT PARQUET, COMPRESSION ZSTD)") | |
| # ---- P3 IP statistics per class (distinct (source, ip) pairs) | |
| ipst = con.execute("""SELECT Attack, count(DISTINCT source || '|' || sip) n_ips, | |
| count(DISTINCT source || '|' || sip) FILTER (WHERE p3 = 0) tr_ips, count(DISTINCT source || '|' || sip) FILTER (WHERE p3 = 2) te_ips, | |
| max(top_share) top_share FROM (SELECT sp.*, max(c) OVER (PARTITION BY Attack) * 1.0 / sum(c) OVER (PARTITION BY Attack) top_share | |
| FROM (SELECT *, count(*) OVER (PARTITION BY Attack, source, sip) c FROM sp) sp) GROUP BY Attack ORDER BY n_ips""").fetchall() | |
| _w(os.path.join(out, "p3_ip_stats.csv"), ["Attack", "n_distinct_src_ips", "n_train_ips", "n_test_ips", "top_ip_share"], [[a, n, tr, te, round(t, 4)] for a, n, tr, te, t in ipst]) | |
| p3_ok = {a: (tr >= MIN_IPS and te >= MIN_IPS and t <= MAX_TOP_IP) for a, n, tr, te, t in ipst} | |
| # ---- evaluability matrix | |
| rows, summary = [], {"population_rows": npop, "thresholds": {"MIN_TRAIN": MIN_TRAIN, "MIN_TEST": MIN_TEST, "MIN_IPS_P3": MIN_IPS, "MAX_TOP_IP_P3": MAX_TOP_IP, "EMBARGO_MS": EMBARGO_MS}, | |
| "protocols": {}, "loso_lists": lists} | |
| for p in protos: | |
| L = label_of(p) | |
| rs = con.execute(f"""SELECT sp.{L}, count(*) FILTER (WHERE sp.{p} = 0), count(*) FILTER (WHERE sp.{p} = 1), count(*) FILTER (WHERE sp.{p} = 2), | |
| count(*) FILTER (WHERE f.lk = 1), count(*) FILTER (WHERE f.lk = 2), count(DISTINCT sp.hB) FILTER (WHERE sp.{p} = 0) | |
| FROM sp LEFT JOIN (SELECT row_id, lk FROM fl WHERE protocol = '{p}') f USING (row_id) GROUP BY 1 ORDER BY 1""").fetchall() | |
| nA = nB = 0; tests = clean_ev = 0 | |
| for lab, tr, va, te, lk1, lk2, tr_u in rs: | |
| clean = te - lk1 - lk2 | |
| ok3 = (p != "p3") or p3_ok.get(lab, False) | |
| evA = int(tr >= MIN_TRAIN and te >= MIN_TEST and ok3) | |
| evB = int(tr_u >= MIN_TRAIN and clean >= MIN_TEST and ok3) | |
| rows.append([p, L, lab, tr, va, te, lk1, lk2, clean, tr_u, evA, evB]) | |
| nA += evA; nB += evB; tests += te; clean_ev += clean if evB else 0 | |
| summary["protocols"][p] = {"labels": len(rs), "evaluable_A": nA, "evaluable_B": nB, "test_rows": tests, "clean_test_rows_in_evaluable_B_labels": clean_ev, | |
| "scored": nA >= 2, "degenerate": nA < 2} | |
| _w(os.path.join(out, "evaluability_matrix.csv"), ["protocol", "label_level", "label", "n_train", "n_val", "n_test", "n_test_leak_same_label", "n_test_cross_label_conflict", "n_test_clean", "n_train_unique_B", "evaluable_A", "evaluable_B"], rows) | |
| # ---- assertions | |
| chk = {} | |
| chk["p2_train_before_test_in_every_stream"] = con.execute("""SELECT count(*) FROM (SELECT p.source, p.Attack FROM pop p JOIN sp USING (row_id) GROUP BY ALL | |
| HAVING max(CASE WHEN sp.p2 = 0 THEN p.ts END) >= min(CASE WHEN sp.p2 = 2 THEN p.ts END))""").fetchone()[0] == 0 | |
| chk["p3_no_source_ip_in_both_train_and_test"] = con.execute("""SELECT count(*) FROM (SELECT source, Attack, sip FROM sp | |
| GROUP BY ALL HAVING count(DISTINCT p3) FILTER (WHERE p3 IN (0, 2)) > 1)""").fetchone()[0] == 0 | |
| for s in SOURCES: | |
| sh = SRC_SHORT[s] | |
| for p in ("p4", "p4b", "p5", "p5v0"): | |
| chk[f"{p}_{sh}_test_only_in_heldout_and_train_never"] = con.execute( | |
| f"SELECT count(*) FROM sp WHERE ({p}_{sh} = 2 AND source <> '{s}') OR ({p}_{sh} IN (0,1) AND source = '{s}')").fetchone()[0] == 0 | |
| for p in ("p1", "p2", "p3"): | |
| con.execute(f"CREATE OR REPLACE TABLE trA AS SELECT DISTINCT pop.hA FROM pop JOIN sp USING (row_id) WHERE sp.{p} = 0") | |
| chk[f"no_test_row_has_identical_A_features_in_train_{p}_excluding_label_conflicts"] = con.execute( | |
| f"SELECT count(*) FROM pop JOIN sp USING (row_id) JOIN trA t USING (hA) WHERE sp.{p} = 2 AND NOT pop.conflictA").fetchone()[0] == 0 | |
| chk["flags_only_on_test_rows"] = con.execute("SELECT count(*) FROM fl f JOIN sp USING (row_id) WHERE (CASE f.protocol WHEN 'p1' THEN sp.p1 WHEN 'p2' THEN sp.p2 WHEN 'p3' THEN sp.p3 ELSE 2 END) <> 2").fetchone()[0] == 0 | |
| summary["leak_flag_counts"] = {p: dict(con.execute(f"SELECT lk, count(*) FROM fl WHERE protocol = '{p}' GROUP BY 1").fetchall()) for p in protos} | |
| summary["conflictA_rows_in_population"] = con.execute("SELECT count(*) FROM pop WHERE conflictA").fetchone()[0] | |
| summary["assertions_all_passed"] = all(chk.values()) | |
| save_json(chk, os.path.join(out, "assertions.json")); save_json(summary, os.path.join(out, "protocol_summary.json")) | |
| print(json.dumps({"assertions_failed": [k for k, v in chk.items() if not v], "n_assertions": len(chk), | |
| "protocols": summary["protocols"]}, indent=1)[:6000]) | |