Download scripts/audit_exact_label_conflicts.py from Dhruv1000/tracegrpo: direct link, hf CLI and curl.
- Browser
- Download file 7.05 kB
-
https://huggingface.co/Dhruv1000/tracegrpo/resolve/main/scripts/audit_exact_label_conflicts.py
- Command line
-
hf download hf://Dhruv1000/tracegrpo/scripts/audit_exact_label_conflicts.py
-
curl -L -o audit_exact_label_conflicts.py https://huggingface.co/Dhruv1000/tracegrpo/resolve/main/scripts/audit_exact_label_conflicts.py
7.05 kB
| """Measure exact target-code duplicates with conflicting labels in TRAIN/VALID only.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import re | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| import pandas as pd | |
| from src.contracts.prompt import code_for_sample | |
| ROOT = Path(__file__).resolve().parents[1] | |
| CORPUS = ROOT / "data/processed/corpus.parquet" | |
| TRAIN = ROOT / "data/splits/chronological/train.json" | |
| VALID = ROOT / "data/splits/chronological/valid.json" | |
| OUTPUT = ROOT / "results/phase7/exact_label_conflict_audit.json" | |
| TOKEN_RE = re.compile(r"[A-Za-z_]\w*|0[xX][0-9A-Fa-f]+|\d+|==|!=|<=|>=|->|\+\+|--|&&|\|\||[^\s]") | |
| COMMENT_RE = re.compile(r"/\*.*?\*/|//[^\n]*", re.DOTALL) | |
| def digest(path: Path) -> str: | |
| return hashlib.sha256(path.read_bytes()).hexdigest() | |
| def fingerprint(code: str, normalized: bool) -> str: | |
| if normalized: | |
| code = " ".join(TOKEN_RE.findall(COMMENT_RE.sub(" ", code))) | |
| return hashlib.sha256(code.encode()).hexdigest() | |
| def summarize(rows: list[dict]) -> dict: | |
| groups: dict[str, list[dict]] = defaultdict(list) | |
| for row in rows: | |
| groups[row["fingerprint"]].append(row) | |
| duplicate = {h: g for h, g in groups.items() if len(g) > 1} | |
| conflicts = {h: g for h, g in duplicate.items() if len({x["target"] for x in g}) > 1} | |
| unavoidable = sum(min(Counter(x["target"] for x in g).values()) for g in conflicts.values()) | |
| return {"rows": len(rows), "unique_fingerprints": len(groups), | |
| "duplicate_groups": len(duplicate), "rows_in_duplicate_groups": sum(map(len, duplicate.values())), | |
| "opposite_label_groups": len(conflicts), | |
| "rows_in_opposite_label_groups": sum(map(len, conflicts.values())), | |
| "majority_label_code_only_ceiling": 1.0 - unavoidable / len(rows) if rows else None, | |
| "unavoidable_minority_rows": int(unavoidable), | |
| "examples": [{"targets": [x["target"] for x in g], | |
| "splits": [x["split"] for x in g], | |
| "sample_ids": [x["sample_id"] for x in g], | |
| "sources": [x["source"] for x in g], | |
| "cwes": [x["cwe"] for x in g]} | |
| for g in list(conflicts.values())[:8]]} | |
| def train_lookup(train_rows: list[dict], valid_rows: list[dict]) -> dict: | |
| lookup: dict[str, Counter] = defaultdict(Counter) | |
| for row in train_rows: | |
| lookup[row["fingerprint"]][row["target"]] += 1 | |
| covered = tied = correct = 0 | |
| per_row = [] | |
| for row in valid_rows: | |
| counts = lookup.get(row["fingerprint"]) | |
| if not counts: | |
| continue | |
| covered += 1 | |
| if counts[0] == counts[1]: | |
| tied += 1 | |
| continue | |
| pred = max(counts, key=counts.get) | |
| correct += int(pred == row["target"]) | |
| per_row.append({"target": row["target"], "pred": pred}) | |
| return {"valid_rows": len(valid_rows), "exact_train_code_matches": covered, | |
| "match_coverage": covered / len(valid_rows), "ambiguous_majority_ties": tied, | |
| "resolved_matches": len(per_row), | |
| "train_majority_label_accuracy_on_resolved_matches": correct / len(per_row) if per_row else None, | |
| "resolved_match_count_correct": correct} | |
| def run(corpus_path: Path = CORPUS, train_path: Path = TRAIN, | |
| valid_path: Path = VALID) -> dict: | |
| train_ids, valid_ids = set(map(str, json.loads(train_path.read_text()))), set(map(str, json.loads(valid_path.read_text()))) | |
| if train_ids & valid_ids: | |
| raise ValueError("chronological TRAIN/VALID pair overlap") | |
| frame = pd.read_parquet(corpus_path) | |
| rows = {"train": [], "valid": []} | |
| for split, ids in (("train", train_ids), ("valid", valid_ids)): | |
| subset = frame[frame.pair_id.astype(str).isin(ids)] | |
| for sample in subset.itertuples(index=False): | |
| row = sample._asdict() | |
| code = code_for_sample(row) | |
| rows[split].append({"sample_id": str(row["sample_id"]), "pair_id": str(row["pair_id"]), | |
| "target": int(row["target"]), "source": str(row["source"]), | |
| "cwe": str(row["cwe"]), "code": code}) | |
| if len(rows[split]) != 2 * len(ids): | |
| raise ValueError(f"{split} pair row-count mismatch") | |
| result = {"purpose": "code-only exact duplicate/conflicting-label audit; no TEST records read", | |
| "normalization_caveat": "Token view strips C-style comments and whitespace using regex; it is a screening signature, not a parser or semantic equivalence test.", | |
| "splits": {}} | |
| for view, normalized in (("raw_code", False), ("comment_whitespace_token_signature", True)): | |
| indexed = {split: [{**row, "split": split, | |
| "fingerprint": fingerprint(row["code"], normalized)} for row in split_rows] | |
| for split, split_rows in rows.items()} | |
| combined = indexed["train"] + indexed["valid"] | |
| all_stats = summarize(combined) | |
| split_stats = {split: summarize(items) for split, items in indexed.items()} | |
| train_groups: dict[str, list[dict]] = defaultdict(list) | |
| valid_groups: dict[str, list[dict]] = defaultdict(list) | |
| for row in indexed["train"]: train_groups[row["fingerprint"]].append(row) | |
| for row in indexed["valid"]: valid_groups[row["fingerprint"]].append(row) | |
| shared = set(train_groups) & set(valid_groups) | |
| cross_conflicts = {h: train_groups[h] + valid_groups[h] for h in shared | |
| if len({r["target"] for r in train_groups[h] + valid_groups[h]}) > 1} | |
| result["splits"][view] = { | |
| "all_train_valid": all_stats, "train": split_stats["train"], "valid": split_stats["valid"], | |
| "cross_split": {"shared_code_groups": len(shared), "opposite_label_groups": len(cross_conflicts), | |
| "rows_in_opposite_label_groups": sum(map(len, cross_conflicts.values()))}, | |
| "train_lookup_on_valid": train_lookup(indexed["train"], indexed["valid"]), | |
| } | |
| result["provenance"] = {"corpus_sha256": digest(corpus_path), "train_split_sha256": digest(train_path), | |
| "valid_split_sha256": digest(valid_path), "train_pairs": len(train_ids), | |
| "valid_pairs": len(valid_ids), "test_read": False} | |
| return result | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--corpus", type=Path, default=CORPUS) | |
| parser.add_argument("--train", type=Path, default=TRAIN) | |
| parser.add_argument("--valid", type=Path, default=VALID) | |
| parser.add_argument("--output", type=Path, default=OUTPUT) | |
| args = parser.parse_args() | |
| result = run(args.corpus, args.train, args.valid) | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") | |
| print(json.dumps(result, indent=2, sort_keys=True)) | |
| if __name__ == "__main__": | |
| main() | |