File size: 21,381 Bytes
12c2325 | 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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | #!/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()
|