Download scripts/contradiction_audit_lib.py from Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs: direct link, hf CLI and curl.
- Browser
- Download file 9.81 kB
-
https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/contradiction_audit_lib.py
- Command line
-
hf download hf://Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/scripts/contradiction_audit_lib.py
-
curl -L -o contradiction_audit_lib.py https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/contradiction_audit_lib.py
9.81 kB
| """Shared helpers for the GSM-IC-Adv / MATH-Adv LLM contradiction audit. | |
| Used by ``audit_contradictions_and_filter.py`` (full-corpus audit) and | |
| ``audit_contradictions_dose_reuse.py`` (dose-nesting reuse: skip the LLM call | |
| for any lower-dose twin whose injected distractors are a strict subset of an | |
| already-clean higher-dose twin). | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import re | |
| from pathlib import Path | |
| _SENT_SPLIT_RE = re.compile(r"(?<=[.!?])\s+") | |
| _NUM_RE = re.compile(r"-?\d+(?:\.\d+)?") | |
| _VERDICT_RE = re.compile(r"ANSWER:\s*([01])\b", re.IGNORECASE) | |
| def extract_verdict(text: str) -> "int | None": | |
| """Parse the adjudication verdict (0/1) from a wrapped adjudication | |
| response. | |
| The prompt is built via ``format_prompt(adj)``, which nests the | |
| adjudication instructions inside a generic "solve this problem, end with | |
| ANSWER: <number>" wrapper -- the model typically works through the | |
| ORIGINAL problem's arithmetic first (which can itself emit a stray | |
| "answer:"-like phrase colliding with a numbered list item, e.g. "the | |
| answer is:\\n1. ...") before giving the actual 0/1 verdict on the LAST | |
| line, per the adjudication template's explicit "end with exactly one | |
| line" instruction. ``causal_difficulty.llm_cache.extract_number`` takes | |
| the FIRST "ANSWER:" match in the text, which silently picks up that kind | |
| of false-positive intermediate match; this instead takes the LAST literal | |
| "ANSWER: 0" / "ANSWER: 1" occurrence, which empirically always contains | |
| the intended verdict.""" | |
| matches = _VERDICT_RE.findall(text) | |
| if not matches: | |
| return None | |
| return int(matches[-1]) | |
| def gold_for(base_id: str, gold_answers: list) -> "float | str | None": | |
| m = re.match(r"gsmic_adv-(\d+)$", base_id) or re.match(r"math_adv-(\d+)$", base_id) | |
| if not m: | |
| return None | |
| idx = int(m.group(1)) | |
| return gold_answers[idx] if idx < len(gold_answers) else None | |
| def split_sentences(text: str) -> list[str]: | |
| return [s.strip() for s in _SENT_SPLIT_RE.split(text.strip()) if s.strip()] | |
| def injected_sentences(base_text: str, twin_text: str) -> set[str]: | |
| """Sentence-level diff: twin sentences with no matching sentence in the | |
| base (exact match after whitespace normalization). Base sentences are | |
| inserted verbatim by the pipeline, so this recovers the injected | |
| distractor sentences regardless of where they were spliced in.""" | |
| base_sents = set(split_sentences(base_text)) | |
| return {s for s in split_sentences(twin_text) if s not in base_sents} | |
| def cache_key(prompt: str) -> str: | |
| return "contradiction_audit:" + hashlib.md5(prompt.encode()).hexdigest() | |
| _CALENDAR_WORDS = { | |
| "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", | |
| "january", "february", "march", "april", "may", "june", "july", "august", | |
| "september", "october", "november", "december", | |
| } | |
| def _normalize_entity(word: str) -> str: | |
| lw = word.lower() | |
| if lw.endswith("'s") or lw.endswith("’s"): | |
| return lw[:-2] | |
| return lw | |
| def _real_entity_collision(base_text: str, injected_text: str) -> bool: | |
| """Like ``causal_difficulty.features.collision.entity_collision``, but | |
| excludes day-of-week/month names from the shared-entity overlap. | |
| The underlying heuristic (any capitalized, non-sentence-initial word) has | |
| no notion of calendar words, so two GSM8K problems that both happen to | |
| mention e.g. "Tuesday" register as an entity collision even though there | |
| is zero referential ambiguity -- confirmed empirically on | |
| gsmic_adv_m9_4omini: 143 of 272 (52.6%) raw entity_collision hits were | |
| driven purely by calendar-word overlap, with real name reuse (e.g. | |
| "Sophia", "James", "John") in the rest.""" | |
| from causal_difficulty.features.collision import extract_entities | |
| overlap = extract_entities(base_text) & extract_entities(injected_text) | |
| return any(_normalize_entity(w) not in _CALENDAR_WORDS for w in overlap) | |
| def _gold_numeric(gold) -> "float | None": | |
| if gold is None: | |
| return None | |
| if isinstance(gold, (int, float)): | |
| return float(gold) | |
| try: | |
| return float(str(gold).replace(",", "")) | |
| except ValueError: | |
| return None | |
| #: Operators whose twin is produced by *transforming* the base's own sentences | |
| #: (rename / reorder / arithmetic rewrite) rather than by *injecting* new | |
| #: sentences. ``injected_sentences()`` diffs twin vs base sentences, so for a | |
| #: transform every twin sentence differs from the base and the whole twin is | |
| #: (incorrectly) read as "injected" -- making the entity/gold/multi-question | |
| #: collision checks spuriously flag genuinely clean No-Op twins. For these | |
| #: operators only the LLM No-Op adjudication is meaningful; structural checks | |
| #: are recorded for transparency but never used to drop (see App. noop-audit). | |
| TRANSFORM_OPERATORS = { | |
| "sentence_reorder", "entity_rename", "arithmetic_surface", | |
| "question_rephrase", "setup_reorder", "name_swap", | |
| } | |
| def structural_flags(base_text: str, twin_text: str, gold, operator: str | None = None) -> dict: | |
| """Free, local re-implementation of the repo's own No-Op structural | |
| checks (``noop_verification.py`` / ``noop_filtered_subset_check.py``): | |
| entity-name collision, unit-compatible quantity collision, gold-answer | |
| number collision, and multi-question collision. These catch exactly the | |
| failure modes the pipeline's "No-Op audit findings" fix (punctuation | |
| artifacts / entity-name collisions, commit 1db3712) targeted -- since the | |
| on-disk data predates that fix, applying these checks here is the | |
| equivalent of the fix for data already generated. | |
| ``operator`` is honoured: transforming operators (see | |
| ``TRANSFORM_OPERATORS``) are recorded but never drop, because the | |
| sentence-diff treats their whole twin as injected (spurious flags).""" | |
| from causal_difficulty.features.collision import unit_compatible_quantity_collision | |
| is_transform = operator is not None and operator in TRANSFORM_OPERATORS | |
| inj_sents = injected_sentences(base_text, twin_text) if not is_transform else set() | |
| inj_text = " ".join(inj_sents) | |
| multi_question = any("?" in s for s in inj_sents) | |
| ent_collision = _real_entity_collision(base_text, inj_text) | |
| unit_collision = unit_compatible_quantity_collision(base_text, inj_text) | |
| twin_numbers = [float(x) for x in _NUM_RE.findall(twin_text)] | |
| base_numbers_set = {float(x) for x in _NUM_RE.findall(base_text)} | |
| injected_numbers = [n for n in twin_numbers if n not in base_numbers_set] | |
| gnum = _gold_numeric(gold) | |
| gold_collision = gnum is not None and any(abs(n - gnum) < 1e-6 for n in injected_numbers) | |
| return { | |
| "multi_question_collision": multi_question, | |
| "entity_collision": ent_collision, | |
| # Recorded for transparency but NOT used to drop pairs: this heuristic treats | |
| # a shared number as "colliding" even when neither side has a recognized unit | |
| # word, so unrelated distractors collide by sheer numeric coincidence far more | |
| # than they create real ambiguity (confirmed empirically: it alone would flag | |
| # ~34% of gsmic_adv_m9_4omini, while the LLM adjudicator -- reasoning through | |
| # whether the correct answer actually changes -- found zero contradictions). | |
| "unit_compatible_quantity_collision": unit_collision, | |
| "gold_answer_collision": gold_collision, | |
| # Drop-triggering flags only: entity/gold-answer/multi-question collisions are | |
| # semantically specific (name reuse, the injected number matching the actual | |
| # correct answer, a foreign question competing for attention) rather than bare | |
| # numeric coincidence. | |
| "any_drop_flag": multi_question or ent_collision or gold_collision, | |
| } | |
| def adjudicate_pairs( | |
| pairs: list, | |
| gold_answers: list, | |
| *, | |
| model: str, | |
| provider: str, | |
| api_key: str, | |
| cache_path: Path, | |
| concurrency: int, | |
| ) -> dict[str, dict]: | |
| """Run the LLM No-Op/contradiction adjudicator on *pairs*. | |
| Returns ``{twin_id: {"verdict": "clean"|"contradiction"|"unparsed"|"no_gold", "raw": str|None}}``. | |
| """ | |
| import noop_verification as noop | |
| from causal_difficulty.llm_cache import ( | |
| format_prompt, load_cache, prefetch_cache_sync, save_cache, | |
| ) | |
| prompts: dict[str, str] = {} | |
| keyed: list[tuple[str, str | None]] = [] # (twin_id, cache_key or None) | |
| for p in pairs: | |
| gold = gold_for(p.base_id, gold_answers) | |
| if gold is None: | |
| keyed.append((p.twin_id, None)) | |
| continue | |
| adj = noop._ADJ_TEMPLATE.format(base=p.base_text, twin=p.twin_text, gold=gold) | |
| prompt = format_prompt(adj) | |
| key = cache_key(prompt) | |
| prompts[key] = prompt | |
| keyed.append((p.twin_id, key)) | |
| cache = load_cache(cache_path) | |
| stats = prefetch_cache_sync( | |
| prompts, provider=provider, api_key=api_key, model=model, | |
| cache=cache, cache_path=cache_path, concurrency=concurrency, | |
| ) | |
| save_cache(cache_path, cache) | |
| print(f" fetch stats: ok={stats.ok} cached={stats.cached} empty={stats.empty} " | |
| f"no_answer={stats.no_answer} truncated={stats.truncated} api_error={stats.api_error}") | |
| results: dict[str, dict] = {} | |
| for twin_id, key in keyed: | |
| if key is None: | |
| results[twin_id] = {"verdict": "no_gold", "raw": None} | |
| continue | |
| resp = cache.get(key) | |
| val = extract_verdict(resp) if resp else None | |
| if val is None: | |
| results[twin_id] = {"verdict": "unparsed", "raw": (resp[-200:] if resp else None)} | |
| continue | |
| results[twin_id] = { | |
| "verdict": "contradiction" if val == 1 else "clean", | |
| "raw": resp[-200:], | |
| } | |
| return results | |