Datasets:
Download src/explicit_learning/contamination/match.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/contamination/match.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/contamination/match.py
-
curl -L -o match.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/contamination/match.py
10.8 kB
| """Decontamination matching: automatic rejection and a clean allowlist. | |
| ``docs/02_DATA_PIPELINE.md`` §5.2/§5.3 define two outcomes for every train | |
| candidate, measured against the frozen evaluation index: | |
| - ``REJECT_CONTAMINATION`` — an automatic, non-reviewable exclusion. | |
| - near-duplicate — automatically excluded and written to an immutable rejection | |
| report. There is no human override or re-admission path. | |
| The final allowlist is the train base_ids that are neither exact contamination | |
| nor near-duplicates. This fail-closed rule preserves the zero-per-example-human | |
| contract and cannot be relaxed to meet a quota. | |
| Thresholds are frozen here, not tuned to results (``docs/02`` §5.3). | |
| """ | |
| from __future__ import annotations | |
| from collections.abc import Mapping, Sequence | |
| from dataclasses import dataclass, field | |
| from typing import Any | |
| from ..atomic_io import atomic_write_jsonl | |
| from .fingerprints import estimated_jaccard, phash_hamming | |
| from .index import LoadedFingerprints, load_all | |
| # Frozen thresholds (docs/02 §5.3). | |
| PHASH_HAMMING_MAX = 4 | |
| OCR_JACCARD_MIN = 0.85 | |
| QUESTION_JACCARD_MIN = 0.90 | |
| REJECT = "REJECT_CONTAMINATION" | |
| NEAR_DUP = "NEAR_DUPLICATE" | |
| CLEAN = "CLEAN" | |
| class Match: | |
| """One near-duplicate match between a train item and an eval item.""" | |
| eval_base_id: str | |
| reason: str | |
| evidence: dict[str, Any] = field(default_factory=dict) | |
| class ItemDecision: | |
| """The decontamination verdict for one train base_id.""" | |
| base_id: str | |
| source: str | |
| outcome: str # REJECT | NEAR_DUPLICATE | CLEAN | |
| reject_reason: str | None = None | |
| matches: list[Match] = field(default_factory=list) | |
| class DecontaminationResult: | |
| rejected: list[ItemDecision] | |
| near_duplicates: list[ItemDecision] | |
| clean: list[ItemDecision] | |
| def allowlist_base_ids(self) -> list[str]: | |
| return sorted(d.base_id for d in self.clean) | |
| def _classify( | |
| train: LoadedFingerprints, | |
| eval_fps: Sequence[LoadedFingerprints], | |
| *, | |
| eval_image_shas: set[str], | |
| source_native_to_base: dict[str, str], | |
| eval_by_base: dict[str, LoadedFingerprints], | |
| canonical_q_to_bases: Mapping[str, Sequence[str]], | |
| ) -> ItemDecision: | |
| # --- auto-reject (docs/02 §5.2) --- | |
| shared_images = [sha for sha in train.image_sha256 if sha in eval_image_shas] | |
| if shared_images: | |
| return ItemDecision( | |
| base_id=train.base_id, | |
| source=train.source, | |
| outcome=REJECT, | |
| reject_reason="train image SHA-256 matches an eval image", | |
| ) | |
| # canonical question SHA-256 AND >=1 image SHA-256 both match the SAME eval item. | |
| if train.question_canonical_sha256 in canonical_q_to_bases: | |
| for eval_base in canonical_q_to_bases[train.question_canonical_sha256]: | |
| eval_fp = eval_by_base[eval_base] | |
| if train.image_sha256 and set(train.image_sha256) & set(eval_fp.image_sha256): | |
| return ItemDecision( | |
| base_id=train.base_id, | |
| source=train.source, | |
| outcome=REJECT, | |
| reject_reason=( | |
| "canonical question SHA-256 and an image SHA-256 both match " | |
| "the same eval item" | |
| ), | |
| ) | |
| if f"{train.source}\0{train.native_id}" in source_native_to_base: | |
| return ItemDecision( | |
| base_id=train.base_id, | |
| source=train.source, | |
| outcome=REJECT, | |
| reject_reason="source/native_id explicitly matches the evaluation registry", | |
| ) | |
| if train.derived_from_eval: | |
| return ItemDecision( | |
| base_id=train.base_id, | |
| source=train.source, | |
| outcome=REJECT, | |
| reject_reason="provenance states the row derives from an evaluation-only source", | |
| ) | |
| # --- near-duplicate queue (docs/02 §5.3) --- | |
| matches: list[Match] = [] | |
| seen_eval: set[str] = set() | |
| for eval_fp in eval_fps: | |
| if eval_fp.base_id in seen_eval: | |
| continue | |
| match = _near_dup_match(train, eval_fp) | |
| if match is not None: | |
| matches.append(match) | |
| seen_eval.add(eval_fp.base_id) | |
| if matches: | |
| matches.sort(key=lambda m: m.eval_base_id) | |
| return ItemDecision( | |
| base_id=train.base_id, source=train.source, outcome=NEAR_DUP, matches=matches | |
| ) | |
| return ItemDecision(base_id=train.base_id, source=train.source, outcome=CLEAN) | |
| def _near_dup_match(train: LoadedFingerprints, eval_fp: LoadedFingerprints) -> Match | None: | |
| # pHash Hamming distance <= 4 between any train image and any eval image. | |
| for t_hash in train.image_phash: | |
| for e_hash in eval_fp.image_phash: | |
| if phash_hamming(t_hash, e_hash) <= PHASH_HAMMING_MAX: | |
| return Match( | |
| eval_base_id=eval_fp.base_id, | |
| reason="phash_hamming_le_4", | |
| evidence={"train_phash": t_hash, "eval_phash": e_hash}, | |
| ) | |
| # OCR MinHash estimated Jaccard >= 0.85 (only when both sides have OCR text). | |
| if ( | |
| train.ocr_minhash | |
| and eval_fp.ocr_minhash | |
| and (estimated_jaccard(train.ocr_minhash, eval_fp.ocr_minhash) >= OCR_JACCARD_MIN) | |
| ): | |
| return Match(eval_base_id=eval_fp.base_id, reason="ocr_minhash_jaccard_ge_0.85") | |
| # question MinHash estimated Jaccard >= 0.90. | |
| if ( | |
| train.question_minhash | |
| and eval_fp.question_minhash | |
| and ( | |
| estimated_jaccard(train.question_minhash, eval_fp.question_minhash) | |
| >= QUESTION_JACCARD_MIN | |
| ) | |
| ): | |
| return Match(eval_base_id=eval_fp.base_id, reason="question_minhash_jaccard_ge_0.90") | |
| # question + choices nearly the same but image crop differs. | |
| if ( | |
| train.question_canonical_sha256 | |
| and train.question_canonical_sha256 == eval_fp.question_canonical_sha256 | |
| and train.choices_sha256 | |
| and train.choices_sha256 == eval_fp.choices_sha256 | |
| and set(train.image_sha256).isdisjoint(set(eval_fp.image_sha256)) | |
| ): | |
| return Match(eval_base_id=eval_fp.base_id, reason="same_question_choices_different_image") | |
| return None | |
| def decontaminate( | |
| train_fps: Sequence[LoadedFingerprints], | |
| eval_fps: Sequence[LoadedFingerprints], | |
| ) -> DecontaminationResult: | |
| """Classify every train item against the eval index.""" | |
| eval_by_base = {fp.base_id: fp for fp in eval_fps} | |
| eval_image_shas: set[str] = set() | |
| source_native_to_base: dict[str, str] = {} | |
| canonical_q_to_bases: dict[str, list[str]] = {} | |
| for fp in eval_fps: | |
| eval_image_shas.update(fp.image_sha256) | |
| source_native_to_base[f"{fp.source}\0{fp.native_id}"] = fp.base_id | |
| if fp.question_canonical_sha256: | |
| canonical_q_to_bases.setdefault(fp.question_canonical_sha256, []).append(fp.base_id) | |
| rejected: list[ItemDecision] = [] | |
| near_duplicates: list[ItemDecision] = [] | |
| clean: list[ItemDecision] = [] | |
| for train in sorted(train_fps, key=lambda f: f.base_id): | |
| decision = _classify( | |
| train, | |
| eval_fps, | |
| eval_image_shas=eval_image_shas, | |
| source_native_to_base=source_native_to_base, | |
| eval_by_base=eval_by_base, | |
| canonical_q_to_bases=canonical_q_to_bases, | |
| ) | |
| if decision.outcome == REJECT: | |
| rejected.append(decision) | |
| elif decision.outcome == NEAR_DUP: | |
| near_duplicates.append(decision) | |
| else: | |
| clean.append(decision) | |
| return DecontaminationResult(rejected=rejected, near_duplicates=near_duplicates, clean=clean) | |
| def _allowlist_rows(base_ids: Sequence[str], source_of: Mapping[str, str]) -> list[dict[str, Any]]: | |
| return [ | |
| {"base_id": bid, "source": source_of.get(bid, ""), "policy": "train_candidate"} | |
| for bid in sorted(base_ids) | |
| ] | |
| def _near_duplicate_rejection_rows( | |
| near_duplicates: Sequence[ItemDecision], | |
| ) -> list[dict[str, Any]]: | |
| rows: list[dict[str, Any]] = [] | |
| for decision in sorted(near_duplicates, key=lambda d: d.base_id): | |
| for match in decision.matches: | |
| rows.append( | |
| { | |
| "base_id": decision.base_id, | |
| "source": decision.source, | |
| "eval_base_id": match.eval_base_id, | |
| "reason": match.reason, | |
| "evidence": match.evidence, | |
| "status": "auto_rejected", | |
| } | |
| ) | |
| return rows | |
| def write_allowlist_and_review( | |
| result: DecontaminationResult, | |
| eval_base_ids: Sequence[str], | |
| *, | |
| allowlist_path: str | None = None, | |
| review_path: str | None = None, | |
| decisions: Mapping[str, str] | None = None, | |
| ) -> dict[str, Any]: | |
| """Write the allowlist and automatic near-duplicate rejects as JSONL. | |
| ``decisions`` is retained only to fail loudly for callers using the removed | |
| human-override API. No evaluation base_id or near-duplicate may ever enter | |
| the allowlist. | |
| """ | |
| if decisions is not None: | |
| raise ValueError( | |
| "per-example decontamination decisions are forbidden; " | |
| "near-duplicates are always auto-rejected" | |
| ) | |
| train_source = {d.base_id: d.source for d in result.clean + result.near_duplicates} | |
| allowlist_ids = list(result.allowlist_base_ids) | |
| eval_id_set = set(eval_base_ids) | |
| summary: dict[str, Any] = { | |
| "allowlist_count": len(allowlist_ids), | |
| "rejected_count": len(result.rejected), | |
| "near_duplicate_count": len(result.near_duplicates), | |
| "near_duplicates_auto_rejected": len(result.near_duplicates), | |
| "undecided_near_duplicates": 0, | |
| "eval_ids_in_allowlist": sum(1 for bid in allowlist_ids if bid in eval_id_set), | |
| } | |
| if allowlist_path is not None: | |
| atomic_write_jsonl(allowlist_path, _allowlist_rows(allowlist_ids, train_source)) | |
| if review_path is not None: | |
| atomic_write_jsonl(review_path, _near_duplicate_rejection_rows(result.near_duplicates)) | |
| return summary | |
| def decontaminate_dbs( | |
| train_db: str, | |
| eval_db: str, | |
| *, | |
| allowlist_path: str | None = None, | |
| review_path: str | None = None, | |
| decisions: Mapping[str, str] | None = None, | |
| ) -> dict[str, Any]: | |
| """Load both indexes, decontaminate, and write outputs. Returns the summary.""" | |
| eval_fps = load_all(eval_db) | |
| result = decontaminate(load_all(train_db), eval_fps) | |
| summary = write_allowlist_and_review( | |
| result, | |
| [fp.base_id for fp in eval_fps], | |
| allowlist_path=allowlist_path, | |
| review_path=review_path, | |
| decisions=decisions, | |
| ) | |
| summary["rejected"] = [ | |
| {"base_id": d.base_id, "reason": d.reject_reason} for d in result.rejected | |
| ] | |
| return summary | |