"""Label-fidelity audit (claim C5). A shift is only valid if it is *label-preserving*. We verify this WITHOUT new human annotation using a local NLI model (DeBERTa-v3-MNLI): a paraphrase should be mutually entailing with its source; we drop pairs that flip. We report the flip rate so reviewers can see the shifts are clean. This is the standard "are your counterfactuals actually label-preserving?" defence. Zero API cost — the NLI model runs locally. """ from __future__ import annotations import numpy as np _NLI = None _NLI_LABELS = None # index order of {entailment, neutral, contradiction} def _get_nli(model_name: str = "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli"): global _NLI, _NLI_LABELS if _NLI is None: import torch from transformers import AutoModelForSequenceClassification, AutoTokenizer tok = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained(model_name) if torch.cuda.is_available(): model = model.to("cuda").half() model.eval() _NLI = (tok, model) _NLI_LABELS = model.config.id2label # {0:'entailment',...} varies by checkpoint return _NLI def _entail_prob(premises: list[str], hypotheses: list[str], batch_size: int = 32) -> np.ndarray: """P(entailment) for each (premise, hypothesis) pair.""" import torch tok, model = _get_nli() device = next(model.parameters()).device ent_idx = [i for i, v in _NLI_LABELS.items() if "entail" in v.lower()][0] probs = [] for i in range(0, len(premises), batch_size): enc = tok(premises[i:i + batch_size], hypotheses[i:i + batch_size], return_tensors="pt", padding=True, truncation=True, max_length=256).to(device) with torch.no_grad(): logits = model(**enc).logits.float() p = torch.softmax(logits, dim=-1)[:, ent_idx] probs.extend(p.cpu().numpy().tolist()) return np.asarray(probs) def paraphrase_keep_mask(originals: list[str], shifted: list[str], thresh: float = 0.5 ) -> np.ndarray: """Boolean mask: keep pairs that are mutually entailing (label preserved). TODO(4090): tune `thresh` on a small dev set of known paraphrases; report flip rate and a sensitivity curve over thresh in the paper appendix. """ fwd = _entail_prob(originals, shifted) bwd = _entail_prob(shifted, originals) keep = (fwd >= thresh) & (bwd >= thresh) return keep def audit(originals: list[str], shifted: list[str], thresh: float = 0.5) -> dict: keep = paraphrase_keep_mask(originals, shifted, thresh) return {"keep_mask": keep, "flip_rate": float(1.0 - keep.mean()), "n": len(originals)}