File size: 8,664 Bytes
10979b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()