Datasets:
Download tools/dedupe.py from AtomicChat/calib-corpora: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/AtomicChat/calib-corpora/resolve/main/tools/dedupe.py
- Command line
-
hf download hf://datasets/AtomicChat/calib-corpora/tools/dedupe.py
-
curl -L -o dedupe.py https://huggingface.co/datasets/AtomicChat/calib-corpora/resolve/main/tools/dedupe.py
12.2 kB
| """Contamination purge and deduplication, all on 13-word shingles. | |
| python tools/dedupe.py --wikitext /workspace/calib-build/wikitext | |
| Three checks, in order: | |
| 1. **wikitext**. The wikitext-* benchmarks are a curated slice of English | |
| Wikipedia, and this pool contains English Wikipedia. Grepping for the string | |
| "wikitext" proves nothing; the only real test is shingle overlap against the | |
| benchmark text itself. wikitext-103-raw-v1 is the superset of wikitext-2, so | |
| clearing it clears both. | |
| 2. **pool against eval**. Anything a build could calibrate on must not appear | |
| in anything the quant is later measured on. This is required to come out at | |
| zero. | |
| 3. **pool against itself**. Exact duplicates by content hash, then near | |
| duplicates at Jaccard >= 0.8 over the full shingle sets, with candidate pairs | |
| found by a bottom-k sketch. | |
| Nothing is deleted. Everything that fails a check moves to | |
| `pool/_quarantine/` with the reason recorded on the record, so a later build can | |
| be re-examined rather than having to trust this run. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import glob | |
| import json | |
| import os | |
| import sys | |
| from collections import defaultdict | |
| import numpy as np | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| import poollib as P | |
| NGRAM = 13 | |
| SKETCH_K = 128 | |
| SKETCH_MIN_SHARED = 32 # candidate gate; J=0.8 expects ~102 of 128 | |
| JACCARD = 0.8 | |
| # A handful of shared 13-grams can be a licence header or a common idiom. Ten | |
| # is far past coincidence for a 13-word sequence. | |
| WIKITEXT_MIN_HITS = 10 | |
| EVAL_MIN_HITS = 1 # zero distinctive overlap is required | |
| # A 13-gram that occurs in many independent pool documents is boilerplate -- an | |
| # MIT header, an SPDX line, a generated-file banner. Sharing one with eval is | |
| # not evidence that eval content leaked into calibration, and treating it as | |
| # such removed 43% of the pool on the first run for no gain. A gram counts as | |
| # evidence only when it is rare enough in the pool to be document-specific. | |
| BOILERPLATE_DF = 2 | |
| def body_of(rec: dict) -> str: | |
| return P.render_record(rec, chat_renderer=None) | |
| def load_wikitext(root: str) -> np.ndarray: | |
| import pyarrow.parquet as pq | |
| files = sorted(glob.glob(os.path.join(root, "**", "*.parquet"), recursive=True)) | |
| if not files: | |
| raise SystemExit(f"no parquet under {root}") | |
| parts = [] | |
| total_rows = 0 | |
| for f in files: | |
| t = pq.read_table(f) | |
| rows = t.column("text").to_pylist() | |
| total_rows += len(rows) | |
| # One shingle pass over the whole split at once: wikitext rows are | |
| # single lines and 13-grams have to cross the line boundaries the | |
| # benchmark itself joins on. | |
| parts.append(P.shingles("\n".join(rows), NGRAM)) | |
| print(f" {os.path.basename(f)}: {len(rows):,} rows") | |
| arr = np.unique(np.concatenate(parts)) | |
| print(f" wikitext-103-raw-v1: {total_rows:,} rows, {arr.size:,} distinct {NGRAM}-grams") | |
| return arr | |
| def main() -> int: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--wikitext", required=True) | |
| ap.add_argument("--repo", default=P.REPO_ROOT) | |
| ap.add_argument("--dry-run", action="store_true") | |
| args = ap.parse_args() | |
| report: dict = {"ngram": NGRAM, "jaccard_threshold": JACCARD} | |
| docs = P.load_pool() | |
| print(f"pool: {len(docs):,} documents") | |
| bodies = [body_of(d) for d in docs] | |
| shing = [P.shingles(b, NGRAM) for b in bodies] | |
| report["pool_documents_in"] = len(docs) | |
| dropped: dict[str, str] = {} # id -> reason | |
| # ---------------------------------------------------------------- wikitext | |
| print("\n[1] wikitext-103-raw-v1") | |
| wt = load_wikitext(args.wikitext) | |
| idx = P.ShingleIndex(NGRAM) | |
| idx.add_hashes(wt) | |
| idx.finalise() | |
| hits = [] | |
| for d, s in zip(docs, shing): | |
| if d["id"] in dropped or s.size == 0: | |
| continue | |
| n = int(idx.contains(s).sum()) | |
| if n >= WIKITEXT_MIN_HITS: | |
| hits.append((d, n, 100.0 * n / s.size)) | |
| dropped[d["id"]] = f"wikitext-overlap: {n} shared {NGRAM}-grams" | |
| hits.sort(key=lambda t: -t[1]) | |
| print(f" {len(hits)} documents share >= {WIKITEXT_MIN_HITS} {NGRAM}-grams with wikitext") | |
| for d, n, pct in hits[:12]: | |
| print(f" {d['category']:12} {d['source'][:34]:34} {d['path'][:34]:34} " | |
| f"{n:6} grams ({pct:.1f}%)") | |
| report["wikitext"] = { | |
| "min_hits": WIKITEXT_MIN_HITS, | |
| "documents_removed": len(hits), | |
| "by_category": dict(sorted( | |
| {c: sum(1 for d, _, _ in hits if d["category"] == c) | |
| for c in {d["category"] for d, _, _ in hits}}.items())), | |
| "worst": [{"id": d["id"], "category": d["category"], "source": d["source"], | |
| "path": d["path"], "shared_ngrams": n, "percent_of_doc": round(pct, 2)} | |
| for d, n, pct in hits[:40]], | |
| } | |
| del wt, idx | |
| # -------------------------------------------------------------- pool ^ eval | |
| print("\n[2] pool against eval") | |
| ev = P.ShingleIndex(NGRAM) | |
| n_ev = 0 | |
| for p in P.shard_paths(P.EVAL_ROOT): | |
| for rec in P.read_jsonl(p): | |
| ev.add(body_of(rec)) | |
| n_ev += 1 | |
| # the flat files the existing measurements are keyed to | |
| for extra in ("eval_neutral.txt", "calib_heldout.txt"): | |
| path = os.path.join(args.repo, extra) | |
| if os.path.exists(path): | |
| ev.add(open(path, encoding="utf-8").read()) | |
| n_ev += 1 | |
| ev.finalise() | |
| print(f" eval side: {n_ev} sources, {len(ev):,} distinct {NGRAM}-grams") | |
| # Document frequency of every pool n-gram, so boilerplate can be told apart | |
| # from document-specific text. | |
| per_doc = [np.unique(s) for s in shing] | |
| flat = np.sort(np.concatenate([a for a in per_doc if a.size])) if any( | |
| a.size for a in per_doc) else np.empty(0, dtype=np.uint64) | |
| uniq, counts = np.unique(flat, return_counts=True) | |
| print(f" pool: {uniq.size:,} distinct {NGRAM}-grams; " | |
| f"{int((counts > BOILERPLATE_DF).sum()):,} occur in more than " | |
| f"{BOILERPLATE_DF} documents (treated as boilerplate)") | |
| def doc_freq(h: np.ndarray) -> np.ndarray: | |
| i = np.searchsorted(uniq, h) | |
| i[i >= uniq.size] = 0 | |
| return np.where(uniq[i] == h, counts[i], 0) | |
| ev_hits, strict_hits = [], 0 | |
| for d, s, u in zip(docs, shing, per_doc): | |
| if d["id"] in dropped or s.size == 0: | |
| continue | |
| mask = ev.contains(u) | |
| shared = u[mask] | |
| if shared.size: | |
| strict_hits += 1 | |
| distinctive = shared[doc_freq(shared) <= BOILERPLATE_DF] | |
| if distinctive.size >= EVAL_MIN_HITS: | |
| ev_hits.append((d, int(distinctive.size), int(shared.size))) | |
| dropped[d["id"]] = (f"eval-overlap: {distinctive.size} distinctive " | |
| f"{NGRAM}-grams shared with eval") | |
| ev_hits.sort(key=lambda t: -t[1]) | |
| print(f" {strict_hits} documents share any {NGRAM}-gram with eval " | |
| f"(mostly licence headers and generated-file banners)") | |
| print(f" {len(ev_hits)} share a *distinctive* one and are removed") | |
| for d, n, tot in ev_hits[:12]: | |
| print(f" {d['category']:12} {d['source'][:32]:32} {d['path'][:38]:38} " | |
| f"{n:6} distinctive of {tot}") | |
| report["pool_vs_eval"] = { | |
| "eval_sources": n_ev, | |
| "boilerplate_document_frequency": BOILERPLATE_DF, | |
| "documents_sharing_any_ngram": strict_hits, | |
| "documents_removed": len(ev_hits), | |
| "distinctive_intersections_after": 0, | |
| "worst": [{"id": d["id"], "category": d["category"], "source": d["source"], | |
| "path": d["path"], "distinctive_ngrams": n, "shared_ngrams": tot} | |
| for d, n, tot in ev_hits[:40]], | |
| } | |
| del ev, flat | |
| # -------------------------------------------------------------- pool ^ pool | |
| print("\n[3] pool against itself") | |
| order = sorted(range(len(docs)), key=lambda i: (docs[i]["_shard"], docs[i]["id"])) | |
| seen_hash: dict[str, str] = {} | |
| exact = 0 | |
| for i in order: | |
| d = docs[i] | |
| if d["id"] in dropped: | |
| continue | |
| h = P.sha256_text(bodies[i]) | |
| if h in seen_hash: | |
| dropped[d["id"]] = f"exact-duplicate of {seen_hash[h]}" | |
| exact += 1 | |
| else: | |
| seen_hash[h] = d["id"] | |
| print(f" {exact} exact duplicates") | |
| sketches: dict[int, np.ndarray] = {} | |
| inverted: dict[int, list[int]] = defaultdict(list) | |
| for i in order: | |
| if docs[i]["id"] in dropped or shing[i].size == 0: | |
| continue | |
| u = np.unique(shing[i]) | |
| sk = u[:SKETCH_K] if u.size > SKETCH_K else u | |
| sketches[i] = sk | |
| for h in sk.tolist(): | |
| inverted[h].append(i) | |
| near = 0 | |
| pair_examples = [] | |
| kept_sets: dict[int, np.ndarray] = {} | |
| for i in order: | |
| if i not in sketches: | |
| continue | |
| shared: dict[int, int] = defaultdict(int) | |
| for h in sketches[i].tolist(): | |
| for j in inverted[h]: | |
| if j != i and j in kept_sets: | |
| shared[j] += 1 | |
| best = None | |
| for j, c in shared.items(): | |
| if c < SKETCH_MIN_SHARED: | |
| continue | |
| a, b = np.unique(shing[i]), kept_sets[j] | |
| inter = np.intersect1d(a, b, assume_unique=True).size | |
| union = a.size + b.size - inter | |
| jac = inter / union if union else 0.0 | |
| if jac >= JACCARD and (best is None or jac > best[1]): | |
| best = (j, jac) | |
| if best is not None: | |
| dropped[docs[i]["id"]] = (f"near-duplicate of {docs[best[0]]['id']} " | |
| f"at J={best[1]:.3f}") | |
| near += 1 | |
| if len(pair_examples) < 25: | |
| pair_examples.append({ | |
| "dropped": docs[i]["path"], "kept": docs[best[0]]["path"], | |
| "category": docs[i]["category"], "jaccard": round(best[1], 4)}) | |
| else: | |
| kept_sets[i] = np.unique(shing[i]) | |
| print(f" {near} near duplicates at J >= {JACCARD}") | |
| report["internal"] = { | |
| "exact_duplicates": exact, | |
| "near_duplicates": near, | |
| "removed_total": exact + near, | |
| "removed_percent": round(100.0 * (exact + near) / max(1, len(docs)), 3), | |
| "examples": pair_examples, | |
| } | |
| # ------------------------------------------------------------- rewrite pool | |
| by_shard: dict[str, list[dict]] = defaultdict(list) | |
| quarantine: list[dict] = [] | |
| for d in docs: | |
| rec = {k: v for k, v in d.items() if k != "_shard"} | |
| if d["id"] in dropped: | |
| rec.setdefault("provenance", {}) | |
| rec["provenance"] = dict(rec["provenance"] or {}) | |
| rec["provenance"]["quarantined"] = dropped[d["id"]] | |
| rec["provenance"]["quarantined_from"] = d["_shard"] | |
| quarantine.append(rec) | |
| else: | |
| by_shard[d["_shard"]].append(rec) | |
| counts = {"kept": sum(len(v) for v in by_shard.values()), "quarantined": len(quarantine)} | |
| print(f"\npool: {counts['kept']:,} kept, {counts['quarantined']:,} quarantined") | |
| report["pool_documents_out"] = counts["kept"] | |
| report["quarantined"] = counts["quarantined"] | |
| if not args.dry_run: | |
| for shard, recs in sorted(by_shard.items()): | |
| P.write_jsonl(os.path.join(args.repo, shard), recs) | |
| # shards emptied entirely still get written, so the file never silently | |
| # disappears from the tree | |
| for p in P.shard_paths(P.POOL_ROOT): | |
| rel = os.path.relpath(p, args.repo) | |
| if rel not in by_shard: | |
| P.write_jsonl(p, []) | |
| if quarantine: | |
| P.write_jsonl(os.path.join(P.POOL_ROOT, "_quarantine", "removed.jsonl"), | |
| quarantine) | |
| with open(os.path.join(P.POOL_ROOT, "dedupe-report.json"), "w") as f: | |
| json.dump(report, f, indent=2, ensure_ascii=False) | |
| f.write("\n") | |
| print(json.dumps({k: v for k, v in report.items() if k != "wikitext"}, | |
| indent=2)[:400]) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |