#!/usr/bin/env python3 """Aggregate E3 CIFAR-100 evaluations and paired ReLU6 comparisons.""" from __future__ import annotations import argparse import csv import json import math import os import re import sys import zlib from collections import defaultdict from pathlib import Path from typing import Any import numpy as np PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from gmnet.evaluation import CORRUPTION_SPECS, paired_hierarchical_bootstrap PROTOCOL_VERSION = "e3-cifar100-corruptions-v1" GATES = ("relu6", "relu", "gelu", "smooth_static", "identity", "no_gate") SEEDS = (0, 1, 2) CONDITIONS = tuple(CORRUPTION_SPECS) RUN_PATTERN = re.compile(r"e3_c100_s1_(relu6|relu|gelu|smooth_static|identity|no_gate)_seed(\d+)$") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--runs-root", default="/tmp/gmnet_runs/e3_cifar100") parser.add_argument("--output-dir", default=None) parser.add_argument("--bootstrap-samples", type=int, default=2000) parser.add_argument("--bootstrap-seed", type=int, default=250322841) parser.add_argument("--allow-incomplete", action="store_true") parser.add_argument("--overwrite", action="store_true") return parser.parse_args() def discover_runs(root: Path, allow_incomplete: bool) -> dict[tuple[str, int], dict[str, Any]]: runs: dict[tuple[str, int], dict[str, Any]] = {} for directory in sorted(root.glob("e3_c100_s1_*_seed*")): match = RUN_PATTERN.fullmatch(directory.name) result_path = directory / "evaluation" / "results.json" if not match or not result_path.is_file(): continue gate, seed_text = match.groups() result = json.loads(result_path.read_text(encoding="utf-8")) if result["protocol_version"] != PROTOCOL_VERSION: raise ValueError(f"protocol mismatch in {result_path}") if result["partial_evaluation"] and not allow_incomplete: raise ValueError(f"partial evaluation cannot be aggregated: {result_path}") if not result["complete_training_required"] and not allow_incomplete: raise ValueError(f"incomplete-training evaluation cannot be aggregated: {result_path}") key = (gate, int(seed_text)) if key in runs: raise ValueError(f"duplicate run: {key}") runs[key] = {"directory": directory, "result": result} expected = {(gate, seed) for gate in GATES for seed in SEEDS} missing = sorted(expected - set(runs)) if missing and not allow_incomplete: raise FileNotFoundError(f"missing complete evaluations: {missing}") return runs def aggregate_metrics(runs: dict[tuple[str, int], dict[str, Any]]) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] for gate in GATES: gate_runs = [runs[(gate, seed)]["result"] for seed in SEEDS if (gate, seed) in runs] if not gate_runs: continue for metric in ( "clean_top1", "clean_top5", "clean_nll", "clean_ece", "mean_corruption_top1", "mean_corruption_nll", "mean_corruption_ece", "retention", ): values = np.asarray([run["overall"][metric] for run in gate_runs], dtype=np.float64) rows.append( { "gate": gate, "scope": "overall", "condition": "all", "metric": metric, "mean": float(values.mean()), "std": float(values.std(ddof=1)) if len(values) > 1 else math.nan, "seeds": len(values), } ) for condition in CONDITIONS: for metric in ("top1", "top5", "nll", "ece"): values = np.asarray( [run["conditions"][condition][metric] for run in gate_runs], dtype=np.float64, ) rows.append( { "gate": gate, "scope": "condition", "condition": condition, "metric": metric, "mean": float(values.mean()), "std": float(values.std(ddof=1)) if len(values) > 1 else math.nan, "seeds": len(values), } ) return rows def load_per_sample(path: Path) -> tuple[dict[str, np.ndarray], np.ndarray]: values = { "correct": np.full((len(CONDITIONS), 10_000), -1, dtype=np.int8), "top5_correct": np.full((len(CONDITIONS), 10_000), -1, dtype=np.int8), "nll": np.full((len(CONDITIONS), 10_000), np.nan, dtype=np.float32), } targets = np.full((len(CONDITIONS), 10_000), -1, dtype=np.int16) condition_index = {name: index for index, name in enumerate(CONDITIONS)} with path.open(newline="", encoding="utf-8") as handle: for row in csv.DictReader(handle): condition = row["condition"] if condition not in condition_index: continue index = int(row["sample_index"]) ci = condition_index[condition] if values["correct"][ci, index] != -1: raise ValueError(f"duplicate correctness row: {path}, {condition}, {index}") values["correct"][ci, index] = int(row["correct"]) values["top5_correct"][ci, index] = int(row["top5_correct"]) values["nll"][ci, index] = float(row["nll"]) targets[ci, index] = int(row["target"]) if ( (values["correct"] < 0).any() or (values["top5_correct"] < 0).any() or not np.isfinite(values["nll"]).all() or (targets < 0).any() ): raise ValueError(f"incomplete per-sample correctness: {path}") if not np.all(targets == targets[0]): raise ValueError(f"targets differ across conditions: {path}") return values, targets[0] def paired_comparisons( runs: dict[tuple[str, int], dict[str, Any]], samples: int, seed: int ) -> list[dict[str, Any]]: arrays: dict[str, dict[str, list[np.ndarray]]] = defaultdict( lambda: defaultdict(list) ) reference_targets: np.ndarray | None = None for gate in GATES: for training_seed in SEEDS: if (gate, training_seed) not in runs: continue path = runs[(gate, training_seed)]["directory"] / "evaluation" / "per_sample_correctness.csv" sample_values, targets = load_per_sample(path) if reference_targets is None: reference_targets = targets elif not np.array_equal(targets, reference_targets): raise ValueError(f"sample targets do not align: {path}") for metric, values in sample_values.items(): arrays[gate][metric].append(values) if "relu6" not in arrays: raise ValueError("ReLU6 reference evaluations are required") statistics_top1 = { "clean_top1": "clean_top1", "mean_corruption_top1": "mean_corruption_top1", "retention": "retention", **{ f"top1_{condition}": f"condition:{index}" for index, condition in enumerate(CONDITIONS) }, } statistics_top5 = { "clean_top5": "clean_top1", "mean_corruption_top5": "mean_corruption_top1", **{ f"top5_{condition}": f"condition:{index}" for index, condition in enumerate(CONDITIONS) }, } statistics_nll = { "clean_nll": "clean_raw_mean", "mean_corruption_nll": "mean_corruption_raw_mean", **{ f"nll_{condition}": f"condition_raw:{index}" for index, condition in enumerate(CONDITIONS) }, } rows: list[dict[str, Any]] = [] for gate in GATES: if gate == "relu6" or gate not in arrays: continue candidate_top1 = np.stack(arrays[gate]["correct"]) reference_top1 = np.stack(arrays["relu6"]["correct"]) if candidate_top1.shape != reference_top1.shape: if len(candidate_top1) != len(reference_top1): if not all((gate, value) in runs and ("relu6", value) in runs for value in SEEDS): continue raise ValueError(f"candidate/reference shape mismatch for {gate}") gate_seed = seed + zlib.crc32(gate.encode()) comparison_groups = [ ( paired_hierarchical_bootstrap( candidate_top1, reference_top1, statistics=statistics_top1, samples=samples, seed=gate_seed, ), "percentage_points", ), ( paired_hierarchical_bootstrap( np.stack(arrays[gate]["top5_correct"]), np.stack(arrays["relu6"]["top5_correct"]), statistics=statistics_top5, samples=samples, seed=gate_seed + 1, ), "percentage_points", ), ( paired_hierarchical_bootstrap( np.stack(arrays[gate]["nll"]), np.stack(arrays["relu6"]["nll"]), statistics=statistics_nll, samples=samples, seed=gate_seed + 2, ), "nll", ), ] for comparisons, unit in comparison_groups: for comparison in comparisons: comparison.update( gate=gate, reference="relu6", unit=unit, significant=bool( comparison["ci_low"] > 0.0 or comparison["ci_high"] < 0.0 ), ) rows.append(comparison) return rows def aggregate_smooth_clips( runs: dict[tuple[str, int], dict[str, Any]] ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any] | None]: block_rows: list[dict[str, Any]] = [] diagnostics = [] for seed in SEEDS: if ("smooth_static", seed) not in runs: continue result = runs[("smooth_static", seed)]["result"] diagnostic = result.get("smooth_clip_diagnostics") if not diagnostic: raise ValueError(f"missing smooth clip diagnostics for seed {seed}") diagnostics.append(diagnostic) for block in diagnostic["blocks"]: block_rows.append({"seed": seed, **block}) if not diagnostics: return [], [], None stage_rows: list[dict[str, Any]] = [] for stage in sorted({int(row["stage"]) for row in block_rows}): selected = [row for row in block_rows if int(row["stage"]) == stage] per_seed_means = [] for seed in sorted({int(row["seed"]) for row in selected}): values = [float(row["mean"]) for row in selected if int(row["seed"]) == seed] per_seed_means.append(float(np.mean(values))) stage_rows.append( { "stage": stage, "mean": float(np.mean(per_seed_means)), "std_across_seeds": float(np.std(per_seed_means, ddof=1)) if len(per_seed_means) > 1 else math.nan, "min_across_blocks_seeds": min(float(row["min"]) for row in selected), "max_across_blocks_seeds": max(float(row["max"]) for row in selected), "blocks_per_seed": len(selected) // len(per_seed_means), "seeds": len(per_seed_means), } ) minimum = min(float(row["min"]) for row in block_rows) initial = float(diagnostics[0]["initial_clip"]) severe_threshold = float(diagnostics[0]["severe_collapse_threshold"]) strict_threshold = float(diagnostics[0]["strict_boundary_threshold"]) check = { "initial_clip": initial, "global_mean": float(np.mean([float(row["mean"]) for row in block_rows])), "global_min": minimum, "global_max": max(float(row["max"]) for row in block_rows), "strict_boundary_threshold": strict_threshold, "severe_collapse_threshold": severe_threshold, "near_min_boundary": bool(minimum <= strict_threshold), "below_10pct_initial": bool(minimum <= severe_threshold), "phase2_boundary_check_pass": bool(minimum > severe_threshold), } return block_rows, stage_rows, check def find_metric( rows: list[dict[str, Any]], gate: str, metric: str ) -> dict[str, Any]: return next( row for row in rows if row["gate"] == gate and row["scope"] == "overall" and row["metric"] == metric ) def find_comparison( rows: list[dict[str, Any]], gate: str, metric: str ) -> dict[str, Any] | None: return next( (row for row in rows if row["gate"] == gate and row["metric"] == metric), None ) def pm(mean: float, std: float) -> str: return f"{mean:.2f} +/- {std:.2f}" def report( aggregate: list[dict[str, Any]], comparisons: list[dict[str, Any]], samples: int, clip_stages: list[dict[str, Any]], clip_check: dict[str, Any] | None, ) -> str: available = [gate for gate in GATES if any(row["gate"] == gate for row in aggregate)] lines = [ "# E3 CIFAR-100 Gate Screening", "", "Results are mean +/- sample standard deviation across three training seeds.", "Every run is evaluated at fixed epoch 100 from checkpoint_last.pt; no", "test-set best-checkpoint selection is used.", "Corruption comparisons use a hierarchical paired bootstrap over matched training", "seeds and the same 10,000 CIFAR-100 test samples.", "", "| Gate | Clean top-1 | Clean top-5 | NLL | ECE | Mean corruption top-1 | Retention |", "|---|---:|---:|---:|---:|---:|---:|", ] for gate in available: metrics = { name: find_metric(aggregate, gate, name) for name in ( "clean_top1", "clean_top5", "clean_nll", "clean_ece", "mean_corruption_top1", "retention", ) } lines.append( f"| {gate} | " + " | ".join(pm(metrics[name]["mean"], metrics[name]["std"]) for name in metrics) + " |" ) if clip_stages and clip_check: lines.extend( [ "", "## Smooth-static learned clip values", "", "The gate was initialized at c=6.0. Stage means are mean +/- standard", "deviation across seeds; ranges cover every block and seed.", "", "| Stage | Mean +/- std | Block/seed range | Blocks per seed |", "|---:|---:|---:|---:|", ] ) for row in clip_stages: lines.append( f'| {row["stage"]} | {row["mean"]:.4f} +/- {row["std_across_seeds"]:.4f} | ' f'[{row["min_across_blocks_seeds"]:.4f}, {row["max_across_blocks_seeds"]:.4f}] | ' f'{row["blocks_per_seed"]} |' ) verdict = "PASS" if clip_check["phase2_boundary_check_pass"] else "FAIL" lines.extend( [ "", f'- Global clip range: [{clip_check["global_min"]:.4f}, {clip_check["global_max"]:.4f}].', f'- Strict near-boundary threshold: {clip_check["strict_boundary_threshold"]:.4f}; observed: {clip_check["near_min_boundary"]}.', f'- Severe-collapse threshold (10% of initialization): {clip_check["severe_collapse_threshold"]:.4f}; observed: {clip_check["below_10pct_initial"]}.', f'- Phase-2 non-collapse check: **{verdict}**.', ] ) lines.extend( [ "", f"## Paired differences vs ReLU6 ({samples} bootstrap draws)", "", "Differences are candidate minus ReLU6 in percentage points; intervals excluding", "zero are marked `yes`.", "", "| Gate | Clean top-1 diff [95% CI] | Mean corruption diff [95% CI] | Retention diff [95% CI] | Significant |", "|---|---:|---:|---:|---:|", ] ) for gate in available: if gate == "relu6": continue clean = find_comparison(comparisons, gate, "clean_top1") corrupted = find_comparison(comparisons, gate, "mean_corruption_top1") retention = find_comparison(comparisons, gate, "retention") if clean is None or corrupted is None or retention is None: continue interval = lambda value: f'{value["difference"]:.2f} [{value["ci_low"]:.2f}, {value["ci_high"]:.2f}]' significant = "yes" if any(value["significant"] for value in (clean, corrupted, retention)) else "no" lines.append( f"| {gate} | {interval(clean)} | {interval(corrupted)} | {interval(retention)} | {significant} |" ) if available: best_clean = max(available, key=lambda gate: find_metric(aggregate, gate, "clean_top1")["mean"]) best_corrupt = max( available, key=lambda gate: find_metric(aggregate, gate, "mean_corruption_top1")["mean"], ) best_retention = max( available, key=lambda gate: find_metric(aggregate, gate, "retention")["mean"] ) lines.extend( [ "", "## Conclusions", "", f"1. `{best_clean}` has the highest clean top-1 mean in this three-seed screen.", f"2. `{best_corrupt}` has the highest absolute mean corruption top-1; `{best_retention}` has the highest clean-normalized retention.", "3. Absolute corruption accuracy and retention answer different questions; retention alone must not be presented as robustness when clean accuracy is low.", "4. This CIFAR-100 screen supports gate selection and mechanism checks. It does not replace the planned ImageNet matched-recipe comparison.", "", ] ) return "\n".join(lines) def write_csv(path: Path, rows: list[dict[str, Any]], columns: list[str]) -> None: with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=columns, extrasaction="ignore") writer.writeheader() writer.writerows(rows) def main() -> None: args = parse_args() root = Path(args.runs_root).resolve() output = Path(args.output_dir or root / "evaluation_summary").resolve() if (output / "CONCLUSIONS.md").exists() and not args.overwrite: raise FileExistsError(f"summary exists: {output}; use --overwrite") output.mkdir(parents=True, exist_ok=True) runs = discover_runs(root, args.allow_incomplete) aggregate = aggregate_metrics(runs) comparisons = paired_comparisons(runs, args.bootstrap_samples, args.bootstrap_seed) clip_blocks, clip_stages, clip_check = aggregate_smooth_clips(runs) write_csv( output / "aggregate.csv", aggregate, ["gate", "scope", "condition", "metric", "mean", "std", "seeds"], ) write_csv( output / "paired_bootstrap_vs_relu6.csv", comparisons, [ "gate", "reference", "metric", "difference", "ci_low", "ci_high", "unit", "significant", "bootstrap_samples", "training_seeds", "test_samples", ], ) write_csv( output / "smooth_clip_by_block.csv", clip_blocks, [ "seed", "module", "stage", "block", "mean", "min", "max", "channels", "min_clip_boundary", ], ) write_csv( output / "smooth_clip_by_stage.csv", clip_stages, [ "stage", "mean", "std_across_seeds", "min_across_blocks_seeds", "max_across_blocks_seeds", "blocks_per_seed", "seeds", ], ) payload = { "protocol_version": PROTOCOL_VERSION, "runs_root": str(root), "expected_gates": GATES, "expected_seeds": SEEDS, "conditions": CONDITIONS, "aggregate": aggregate, "paired_comparisons": comparisons, "smooth_clip_blocks": clip_blocks, "smooth_clip_stages": clip_stages, "smooth_clip_phase2_check": clip_check, } temporary = output / ".results.json.tmp" temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") os.replace(temporary, output / "results.json") (output / "CONCLUSIONS.md").write_text( report( aggregate, comparisons, args.bootstrap_samples, clip_stages, clip_check, ), encoding="utf-8", ) print(output) if __name__ == "__main__": main()