File size: 9,813 Bytes
a0d1de2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | """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
|