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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
#!/usr/bin/env python3
"""Validate and merge the 18 formal E1 trained-feature audit shards."""

from __future__ import annotations

import argparse
import csv
import json
import math
import sys
from collections import defaultdict
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from run_e1_trained_features import LAYER_ORDER, _aggregate, _format, _write_csv


Row = dict[str, Any]
EXPECTED_GATES = (
    "relu6_self",
    "relu_self",
    "gelu_self",
    "smooth_clipped_self",
    "identity",
    "no_gate",
)
EXPECTED_PAIRS = {(gate, seed) for gate in EXPECTED_GATES for seed in range(3)}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--shard-root", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    return parser.parse_args()


def _convert(value: str) -> Any:
    if value == "":
        return None
    if value == "True":
        return True
    if value == "False":
        return False
    try:
        if value.lstrip("-").isdigit():
            return int(value)
        return float(value)
    except ValueError:
        return value


def _read_csv(path: Path) -> list[Row]:
    with path.open(newline="", encoding="utf-8") as handle:
        return [{key: _convert(value) for key, value in row.items()} for row in csv.DictReader(handle)]


def _weighted_gate_seed_rows(gate_rows: list[Row]) -> list[Row]:
    groups: dict[tuple[str, int, str], list[Row]] = defaultdict(list)
    for row in gate_rows:
        if float(row["cutoff"]) == 1.0:
            groups[(row["gate"], int(row["seed"]), row["stage"])].append(row)
    metrics = (
        "negative_fraction",
        "active_0_to_6_fraction",
        "above_reference_6_fraction",
        "actual_clip_crossing_fraction",
        "clip_value_mean",
    )
    result: list[Row] = []
    for (gate, seed, stage), rows in sorted(groups.items()):
        total = sum(int(row["element_count"]) for row in rows)
        output: Row = {
            "gate": gate,
            "seed": seed,
            "stage": stage,
            "element_count": total,
        }
        for metric in metrics:
            valid = [row for row in rows if row[metric] is not None]
            output[metric] = (
                sum(float(row[metric]) * int(row["element_count"]) for row in valid)
                / sum(int(row["element_count"]) for row in valid)
                if valid
                else None
            )
        result.append(output)
    return result


def _nonfinite_diagnostics(tables: dict[str, list[Row]]) -> tuple[list[Row], list[Row]]:
    """Return explicit nonfinite cells and an observation-level summary."""

    cells: list[Row] = []
    observations: dict[tuple[Any, ...], dict[str, Any]] = {}
    for table, rows in tables.items():
        for row_index, row in enumerate(rows, start=2):
            for metric, value in row.items():
                if not isinstance(value, float) or math.isfinite(value):
                    continue
                cell = {
                    "table": table,
                    "row": row_index,
                    "gate": row.get("gate"),
                    "seed": row.get("seed"),
                    "cutoff": row.get("cutoff"),
                    "layer": row.get("layer"),
                    "metric": metric,
                    "nonfinite_value": "nan" if math.isnan(value) else "inf" if value > 0 else "-inf",
                }
                cells.append(cell)
                key = (
                    table,
                    row.get("gate"),
                    row.get("seed"),
                    row.get("cutoff"),
                    row.get("layer"),
                )
                observation = observations.setdefault(
                    key,
                    {
                        "table": table,
                        "gate": row.get("gate"),
                        "seed": row.get("seed"),
                        "cutoff": row.get("cutoff"),
                        "layer": row.get("layer"),
                        "nonfinite_field_count": 0,
                        "nonfinite_metrics": set(),
                    },
                )
                observation["nonfinite_field_count"] += 1
                observation["nonfinite_metrics"].add(metric)
    summary: list[Row] = []
    for observation in observations.values():
        summary.append(
            {
                **observation,
                "nonfinite_metrics": ";".join(sorted(observation["nonfinite_metrics"])),
            }
        )
    summary.sort(
        key=lambda row: (
            str(row["table"]),
            str(row["gate"]),
            int(row["seed"]) if row["seed"] is not None else -1,
            float(row["cutoff"]) if row["cutoff"] is not None else -1.0,
            str(row["layer"]),
        )
    )
    return cells, summary


