EllaNAM's picture
Add editable evaluation notebooks and their Python source
46e547f verified
Raw History Blame Contribute Delete
8.59 kB
"""Exact and near-duplicate detection with protected gold PIDs."""
from __future__ import annotations
import json
import re
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Literal
_TOKEN_RE = re.compile(r"(?u)\b\w+\b")
@dataclass(frozen=True)
class DedupStats:
input_rows: int
output_rows: int
exact_duplicate_edges: int
near_duplicate_edges: int
protected_gold_rows: int
class _DisjointSet:
def __init__(self) -> None:
self.parent: dict[int, int] = {}
self.rank: dict[int, int] = {}
def find(self, value: int) -> int:
parent = self.parent.setdefault(value, value)
if parent != value:
self.parent[value] = self.find(parent)
return self.parent[value]
def union(self, left: int, right: int) -> bool:
left_root, right_root = self.find(left), self.find(right)
if left_root == right_root:
return False
left_rank = self.rank.get(left_root, 0)
right_rank = self.rank.get(right_root, 0)
if left_rank < right_rank:
left_root, right_root = right_root, left_root
self.parent[right_root] = left_root
if left_rank == right_rank:
self.rank[left_root] = left_rank + 1
return True
def load_protected_gold_pids(qrels_path: str | Path) -> set[str]:
"""Read only ``gold`` PIDs; weak positives and negatives may be remapped."""
protected: set[str] = set()
with Path(qrels_path).open("r", encoding="utf-8") as stream:
for line_number, line in enumerate(stream, 1):
if not line.strip():
continue
row = json.loads(line)
gold = row.get("gold", [])
if not isinstance(gold, list):
raise ValueError(f"gold must be a list at qrels line {line_number}")
protected.update(str(pid) for pid in gold)
return protected
def _token_shingles(text: str, size: int) -> set[str]:
tokens = _TOKEN_RE.findall(text.casefold())
if not tokens:
return {""}
if len(tokens) < size:
return {" ".join(tokens)}
return {" ".join(tokens[offset : offset + size]) for offset in range(len(tokens) - size + 1)}
def _jaccard(left: set[str], right: set[str]) -> float:
union = left | right
return len(left & right) / len(union) if union else 1.0
def choose_component_representatives(
components: Iterable[list[int]],
pids: list[str],
protected_gold_pids: set[str],
) -> tuple[set[int], dict[str, str]]:
"""Keep every protected gold row and select a stable target for the rest."""
keep: set[int] = set()
remap: dict[str, str] = {}
for members in components:
ordered = sorted(members)
protected = [index for index in ordered if pids[index] in protected_gold_pids]
retained = protected if protected else ordered[:1]
keep.update(retained)
canonical = retained[0]
for index in ordered:
if index not in retained:
remap[pids[index]] = pids[canonical]
return keep, remap
def safe_deduplicate(
dataset: Any,
protected_gold_pids: set[str],
*,
text_column: str = "clean_text",
threshold: float = 0.92,
num_perm: int = 128,
shingle_size: int = 3,
near_scope: Literal["title", "global"] = "title",
) -> tuple[Any, dict[str, str], DedupStats]:
"""Deduplicate a HF Dataset while guaranteeing that gold PIDs survive.
Exact duplicates within one title are detected with ``xxh3_128``. Near-duplicate
candidates are produced by ``datasketch.MinHashLSH`` and then confirmed by
exact shingle Jaccard similarity, preventing LSH false positives from
deleting passages. ``near_scope='title'`` bounds RAM on the ordered psgs_w100
corpus by resetting the LSH at title boundaries; use ``global`` when enough
RAM (or a datasketch external storage customization) is available.
"""
if not 0.0 < threshold <= 1.0:
raise ValueError("threshold must be in (0, 1]")
if near_scope not in {"title", "global"}:
raise ValueError("near_scope must be 'title' or 'global'")
try:
import xxhash
from datasketch import MinHash, MinHashLSH
except ImportError as exc: # pragma: no cover - installation guard
raise RuntimeError(
"Install the wiki extra with pip install -e '.[wiki]'"
) from exc
pids = [str(pid) for pid in dataset["pid"]]
if len(set(pids)) != len(pids):
raise ValueError("input corpus contains duplicate pid values")
missing_gold = protected_gold_pids.difference(pids)
if missing_gold:
sample = sorted(missing_gold)[:10]
raise ValueError(f"qrels references missing corpus PIDs (sample): {sample}")
dsu = _DisjointSet()
exact_seen: dict[str, int] = {}
exact_edges = 0
near_edges = 0
template = MinHashLSH(threshold=threshold, num_perm=num_perm)
signature = MinHash(num_perm=num_perm)
global_lsh = template if near_scope == "global" else None
title_lsh = None
active_title: str | None = None
for index, row in enumerate(dataset.select_columns(["title", text_column])):
title = str(row["title"])
if near_scope == "title" and title != active_title:
active_title = title
title_lsh = MinHashLSH(num_perm=num_perm, params=(template.b, template.r))
text = str(row[text_column])
digest = xxhash.xxh3_128_hexdigest((title + "\0" + text).encode("utf-8"))
exact_index = exact_seen.get(digest)
if exact_index is not None:
# xxh3_128 collisions are extraordinarily unlikely, but comparison
# keeps the operation logically lossless.
other = dataset[exact_index]
if str(other["title"]) == title and str(other[text_column]) == text:
exact_edges += int(dsu.union(exact_index, index))
continue
else:
exact_seen[digest] = index
if near_scope == "title":
lsh = title_lsh
else:
lsh = global_lsh
assert lsh is not None
shingles = _token_shingles(text, shingle_size)
signature.clear()
signature.update_batch([shingle.encode("utf-8") for shingle in shingles])
for candidate_index in lsh.query(signature):
candidate = dataset[int(candidate_index)]
if str(candidate["title"]) != title:
continue
candidate_text = str(candidate[text_column])
candidate_shingles = _token_shingles(candidate_text, shingle_size)
if _jaccard(shingles, candidate_shingles) >= threshold:
near_edges += int(dsu.union(int(candidate_index), index))
lsh.insert(index, signature)
components_by_root: dict[int, list[int]] = defaultdict(list)
duplicate_members = set(dsu.parent)
for index in duplicate_members:
components_by_root[dsu.find(index)].append(index)
components = list(components_by_root.values())
keep_from_components, remap = choose_component_representatives(
components, pids, protected_gold_pids
)
keep_indices = [
index
for index in range(len(dataset))
if index not in duplicate_members or index in keep_from_components
]
deduplicated = dataset.select(keep_indices)
kept_pids = set(str(pid) for pid in deduplicated["pid"])
if not protected_gold_pids.issubset(kept_pids):
raise AssertionError("gold PID protection invariant failed")
if not set(remap.values()).issubset(kept_pids):
raise AssertionError("pid_remap contains a target absent from output")
if len(kept_pids) + len(remap) != len(pids):
raise AssertionError("every source PID must be either retained or remapped exactly once")
stats = DedupStats(
input_rows=len(dataset),
output_rows=len(deduplicated),
exact_duplicate_edges=exact_edges,
near_duplicate_edges=near_edges,
protected_gold_rows=len(protected_gold_pids),
)
return deduplicated, remap, stats
def write_pid_remap(remap: dict[str, str], output_path: str | Path) -> None:
path = Path(output_path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("w", encoding="utf-8") as stream:
json.dump(dict(sorted(remap.items())), stream, ensure_ascii=False, indent=2)
stream.write("\n")
temporary.replace(path)