Backup / gmnet /code /journal_exp /scripts /summarize_cifar100_pregate_v2.py
YFanwang's picture
Add files using upload-large-folder tool
10979b5 verified
Raw History Blame Contribute Delete
8.66 kB
#!/usr/bin/env python3
"""Summarize the matched CIFAR-100 pre-gate for ImageNet protocol v2."""
from __future__ import annotations
import argparse
import csv
import json
import math
from pathlib import Path
from typing import Any
import numpy as np
from scipy import stats
VARIANTS = {
"smooth_corrected": "e3_c100_pregate_v2_smooth_corrected_seed{seed}",
"relu6_only": "e3_c100_pregate_v2_relu6_only_seed{seed}",
}
METRICS = (
"clean_top1",
"mean_corruption_top1",
"clean_nll",
"mean_corruption_nll",
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--reference-root", type=Path, default=Path("/tmp/gmnet_runs/e3_cifar100")
)
parser.add_argument(
"--pregate-root",
type=Path,
default=Path("/tmp/gmnet_runs/e3_cifar100_pregate_v2"),
)
parser.add_argument(
"--output-dir",
type=Path,
default=Path("/nfs/ywang29/GmNet/local_results/imagenet_v2_pregate"),
)
return parser.parse_args()
def load_result(path: Path) -> dict[str, Any]:
result = json.loads(path.read_text(encoding="utf-8"))
if result.get("partial_evaluation") or not result.get("complete_training_required"):
raise ValueError(f"incomplete evaluation cannot enter pre-gate: {path}")
values = [result["overall"][metric] for metric in METRICS]
if not np.isfinite(np.asarray(values, dtype=np.float64)).all():
raise ValueError(f"non-finite result: {path}")
return result
def paired_interval(differences: np.ndarray) -> tuple[float, float]:
differences = np.asarray(differences, dtype=np.float64)
if differences.shape != (3,):
raise ValueError("pre-gate inference requires exactly three paired seeds")
radius = float(stats.t.ppf(0.975, 2) * stats.sem(differences))
mean = float(differences.mean())
return mean - radius, mean + radius
def format_effect(row: dict[str, Any]) -> str:
return f"{row['difference']:+.3f} [{row['ci_low']:+.3f}, {row['ci_high']:+.3f}]"
def main() -> None:
args = parse_args()
reference_root = args.reference_root.resolve()
pregate_root = args.pregate_root.resolve()
output_dir = args.output_dir.resolve()
output_dir.mkdir(parents=True, exist_ok=True)
reference: dict[int, dict[str, Any]] = {}
candidates: dict[str, dict[int, dict[str, Any]]] = {
variant: {} for variant in VARIANTS
}
for seed in range(3):
reference[seed] = load_result(
reference_root
/ f"e3_c100_s1_relu6_seed{seed}"
/ "evaluation/results.json"
)
for variant, pattern in VARIANTS.items():
candidates[variant][seed] = load_result(
pregate_root / pattern.format(seed=seed) / "evaluation/results.json"
)
fixed = load_result(
pregate_root
/ "e3_c100_pregate_v2_smooth_fixed_c6_seed0"
/ "evaluation/results.json"
)
effects: list[dict[str, Any]] = []
aggregates: list[dict[str, Any]] = []
for variant, runs in candidates.items():
for metric in METRICS:
candidate_values = np.asarray(
[runs[seed]["overall"][metric] for seed in range(3)], dtype=np.float64
)
reference_values = np.asarray(
[reference[seed]["overall"][metric] for seed in range(3)],
dtype=np.float64,
)
differences = candidate_values - reference_values
ci_low, ci_high = paired_interval(differences)
effects.append(
{
"variant": variant,
"reference": "relu6_self",
"metric": metric,
"difference": float(differences.mean()),
"ci_low": ci_low,
"ci_high": ci_high,
"seed_differences": [float(value) for value in differences],
"inference_unit": "paired_training_seed",
"seeds": 3,
}
)
aggregates.append(
{
"variant": variant,
"metric": metric,
"mean": float(candidate_values.mean()),
"std": float(candidate_values.std(ddof=1)),
"seeds": 3,
}
)
smooth_diagnostics = [
candidates["smooth_corrected"][seed]["smooth_clip_diagnostics"]
for seed in range(3)
]
global_min = min(float(item["global_min"]) for item in smooth_diagnostics)
severe_boundary = max(
float(item["severe_collapse_threshold"]) for item in smooth_diagnostics
)
cap_pass = all(
bool(item["phase2_boundary_check_pass"]) for item in smooth_diagnostics
)
fixed_caps = fixed["smooth_clip_diagnostics"]
fixed_pass = bool(fixed_caps) and math.isclose(
float(fixed_caps["global_mean"]), 6.0, abs_tol=1e-7
)
pregate_pass = cap_pass and fixed_pass
effect_index = {(row["variant"], row["metric"]): row for row in effects}
lines = [
"# ImageNet v2 CIFAR-100 Pre-Gate Evidence",
"",
f"Decision: **{'PASS' if pregate_pass else 'FAIL'}**. This is a technical/controller pre-gate, not an accuracy-selection rule.",
"",
"All runs completed 100 fixed epochs and full clean plus five-corruption evaluation. "
"Intervals use the three paired training seeds; n=3 intervals are necessarily wide.",
"",
"| Variant | Clean Top-1 effect | Mean-corruption Top-1 effect | Clean NLL effect | Corruption NLL effect |",
"|---|---:|---:|---:|---:|",
]
for variant in VARIANTS:
cells = [format_effect(effect_index[(variant, metric)]) for metric in METRICS]
lines.append(f"| {variant} | " + " | ".join(cells) + " |")
lines.extend(
[
"",
"## Controller Audit",
"",
f"The learned-smooth minimum cap across seeds/blocks is `{global_min:.4f}`; "
f"the predefined severe-collapse boundary is `{severe_boundary:.4f}`. "
f"Controller non-collapse: `{cap_pass}`.",
f"The fixed-c6 controller remains at 6.0: `{fixed_pass}`.",
"",
"The old learned-cap collapse cannot be interpreted as adaptation because `raw_clip` "
"received weight decay. With zero controller weight decay, caps remain finite and "
"stage-dependent, so corrected learned-smooth is eligible for ImageNet.",
"",
"## Design Consequence",
"",
"Activation-only does not show the locally expected material loss. Its ImageNet test "
"must therefore not be an early fixed-sequence gate that suppresses the ReLU and "
"smooth hypotheses. Treat the four predeclared primary contrasts with simultaneous "
"family-wise correction, and interpret activation-only as an operator-replacement "
"test rather than unique causal evidence for multiplication.",
"",
]
)
report = "\n".join(lines)
(output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8")
(output_dir / "results.json").write_text(
json.dumps(
{
"protocol": "imagenet-long-v2-pregate",
"decision": "passed" if pregate_pass else "failed",
"reference_root": str(reference_root),
"pregate_root": str(pregate_root),
"effects": effects,
"aggregates": aggregates,
"controller": {
"learned_global_min": global_min,
"severe_collapse_boundary": severe_boundary,
"learned_noncollapse_pass": cap_pass,
"fixed_c6_pass": fixed_pass,
},
},
indent=2,
sort_keys=True,
)
+ "\n",
encoding="utf-8",
)
with (output_dir / "paired_seed_effects.csv").open(
"w", newline="", encoding="utf-8"
) as handle:
writer = csv.DictWriter(
handle,
fieldnames=[
"variant",
"reference",
"metric",
"difference",
"ci_low",
"ci_high",
"seed_differences",
"inference_unit",
"seeds",
],
)
writer.writeheader()
writer.writerows(effects)
print(output_dir)
if __name__ == "__main__":
main()