def _report(
    sample_hash: str,
    accuracy_summary: list[Row],
    auc_summary: list[Row],
    feature_summary: list[Row],
    transfer_summary: list[Row],
    gate_summary: list[Row],
    nonfinite_cells: list[Row],
    nonfinite_summary: list[Row],
) -> str:
    lines = [
        "# E1 Trained CIFAR-100 Feature Audit",
        "",
        "Status: complete formal 6-gate x 3-seed matrix.",
        "",
        "## Frozen Protocol",
        "",
        "- Exactly 18 `checkpoint_last.pt` files at fixed epoch 100.",
        "- `checkpoint_best.pt` is excluded to avoid CIFAR-100 test-selection leakage.",
        f"- Every run uses the same 10,000 ordered test samples; index hash `{sample_hash}`.",
        "- Butterworth order 4, cutoffs 0, 0.125, 0.25, 0.5, 0.75, and identity endpoint 1.",
        "",
        "## Frequency-Accuracy AUC",
        "",
        "| Gate | Seeds | Identity Top-1 | Top-1 AUC |",
        "|---|---:|---:|---:|",
    ]
    for row in auc_summary:
        lines.append(
            f"| {row['gate']} | {row['count']} | {_format(row['identity_top1_mean'])} +/- {_format(row['identity_top1_std'])} | "
            f"{_format(row['frequency_accuracy_auc_top1_mean'])} +/- {_format(row['frequency_accuracy_auc_top1_std'])} |"
        )
    lines.extend(
        [
            "",
            "## Accuracy Curve",
            "",
            "| Gate | Cutoff | Top-1 | Top-5 |",
            "|---|---:|---:|---:|",
        ]
    )
    for row in accuracy_summary:
        lines.append(
            f"| {row['gate']} | {row['cutoff']} | {_format(row['top1_mean'])} +/- {_format(row['top1_std'])} | "
            f"{_format(row['top5_mean'])} +/- {_format(row['top5_std'])} |"
        )
    lines.extend(
        [
            "",
            "## Identity-Input Feature PSD",
            "",
            "| Gate | Layer | Size | Centroid | High/low | Entropy |",
            "|---|---|---|---:|---:|---:|",
        ]
    )
    for row in feature_summary:
        lines.append(
            f"| {row['gate']} | {row['layer']} | {row['height']}x{row['width']} | "
            f"{_format(row['spectral_centroid_mean'])} | {_format(row['high_low_ratio_mean'])} | "
            f"{_format(row['spectral_entropy_mean'])} |"
        )
    lines.extend(
        [
            "",
            "## Cutoff 0.25 Feature Transfer",
            "",
            "| Gate | Layer | Centroid delta | Entropy delta |",
            "|---|---|---:|---:|",
        ]
    )
    for row in transfer_summary:
        lines.append(
            f"| {row['gate']} | {row['layer']} | {_format(row['centroid_delta_vs_identity_mean'])} | "
            f"{_format(row['entropy_delta_vs_identity_mean'])} |"
        )
    lines.extend(
        [
            "",
            "## Identity-Input Gate Regions",
            "",
            "| Gate | Stage | Negative | Active [0,6) | Above 6 | Clip mean | Actual clip crossing |",
            "|---|---|---:|---:|---:|---:|---:|",
        ]
    )
    for row in gate_summary:
        lines.append(
            f"| {row['gate']} | {row['stage']} | {_format(row['negative_fraction_mean'])} | "
            f"{_format(row['active_0_to_6_fraction_mean'])} | {_format(row['above_reference_6_fraction_mean'])} | "
            f"{_format(row['clip_value_mean_mean'])} | {_format(row['actual_clip_crossing_fraction_mean'])} |"
        )
    lines.extend(
        [
            "",
            "## Nonfinite Diagnostics",
            "",
            f"- Nonfinite numeric cells: {len(nonfinite_cells)}.",
            f"- Affected table observations: {len(nonfinite_summary)}.",
            "- Aggregates exclude nonfinite values. If no finite observation remains, the statistic is JSON null and report NA; values are never replaced by zero.",
            "",
            "| Table | Gate | Seed | Cutoff | Layer | Nonfinite fields |",
            "|---|---|---:|---:|---|---|",
        ]
    )
    for row in nonfinite_summary:
        lines.append(
            f"| {row['table']} | {row['gate']} | {row['seed']} | {row['cutoff']} | "
            f"{row['layer']} | {row['nonfinite_metrics']} |"
        )
    lines.extend(
        [
            "",
            "## Interpretation Limits",
            "",
            "- Stage3 is 2x2 and has no non-DC FFT cell below normalized radius 0.5; its high/low ratio is NA.",
            "- Stage4 and pre_classifier are 1x1, so their spatial PSD values are NA.",
            "- Frequency-Accuracy AUC measures causal sensitivity to this input filter protocol, not model function frequency.",
            "",
        ]
    )
    return "\n".join(lines)


