"""Dataset, repetition, scoring, and analysis helpers for Experiment 001D.""" from __future__ import annotations import hashlib import math import re from collections import Counter from fractions import Fraction from typing import Iterable, Mapping, Sequence NGRAM = 8 TAIL_WINDOW = 256 SPAN_WINDOW = 1024 SPAN_SEED = 24 def sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def question_id(question: str) -> str: normalized = " ".join(question.split()).lower() return hashlib.sha256(normalized.encode("utf-8")).hexdigest() def _ngrams(values: Sequence[int], n: int) -> list[tuple[int, ...]]: return [tuple(values[i : i + n]) for i in range(max(0, len(values) - n + 1))] def _longest_repeated_span(values: Sequence[int], window: int = SPAN_WINDOW) -> int: """Longest repeated non-overlapping exact token span inside a trailing window.""" tail = list(values[-window:]) if len(tail) < 2 * SPAN_SEED: return 0 earlier: dict[tuple[int, ...], int] = {} best = 0 limit = len(tail) - SPAN_SEED + 1 for start in range(limit): gram = tuple(tail[start : start + SPAN_SEED]) prior = earlier.get(gram) if prior is None: earlier[gram] = start continue if prior + SPAN_SEED > start: continue length = SPAN_SEED while start + length < len(tail) and prior + length < start: if tail[start + length] != tail[prior + length]: break length += 1 best = max(best, length) return best def repetition_metrics( token_ids: Sequence[int], decoded_text: str = "", *, tail_window: int = TAIL_WINDOW, span_window: int = SPAN_WINDOW, ) -> dict: """Measure exact recurrence, n-gram novelty, and answer progress together.""" tail = list(token_ids[-tail_window:]) grams = _ngrams(tail, NGRAM) seen: set[tuple[int, ...]] = set() duplicate_starts = 0 for gram in grams: if gram in seen: duplicate_starts += 1 else: seen.add(gram) fourgrams = _ngrams(tail, 4) unique_fourgram_ratio = len(set(fourgrams)) / max(len(fourgrams), 1) text_tail = decoded_text[-max(512, tail_window * 4) :].lower() marker = bool( re.search(r"\\boxed|\\fbox|final\s+answer|the\s+answer\s+is", text_tail) ) return { "tail_token_count": len(tail), "duplicate_8gram_fraction": duplicate_starts / max(len(grams), 1), "unique_4gram_ratio": unique_fourgram_ratio, "longest_repeated_exact_span": _longest_repeated_span(token_ids, span_window), "final_answer_marker_in_tail": marker, } def is_repetitive_prefix(metrics: Mapping, min_tokens: int = 128) -> bool: """Frozen candidate rule: independent recurrence, low novelty, and no answer.""" return ( int(metrics.get("tail_token_count", 0)) >= min_tokens and int(metrics.get("longest_repeated_exact_span", 0)) >= 64 and float(metrics.get("duplicate_8gram_fraction", 0.0)) >= 0.20 and float(metrics.get("unique_4gram_ratio", 1.0)) <= 0.65 and not bool(metrics.get("final_answer_marker_in_tail", False)) ) def _parse_exact_number(value: str) -> Fraction | None: value = value.strip().replace(",", "").replace("$", "") value = re.sub(r"\s*(?:dollars?|usd)\.?$", "", value, flags=re.IGNORECASE).strip() if not re.fullmatch(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:/[-+]?\d+)?", value): return None try: return Fraction(value) except (ValueError, ZeroDivisionError): return None def gold_number(answer_text: str) -> Fraction | None: marker = answer_text.rsplit("####", 1) value = marker[-1].strip() if len(marker) == 2 else answer_text.strip().splitlines()[-1] return _parse_exact_number(value) def extract_final_number(text: str) -> tuple[str | None, str | None]: """Return a boxed number or a number attached to an explicit final-answer cue.""" tail = text.split("")[-1] if "" in text else text boxes = list(re.finditer(r"\\boxed\s*\{\s*([^{}]+?)\s*\}", tail, flags=re.DOTALL)) if boxes: value = boxes[-1].group(1).strip() return value, "boxed" cues = list( re.finditer( r"(?:final\s+answer|the\s+answer\s+is|answer\s*[:=])\s*[^\d+-]*([-+]?(?:\d+(?:,\d{3})*(?:\.\d*)?|\.\d+)(?:/[-+]?\d+)?)", tail, flags=re.IGNORECASE, ) ) if cues: return cues[-1].group(1), "explicit_final_answer" return None, None def score_completion(text: str, gold_answer: str, finish_reason: str, natural_stop: bool) -> dict: raw_candidate, extraction = extract_final_number(text) predicted = _parse_exact_number(raw_candidate) if raw_candidate is not None else None gold = gold_number(gold_answer) valid_answer = predicted is not None and gold is not None correct = bool(valid_answer and predicted == gold) success = bool(correct and natural_stop) if not natural_stop and finish_reason == "length": status = "token_cap_unresolved" elif not natural_stop and finish_reason == "error": status = "technical_error" elif natural_stop and not valid_answer: status = "natural_stop_without_valid_answer" elif natural_stop and not correct: status = "natural_stop_incorrect_answer" else: status = "correct_natural_completion" return { "status": status, "natural_stop": bool(natural_stop), "valid_final_answer": bool(valid_answer), "correct_final_answer": bool(correct), "primary_success": bool(success), "predicted_raw": raw_candidate, "prediction_extraction": extraction, "gold_parseable": gold is not None, "finish_reason": finish_reason, } def bootstrap_mean(values: Sequence[float], *, seed: int, samples: int = 20_000) -> dict: if not values: return {"n": 0, "mean": None, "ci95": [None, None], "bootstrap_samples": samples} import random rng = random.Random(seed) n = len(values) means = [] for _ in range(samples): means.append(sum(values[rng.randrange(n)] for _ in range(n)) / n) means.sort() return { "n": n, "mean": sum(values) / n, "ci95": [means[int(0.025 * samples)], means[min(samples - 1, int(0.975 * samples))]], "bootstrap_samples": samples, "seed": seed, } def paired_primary_analysis(records: Sequence[Mapping], *, seed: int = 20261104) -> dict: """Question-clustered dynamic-minus-donor risk difference on repetitive prefixes.""" by_question: dict[str, dict[str, list[int]]] = {} for record in records: if record.get("prefix_class") != "repetitive": continue qid = str(record["question_id"]) condition = str(record["condition"]) if condition not in {"dynamic", "donor"}: continue by_question.setdefault(qid, {}).setdefault(condition, []).append( int(bool(record["primary_success"])) ) pairs = [] for qid, values in by_question.items(): if set(values) != {"dynamic", "donor"}: continue pairs.append({ "question_id": qid, "dynamic_success_rate": sum(values["dynamic"]) / len(values["dynamic"]), "donor_success_rate": sum(values["donor"]) / len(values["donor"]), "difference": sum(values["dynamic"]) / len(values["dynamic"]) - sum(values["donor"]) / len(values["donor"]), "dynamic_seed_n": len(values["dynamic"]), "donor_seed_n": len(values["donor"]), }) summary = bootstrap_mean([p["difference"] for p in pairs], seed=seed) summary.update({ "contrast": "authentic_dynamic_minus_donor_shuffled", "endpoint": "correct natural completion within frozen continuation budget", "unit": "source question cluster; seed outcomes averaged within question", "per_question": pairs, }) return summary