"""Frozen, calibration-only selection and paired analysis for Experiment 001B. This module has no inference dependencies. It expects the per-generation JSON records saved by the 001B runner and makes incomplete calibration coverage visible instead of ranking the surviving candidates. """ from __future__ import annotations from collections.abc import Iterable, Mapping, Sequence from typing import Any from paired_stats import paired_cluster_summary _NATURAL_FINISHES = {"stop", "eos", "end_of_sequence", "natural_stop"} _SCORABLE_STATUSES = {"correct", "incorrect"} _KNOWN_SCORE_STATUSES = _SCORABLE_STATUSES | {"unresolved", "unparsed", "error"} _DEFAULT_FORBIDDEN_CANDIDATES = {"base", "base_thinking", "base_no_thinking"} DEFAULT_CONDITIONS = ( "base", "edited", "published_constant", "independent_constant", "norm_matched_random", "rank1_activation_dependent", ) def _record_key(record: Mapping[str, Any]) -> tuple[int, int]: return int(record["source_row"]), int(record["seed"]) def _score_status(record: Mapping[str, Any]) -> str | None: score = record.get("score") if not isinstance(score, Mapping): return None value = score.get("status") return str(value) if value is not None else None def _score_issue(record: Mapping[str, Any]) -> str | None: """Return a data/scoring error instead of silently awarding model no-credit. The frozen grader emits one of: correct, incorrect, unresolved, unparsed, or error, with a matching tri-state ``correct`` value. Missing or inconsistent fields are malformed score records. """ score = record.get("score") if not isinstance(score, Mapping): return "missing_score_object" status = score.get("status") if not isinstance(status, str) or status not in _KNOWN_SCORE_STATUSES: return "unknown_or_missing_score_status" correct = score.get("correct", _MISSING) if correct is _MISSING: return "missing_correct_flag" if status == "correct" and correct is not True: return "correct_status_mismatch" if status == "incorrect" and correct is not False: return "incorrect_status_mismatch" if status in {"unresolved", "unparsed", "error"} and correct is not None: return "unscorable_status_mismatch" return None _MISSING = object() def _record_problem(record: Mapping[str, Any]) -> str | None: if record.get("error"): return "technical_error" issue = _score_issue(record) if issue is not None: return f"scoring_error:{issue}" if _score_status(record) == "error": score = record.get("score") detail = score.get("error") if isinstance(score, Mapping) else None return f"scoring_error:{detail or 'grader_error_status'}" return None def record_validation_issue(record: Mapping[str, Any]) -> str | None: """Public record-integrity check used by analysis summaries and CSV output.""" return _record_problem(record) def _is_natural_completion(record: Mapping[str, Any]) -> bool: if record.get("truncated") is True: return False reason = str(record.get("finish_reason", "")).lower() if reason in _NATURAL_FINISHES: return True return bool(record.get("stopped_on_eos", False)) def _capped_length(record: Mapping[str, Any] | None, max_new_tokens: int) -> int: if record is None: return max_new_tokens value = record.get("tokens", record.get("token_count")) if value is None: return max_new_tokens return min(max_new_tokens, max(0, int(value))) def select_calibration_winners( records_by_candidate: Mapping[str, Iterable[Mapping[str, Any]]], families: Mapping[str, Sequence[str]], expected_question_seeds: Sequence[tuple[int, int]], *, max_new_tokens: int, forbidden_candidates: Iterable[str] = _DEFAULT_FORBIDDEN_CANDIDATES, ) -> dict[str, Any]: """Select one fully observed candidate per family using calibration only. Ranking, from best to worst: maximize verified solves; maximize natural completions; minimize unscorable outputs; minimize mean capped generated length; lexical candidate ID. Any missing record, technical error, or malformed grade blocks that whole family (no fallback winner); callers should resume the run or report the family incomplete. A base comparator cannot be a candidate. """ if max_new_tokens <= 0: raise ValueError("max_new_tokens must be positive") if not expected_question_seeds: raise ValueError("expected_question_seeds cannot be empty") expected = [(int(row), int(seed)) for row, seed in expected_question_seeds] if len(expected) != len(set(expected)): raise ValueError("expected question/seed keys must be unique") forbidden = set(forbidden_candidates) indexed: dict[str, dict[tuple[int, int], Mapping[str, Any]]] = {} for candidate, records in records_by_candidate.items(): if candidate in forbidden or candidate.lower() in forbidden: raise ValueError(f"Comparator {candidate!r} cannot be a calibration candidate") by_key: dict[tuple[int, int], Mapping[str, Any]] = {} for record in records: key = _record_key(record) if key in by_key: raise ValueError(f"Duplicate calibration record for {candidate}/{key}") if record.get("candidate_id", candidate) != candidate: raise ValueError(f"Record candidate_id disagrees with mapping key: {candidate}/{key}") by_key[key] = record extra = set(by_key) - set(expected) if extra: raise ValueError(f"Unexpected calibration keys for {candidate}: {sorted(extra)}") indexed[candidate] = by_key all_family_candidates = {candidate for values in families.values() for candidate in values} if not all_family_candidates: raise ValueError("families must contain at least one candidate") if sum(len(values) for values in families.values()) != len(all_family_candidates): raise ValueError("a candidate ID cannot appear in multiple calibration families") if all_family_candidates & forbidden: raise ValueError("Base/comparator cannot be selected in a family") missing_candidate_records = all_family_candidates - set(indexed) family_results: dict[str, Any] = {} for family, candidates_seq in families.items(): candidates = list(candidates_seq) if not candidates or len(candidates) != len(set(candidates)): raise ValueError(f"Family {family!r} must list unique candidates") candidate_metrics: dict[str, Any] = {} family_blockers: list[str] = [] for candidate in candidates: by_key = indexed.get(candidate, {}) missing = sorted(set(expected) - set(by_key)) error_keys = sorted( key for key, record in by_key.items() if _record_problem(record) == "technical_error" ) score_error_keys = sorted( key for key, record in by_key.items() if _record_problem(record) is not None and _record_problem(record) != "technical_error" ) if candidate in missing_candidate_records: family_blockers.append(f"missing_candidate:{candidate}") if missing: family_blockers.append(f"missing_records:{candidate}") if error_keys: family_blockers.append(f"technical_errors:{candidate}") if score_error_keys: family_blockers.append(f"scoring_errors:{candidate}") solves = sum( key in by_key and _record_problem(by_key[key]) is None and _score_status(by_key[key]) == "correct" for key in expected ) natural = sum(_is_natural_completion(by_key[key]) for key in expected if key in by_key) unscorable = sum( _score_status(by_key.get(key, {})) not in _SCORABLE_STATUSES for key in expected ) lengths = [_capped_length(by_key.get(key), max_new_tokens) for key in expected] candidate_metrics[candidate] = { "n_expected": len(expected), "n_recorded": len(by_key), "n_missing": len(missing), "missing_question_seeds": [list(key) for key in missing], "n_technical_errors": len(error_keys), "technical_error_question_seeds": [list(key) for key in error_keys], "n_scoring_errors": len(score_error_keys), "scoring_error_question_seeds": [list(key) for key in score_error_keys], "solves": solves, "natural_completions": natural, "unscorable": unscorable, "mean_capped_tokens": sum(lengths) / len(expected), "complete": not missing and not error_keys and not score_error_keys and candidate in indexed, } complete = not family_blockers winner = None if complete: winner = min( candidates, key=lambda candidate: ( -candidate_metrics[candidate]["solves"], -candidate_metrics[candidate]["natural_completions"], candidate_metrics[candidate]["unscorable"], candidate_metrics[candidate]["mean_capped_tokens"], candidate, ), ) family_results[family] = { "status": "selected" if complete else "incomplete", "selected_candidate_id": winner, "blockers": sorted(set(family_blockers)), "candidates": candidate_metrics, "selection_rule": [ "maximize solves", "maximize natural completions", "minimize unscorable outputs", "minimize mean capped generated tokens", "lexical candidate ID", ], "selection_source": "calibration only", } return { "phase": "calibration", "max_new_tokens": max_new_tokens, "expected_question_seeds": [list(key) for key in expected], "families": family_results, "base_is_comparator_only": True, "heldout_used_for_selection": False, } def collect_paired_outcomes( records: Iterable[Mapping[str, Any]], condition: str, candidate_id: str | None = None, ) -> tuple[dict[int, dict[int, bool]], dict[tuple[int, int], str]]: """Index one condition's valid records; return technical/scoring exclusions too.""" outcomes: dict[int, dict[int, bool]] = {} excluded: dict[tuple[int, int], str] = {} seen: set[tuple[int, int]] = set() for record in records: if record.get("condition") != condition: continue if candidate_id is not None and record.get("candidate_id") != candidate_id: continue key = _record_key(record) if key in seen: raise ValueError(f"Duplicate heldout record for {condition}/{key}") seen.add(key) question, seed = key outcomes.setdefault(question, {}) problem = _record_problem(record) if problem is not None: excluded[key] = problem continue status = _score_status(record) # For author-aligned solve-by-cap accuracy, non-completion and # unscorable model outputs are no-credit outcomes, not technical errors. outcomes[question][seed] = status == "correct" or ( isinstance(record.get("score"), Mapping) and record["score"].get("correct") is True ) return outcomes, excluded def paired_heldout_summary( records: Iterable[Mapping[str, Any]], first_condition: str, comparator_condition: str, expected_question_seeds: Sequence[tuple[int, int]], *, first_candidate_id: str | None = None, comparator_candidate_id: str | None = None, bootstrap_seed: int = 14353, bootstrap_samples: int = 10_000, ) -> dict[str, Any]: """Compare two heldout conditions and expose every missing/error pair.""" if first_condition == comparator_condition: raise ValueError("first_condition and comparator_condition must differ") expected_list = [(int(question), int(seed)) for question, seed in expected_question_seeds] if len(expected_list) != len(set(expected_list)): raise ValueError("expected_question_seeds must be unique") rows = list(records) first, first_errors = collect_paired_outcomes(rows, first_condition, first_candidate_id) comparator, comparator_errors = collect_paired_outcomes( rows, comparator_condition, comparator_candidate_id ) expected = set(expected_list) first_keys = {(question, seed) for question, seeds in first.items() for seed in seeds} comparator_keys = {(question, seed) for question, seeds in comparator.items() for seed in seeds} first_present = first_keys | set(first_errors) comparator_present = comparator_keys | set(comparator_errors) unexpected = (first_present | comparator_present) - expected if unexpected: raise ValueError(f"Unexpected heldout question/seed keys: {sorted(unexpected)}") matched_keys = sorted((first_keys & comparator_keys) & expected) first_map: dict[int, dict[int, bool]] = {} comparator_map: dict[int, dict[int, bool]] = {} for question, seed in matched_keys: first_map.setdefault(question, {})[seed] = first[question][seed] comparator_map.setdefault(question, {})[seed] = comparator[question][seed] summary = paired_cluster_summary( first_map, comparator_map, bootstrap_seed=bootstrap_seed, bootstrap_samples=bootstrap_samples, ) incomplete = [] for key in sorted(expected): missing = [] if key not in first_present: missing.append(first_condition) if key not in comparator_present: missing.append(comparator_condition) reasons = { first_condition: first_errors.get(key), comparator_condition: comparator_errors.get(key), } if missing or any(reasons.values()): technical = { name: value for name, value in reasons.items() if value == "technical_error" } item = { "source_row": key[0], "seed": key[1], "missing_conditions": missing, "technical_errors": technical, } scoring = { name: value for name, value in reasons.items() if value and value != "technical_error" } if technical: item["technical_errors"] = technical if scoring: item["scoring_errors"] = scoring incomplete.append(item) summary.update( { "first_condition": first_condition, "comparator_condition": comparator_condition, "first_candidate_id": first_candidate_id, "comparator_candidate_id": comparator_candidate_id, "expected_generation_pairs": len(expected), "complete_matched_generation_pairs": len(matched_keys), "incomplete_pairs": incomplete, "analysis_uses_only_complete_pairs": True, "endpoint": "verified correct final answer; unresolved and unparsed are no-credit", } ) if len(matched_keys) != len(expected): summary["question_bootstrap_percentile_95"] = None summary["exact_mcnemar_two_sided_p"] = None summary["inference_suppressed"] = ( "Missing, technical-error, or scoring-error pairs make complete-case inferential summaries unsafe; report the matched counts descriptively." ) return summary def summarize_experiment_001b_contrasts( records: Iterable[Mapping[str, Any]], expected_question_seeds: Sequence[tuple[int, int]], condition_config_ids: Mapping[str, str] | None = None, *, bootstrap_seed: int = 14353, bootstrap_samples: int = 10_000, ) -> dict[str, Any]: """Build the frozen primary and explicitly exploratory 001B contrasts. The single prespecified contrast is edited checkpoint vs the calibration-selected published-constant direction. Remaining comparisons are diagnostics or intervention-vs-base summaries and their p-values are exploratory and unadjusted for multiplicity. """ ids = dict(condition_config_ids or {}) rows = list(records) def summarize(first: str, comparator: str) -> dict[str, Any]: return paired_heldout_summary( rows, first, comparator, expected_question_seeds, first_candidate_id=ids.get(first, first), comparator_candidate_id=ids.get(comparator, comparator), bootstrap_seed=bootstrap_seed, bootstrap_samples=bootstrap_samples, ) base_conditions = [ "edited", "published_constant", "independent_constant", "norm_matched_random", "rank1_activation_dependent", ] diagnostics = { "rank1_activation_dependent_minus_published_constant": ( "rank1_activation_dependent", "published_constant", ), "rank1_activation_dependent_minus_norm_matched_random": ( "rank1_activation_dependent", "norm_matched_random", ), "edited_minus_rank1_activation_dependent": ( "edited", "rank1_activation_dependent", ), } return { "plan": { "primary": "edited_minus_published_constant", "primary_definition": ( "edited checkpoint vs the published_constant candidate selected using calibration only" ), "other_comparisons": "exploratory; p-values are unadjusted and not confirmatory", "small_heldout_note": ( "Ten heldout questions support a mechanism screen only; do not claim population accuracy effects or equivalence." ), }, "primary_prespecified": { "comparison_id": "edited_minus_published_constant", "first_condition": "edited", "comparator_condition": "published_constant", "summary": summarize("edited", "published_constant"), }, "exploratory_vs_base_unadjusted": { f"{condition}_minus_base": summarize(condition, "base") for condition in base_conditions }, "exploratory_diagnostic_pairs_unadjusted": { comparison_id: { "first_condition": pair[0], "comparator_condition": pair[1], "summary": summarize(*pair), } for comparison_id, pair in diagnostics.items() }, } __all__ = [ "DEFAULT_CONDITIONS", "collect_paired_outcomes", "paired_heldout_summary", "record_validation_issue", "select_calibration_winners", "summarize_experiment_001b_contrasts", ]