def main() -> None:
    args = parse_args()
    shard_root = args.shard_root.resolve()
    output_dir = args.output_dir.resolve()
    allowed = Path("/tmp/gmnet_runs/e1_trained_features/full").resolve()
    if output_dir != allowed:
        raise ValueError(f"formal merged output must be {allowed}")
    result_paths = sorted(shard_root.glob("*/results.json"))
    if len(result_paths) != 18:
        raise ValueError(f"expected 18 shard results, found {len(result_paths)}")

    manifests: list[Row] = []
    accuracy_rows: list[Row] = []
    auc_rows: list[Row] = []
    feature_rows: list[Row] = []
    gate_rows: list[Row] = []
    sample_hashes: set[str] = set()
    pairs: set[tuple[str, int]] = set()
    for result_path in result_paths:
        result = json.loads(result_path.read_text(encoding="utf-8"))
        protocol = result["protocol"]
        if result["status"] != "full":
            raise ValueError(f"non-full shard: {result_path}")
        if protocol["checkpoint_name"] != "checkpoint_last.pt":
            raise ValueError(f"wrong checkpoint policy: {result_path}")
        if protocol["require_epochs_completed"] != 100 or protocol["sample_count"] != 10_000:
            raise ValueError(f"wrong frozen protocol: {result_path}")
        if protocol["cutoffs"] != [0.0, 0.125, 0.25, 0.5, 0.75, 1.0]:
            raise ValueError(f"wrong cutoffs: {result_path}")
        sample_hashes.add(protocol["sample_indices_sha256"])
        shard = result_path.parent
        shard_manifest = _read_csv(shard / "checkpoint_manifest.csv")
        if len(shard_manifest) != 1:
            raise ValueError(f"expected one checkpoint per shard: {shard}")
        manifest = shard_manifest[0]
        if manifest["checkpoint_name"] != "checkpoint_last.pt" or manifest["checkpoint_epochs_completed"] != 100:
            raise ValueError(f"checkpoint is not fixed epoch100 last: {shard}")
        pair = (manifest["gate"], int(manifest["seed"]))
        if pair in pairs:
            raise ValueError(f"duplicate shard {pair}")
        pairs.add(pair)
        manifests.append(manifest)
        accuracy_rows.extend(_read_csv(shard / "accuracy_curve.csv"))
        auc_rows.extend(_read_csv(shard / "accuracy_auc.csv"))
        feature_rows.extend(_read_csv(shard / "feature_metrics.csv"))
        gate_rows.extend(_read_csv(shard / "gate_regions.csv"))
    if pairs != EXPECTED_PAIRS:
        raise ValueError(f"checkpoint matrix mismatch; missing={sorted(EXPECTED_PAIRS - pairs)}")
    if len(sample_hashes) != 1:
        raise ValueError(f"sample subsets differ across shards: {sample_hashes}")
    sample_hash = next(iter(sample_hashes))

    nonfinite_cells, nonfinite_summary = _nonfinite_diagnostics(
        {
            "checkpoint_manifest": manifests,
            "accuracy_curve": accuracy_rows,
            "accuracy_auc": auc_rows,
            "feature_metrics": feature_rows,
            "gate_regions": gate_rows,
        }
    )

    accuracy_summary = _aggregate(
        accuracy_rows, ("gate", "cutoff"), ("top1", "top5")
    )
    auc_summary = _aggregate(
        auc_rows,
        ("gate",),
        ("identity_top1", "identity_top5", "frequency_accuracy_auc_top1", "frequency_accuracy_auc_top5"),
    )
    identity_features = [row for row in feature_rows if row["cutoff"] == 1.0]
    feature_summary = _aggregate(
        identity_features,
        ("gate", "layer", "height", "width"),
        ("spectral_centroid", "high_low_ratio", "spectral_entropy"),
    )
    feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"])))
    transfer_rows = [row for row in feature_rows if row["cutoff"] == 0.25]
    transfer_summary = _aggregate(
        transfer_rows,
        ("gate", "layer"),
        ("centroid_delta_vs_identity", "entropy_delta_vs_identity"),
    )
    transfer_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"])))
    gate_seed_rows = _weighted_gate_seed_rows(gate_rows)
    gate_summary = _aggregate(
        gate_seed_rows,
        ("gate", "stage"),
        (
            "negative_fraction",
            "active_0_to_6_fraction",
            "above_reference_6_fraction",
            "clip_value_mean",
            "actual_clip_crossing_fraction",
        ),
    )

    output_dir.mkdir(parents=True, exist_ok=True)
    _write_csv(output_dir / "checkpoint_manifest.csv", manifests)
    _write_csv(output_dir / "accuracy_curve.csv", accuracy_rows)
    _write_csv(output_dir / "accuracy_auc.csv", auc_rows)
    _write_csv(output_dir / "feature_metrics.csv", feature_rows)
    _write_csv(output_dir / "gate_regions.csv", gate_rows)
    _write_csv(output_dir / "accuracy_summary.csv", accuracy_summary)
    _write_csv(output_dir / "accuracy_auc_summary.csv", auc_summary)
    _write_csv(output_dir / "feature_summary.csv", feature_summary)
    _write_csv(output_dir / "feature_transfer_summary.csv", transfer_summary)
    _write_csv(output_dir / "gate_seed_summary.csv", gate_seed_rows)
    _write_csv(output_dir / "gate_summary.csv", gate_summary)
    if nonfinite_cells:
        _write_csv(output_dir / "nonfinite_cells.csv", nonfinite_cells)
        _write_csv(output_dir / "nonfinite_summary.csv", nonfinite_summary)
    merged = {
        "schema_version": 1,
        "experiment_id": "E1-trained-cifar100-feature-audit-formal",
        "timestamp_utc": datetime.now(UTC).isoformat(),
        "status": "complete",
        "checkpoint_policy": "checkpoint_last.pt at fixed epoch 100",
        "checkpoint_count": len(manifests),
        "sample_count_per_run": 10_000,
        "sample_indices_sha256": sample_hash,
        "accuracy_auc_summary": auc_summary,
        "feature_identity_summary": feature_summary,
        "feature_transfer_cutoff_0_25_summary": transfer_summary,
        "gate_identity_summary": gate_summary,
        "nonfinite_diagnostics": {
            "numeric_cell_count": len(nonfinite_cells),
            "affected_observation_count": len(nonfinite_summary),
            "handling": "Excluded from aggregate statistics; all-nonfinite aggregates are null, never zero.",
            "observations": nonfinite_summary,
        },
    }
    (output_dir / "results.json").write_text(
        json.dumps(merged, indent=2, allow_nan=False) + "\n", encoding="utf-8"
    )
    (output_dir / "REPORT.md").write_text(
        _report(
            sample_hash,
            accuracy_summary,
            auc_summary,
            feature_summary,
            transfer_summary,
            gate_summary,
            nonfinite_cells,
            nonfinite_summary,
        ),
        encoding="utf-8",
    )
    print(f"Merged 18 formal shards: {output_dir}")


if __name__ == "__main__":
    main()