#!/usr/bin/env python3 """Pre-registered confirmatory summary for the ImageNet long-run protocol v2.""" from __future__ import annotations import argparse import csv import json import math import sys import zlib from collections import defaultdict from pathlib import Path from typing import Any import numpy as np import yaml from scipy import stats PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from scripts.evaluate_imagenet_long import validate_official_eval REFERENCE_GATE = "relu6_self" EXPECTED_GATES = ( "relu6_self", "relu_self", "smooth_clipped_self", "relu6_only", "no_gate", ) ENTRY_GATE = "no_gate" DOWNSTREAM_GATES = ("relu6_only", "relu_self", "smooth_clipped_self") PRIMARY_GATES = (ENTRY_GATE, *DOWNSTREAM_GATES) METRICS = ("top1", "top5", "nll", "ece") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--protocol", type=Path, default=PROJECT_ROOT / "configs/imagenet_v2_protocol.yaml" ) parser.add_argument( "--runs-root", type=Path, default=Path("/nfs/ywang29/GmNet/runs/imagenet_v2") ) parser.add_argument("--output-dir", type=Path) parser.add_argument("--bootstrap-samples", type=int, default=2_000) parser.add_argument("--bootstrap-seed", type=int, default=250322841) parser.add_argument("--allow-incomplete", action="store_true") return parser.parse_args() def mean_std(values: list[float]) -> tuple[float, float]: array = np.asarray(values, dtype=np.float64) return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0 def paired_t_interval(differences: np.ndarray, confidence: float = 0.95) -> tuple[float, float]: differences = np.asarray(differences, dtype=np.float64) if differences.ndim != 1 or len(differences) < 2: raise ValueError("paired seed interval requires at least two one-dimensional differences") mean = float(differences.mean()) sem = float(stats.sem(differences)) if sem == 0.0: return mean, mean radius = float(stats.t.ppf((1.0 + confidence) / 2.0, len(differences) - 1)) * sem return mean - radius, mean + radius def one_sample_p_value( differences: np.ndarray, null: float, *, alternative: str ) -> float: """Return a finite seed-level t-test p-value, including zero-variance cases.""" differences = np.asarray(differences, dtype=np.float64) mean = float(differences.mean()) if np.all(differences == differences[0]): equal_to_null = math.isclose(mean, null, rel_tol=0.0, abs_tol=1e-12) if alternative == "greater": return 0.0 if mean > null and not equal_to_null else 1.0 if alternative == "less": return 0.0 if mean < null and not equal_to_null else 1.0 if alternative == "two-sided": return 1.0 if equal_to_null else 0.0 raise ValueError(f"unsupported alternative: {alternative}") return float( stats.ttest_1samp(differences, popmean=null, alternative=alternative).pvalue ) def primary_test(gate: str, differences: np.ndarray) -> dict[str, Any]: differences = np.asarray(differences, dtype=np.float64) ci_low, ci_high = paired_t_interval(differences) if gate == ENTRY_GATE: margin = -1.0 p_value = one_sample_p_value(differences, margin, alternative="less") decision_rule = "upper effect is below -1.0 pp" margin_pass = ci_high < margin test_kind = "one_sided_substantive_degradation" elif gate == "relu6_only": margin = -0.3 p_value = one_sample_p_value(differences, margin, alternative="greater") decision_rule = "lower effect is above -0.3 pp" margin_pass = ci_low > margin test_kind = "one_sided_operator_replacement_noninferiority" elif gate == "relu_self": lower, upper = -0.3, 0.3 p_lower = one_sample_p_value(differences, lower, alternative="greater") p_upper = one_sample_p_value(differences, upper, alternative="less") p_value = float(max(p_lower, p_upper)) decision_rule = "95% paired-seed CI lies inside [-0.3, +0.3] pp" margin_pass = ci_low > lower and ci_high < upper test_kind = "tost_practical_equivalence" elif gate == "smooth_clipped_self": margin = -0.2 p_value = one_sample_p_value(differences, margin, alternative="greater") decision_rule = "lower effect is above -0.2 pp" margin_pass = ci_low > margin test_kind = "one_sided_noninferiority" else: raise ValueError(f"no primary test registered for {gate}") return { "gate": gate, "reference": REFERENCE_GATE, "metric": "top1", "difference": float(differences.mean()), "seed_differences": [float(value) for value in differences], "seed_difference_std": float(differences.std(ddof=1)), "ci_low": ci_low, "ci_high": ci_high, "test": test_kind, "p_value": p_value, "alpha": 0.05, "margin_pass": bool(margin_pass), "decision_rule": decision_rule, } def apply_primary_gatekeeping(rows: list[dict[str, Any]]) -> None: by_gate = {row["gate"]: row for row in rows} entry = by_gate[ENTRY_GATE] entry_passed = entry["p_value"] < entry["alpha"] and entry["margin_pass"] entry.update( gatekeeping_stage="entry", holm_adjusted_p=entry["p_value"], confirmatory_tested=True, confirmatory_pass=bool(entry_passed), ) downstream = [by_gate[gate] for gate in DOWNSTREAM_GATES] holm_adjust(downstream) for row in downstream: row.update( gatekeeping_stage="downstream_holm", confirmatory_tested=bool(entry_passed), confirmatory_pass=bool( entry_passed and row["holm_adjusted_p"] < row["alpha"] and row["margin_pass"] ), ) def holm_adjust(rows: list[dict[str, Any]]) -> None: if any(not math.isfinite(float(row["p_value"])) for row in rows): raise ValueError("Holm family contains a non-finite p-value") order = sorted(range(len(rows)), key=lambda index: rows[index]["p_value"]) running = 0.0 total = len(rows) for position, index in enumerate(order): adjusted = min(1.0, (total - position) * rows[index]["p_value"]) running = max(running, adjusted) rows[index]["holm_adjusted_p"] = running rows[index]["holm_significant"] = running < 0.05 def hierarchical_top1_bootstrap( candidate: np.ndarray, reference: np.ndarray, *, draws: int, seed: int, ) -> tuple[float, float]: candidate = np.asarray(candidate, dtype=np.float64) reference = np.asarray(reference, dtype=np.float64) if candidate.shape != reference.shape or candidate.ndim != 2: raise ValueError("bootstrap arrays must match [seed, image]") seed_count, image_count = candidate.shape rng = np.random.default_rng(seed) values = np.empty(draws, dtype=np.float64) for draw in range(draws): seed_indices = rng.integers(0, seed_count, size=seed_count) image_indices = rng.integers(0, image_count, size=image_count) values[draw] = 100.0 * ( candidate[seed_indices][:, image_indices].mean() - reference[seed_indices][:, image_indices].mean() ) return tuple(float(value) for value in np.quantile(values, [0.025, 0.975])) def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: if not rows: raise ValueError(f"refusing to write empty table: {path}") fields: list[str] = [] for row in rows: for field in row: if field not in fields: fields.append(field) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fields) writer.writeheader() writer.writerows(rows) def load_confirmatory_tasks(protocol_path: Path) -> list[dict[str, Any]]: protocol = yaml.safe_load(protocol_path.read_text(encoding="utf-8")) primary = protocol.get("primary_analysis", {}) if primary.get("familywise_error_control") != "fixed_entry_gate_then_parallel_holm": raise ValueError("summary requires fixed-entry then parallel-Holm primary control") if primary.get("fixed_entry_gate", {}).get("candidate_gate") != ENTRY_GATE: raise ValueError("protocol entry gate does not match the summary implementation") downstream = primary.get("downstream_holm_family", {}).get("hypotheses", []) if tuple(item.get("candidate_gate") for item in downstream) != DOWNSTREAM_GATES: raise ValueError("protocol downstream primary family does not match the summary") tasks = [ task for task in protocol["tasks"] if str(task["role"]).startswith("confirmatory_") ] if len(tasks) != 15: raise ValueError(f"formal protocol must define 15 confirmatory tasks, got {len(tasks)}") return tasks def render_report( aggregate: list[dict[str, Any]], primary: list[dict[str, Any]], secondary: list[dict[str, Any]], ) -> str: lines = [ "# ImageNet Long-Run Protocol v2 Confirmatory Summary", "", "All values use fixed final `checkpoint_last.pt`; `checkpoint_best.pt` is rejected.", "Training seed is the primary statistical unit (n=3 per gate).", "", "## Aggregate", "", "| Gate | Top-1 | Top-5 | NLL | ECE |", "|---|---:|---:|---:|---:|", ] by_gate: dict[str, dict[str, Any]] = defaultdict(dict) for row in aggregate: by_gate[row["gate"]][row["metric"]] = row for gate in EXPECTED_GATES: values = by_gate[gate] cells = [] for metric in METRICS: row = values[metric] cells.append(f"{row['mean']:.4f} +/- {row['std']:.4f}") lines.append(f"| {gate} | " + " | ".join(cells) + " |") lines.extend( [ "", "## Primary Gatekeeping Family", "", "No-gate material loss is the fixed entry test. If it passes, ReLU6-only " "non-inferiority, ReLU equivalence, and corrected-smooth non-inferiority " "form a parallel three-test Holm family. One downstream failure does not " "suppress the other downstream tests.", "", "| Stage | Gate | Difference [95% seed CI] | Raw p | Holm p | Tested | Pass |", "|---|---|---:|---:|---:|---|---|", ] ) for row in primary: lines.append( f"| {row['gatekeeping_stage']} | {row['gate']} | {row['difference']:.4f} " f"[{row['ci_low']:.4f}, {row['ci_high']:.4f}] | {row['p_value']:.5g} | " f"{row['holm_adjusted_p']:.5g} | {row['confirmatory_tested']} | " f"{row['confirmatory_pass']} |" ) lines.extend( [ "", "## Interpretation Limits", "", "- A 50k-image hierarchical bootstrap is reported for sample sensitivity, but it does not replace n=3 seed uncertainty.", "- Top-5, NLL and ECE form one 12-test secondary family with Holm adjustment.", "- Corruption, frequency and deployment claims require their separately frozen datasets/runners and are not inferred here.", "- ReLU6-only is an operator/architecture ablation; it does not isolate spectral mixing or learned alignment as a unique causal path.", ] ) return "\n".join(lines) + "\n" def main() -> None: args = parse_args() if args.bootstrap_samples <= 0: raise ValueError("--bootstrap-samples must be positive") tasks = load_confirmatory_tasks(args.protocol.resolve()) records: list[dict[str, Any]] = [] correctness: dict[tuple[str, int], np.ndarray] = {} missing: list[str] = [] for task in tasks: run_dir = args.runs_root / task["task_id"] checkpoint = run_dir / "checkpoint_last.pt" official_eval = run_dir / "official_eval" if not checkpoint.is_file() or not official_eval.is_dir(): missing.append(str(run_dir)) continue result = validate_official_eval( official_eval, checkpoint_path=checkpoint, require_check_certificate=True, ) if result["gate_type"] != task["gate"] or int(result["seed"]) != int(task["seed"]): raise RuntimeError(f"task/result identity mismatch: {task['task_id']}") with np.load(official_eval / "per_sample.npz", allow_pickle=False) as arrays: correctness[(task["gate"], int(task["seed"]))] = arrays["correct"].copy() records.append( { "task_id": task["task_id"], "gate": task["gate"], "seed": int(task["seed"]), **{metric: float(result["metrics"][metric]) for metric in METRICS}, } ) if missing: if not args.allow_incomplete: raise FileNotFoundError(f"missing {len(missing)}/15 formal runs: {missing[:3]}") print(json.dumps({"status": "incomplete", "missing": missing}, indent=2)) return by_gate: dict[str, list[dict[str, Any]]] = defaultdict(list) for record in records: by_gate[record["gate"]].append(record) for gate in EXPECTED_GATES: seeds = sorted(record["seed"] for record in by_gate[gate]) if seeds != [0, 1, 2]: raise RuntimeError(f"{gate} does not contain matched seeds 0/1/2: {seeds}") by_gate[gate].sort(key=lambda row: row["seed"]) aggregate: list[dict[str, Any]] = [] for gate in EXPECTED_GATES: for metric in METRICS: mean, std = mean_std([row[metric] for row in by_gate[gate]]) aggregate.append( {"gate": gate, "metric": metric, "mean": mean, "std": std, "seeds": 3} ) reference = by_gate[REFERENCE_GATE] primary: list[dict[str, Any]] = [] secondary: list[dict[str, Any]] = [] for gate in PRIMARY_GATES: candidate = by_gate[gate] top1_difference = np.asarray( [candidate[index]["top1"] - reference[index]["top1"] for index in range(3)] ) row = primary_test(gate, top1_difference) candidate_correct = np.stack([correctness[(gate, seed)] for seed in range(3)]) reference_correct = np.stack( [correctness[(REFERENCE_GATE, seed)] for seed in range(3)] ) boot_low, boot_high = hierarchical_top1_bootstrap( candidate_correct, reference_correct, draws=args.bootstrap_samples, seed=args.bootstrap_seed + zlib.crc32(gate.encode("utf-8")), ) row["hierarchical_ci_low"] = boot_low row["hierarchical_ci_high"] = boot_high row["bootstrap_samples"] = args.bootstrap_samples primary.append(row) for metric in ("top5", "nll", "ece"): differences = np.asarray( [candidate[index][metric] - reference[index][metric] for index in range(3)] ) ci_low, ci_high = paired_t_interval(differences) p_value = one_sample_p_value( differences, 0.0, alternative="two-sided" ) secondary.append( { "gate": gate, "reference": REFERENCE_GATE, "metric": metric, "difference": float(differences.mean()), "ci_low": ci_low, "ci_high": ci_high, "p_value": p_value, } ) apply_primary_gatekeeping(primary) holm_adjust(secondary) output_dir = (args.output_dir or args.runs_root / "confirmatory_summary").resolve() output_dir.mkdir(parents=True, exist_ok=True) write_csv(output_dir / "aggregate.csv", aggregate) write_csv(output_dir / "primary_gatekeeping_holm.csv", primary) write_csv(output_dir / "secondary_holm.csv", secondary) payload = { "protocol": "imagenet-v2-confirmatory-summary-v2", "status": "complete_15_of_15", "checkpoint_policy": "fixed checkpoint_last only", "statistical_unit": "matched training seed", "seed_count": 3, "primary_family": primary, "secondary_holm_family": secondary, "aggregate": aggregate, } (output_dir / "results.json").write_text( json.dumps(payload, indent=2, allow_nan=False) + "\n", encoding="utf-8" ) (output_dir / "REPORT.md").write_text( render_report(aggregate, primary, secondary), encoding="utf-8" ) print(output_dir) if __name__ == "__main__": main()