File size: 30,227 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
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
#!/usr/bin/env python3
"""Audit trained CIFAR-100 checkpoints with feature-spectrum hooks."""

from __future__ import annotations

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

import numpy as np
import torch
from torch import Tensor, nn
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms

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

from gmnet.models import create_gmnet
from gmnet.models.gmnet import GmNetBlock, SmoothClippedSelfGate
from gmnet.spectral import RadialPSDAccumulator, torch_fft_lowpass


Row = dict[str, Any]
OUTPUT_ROOT = Path("/tmp/gmnet_runs/e1_trained_features")
DIRECTORY_NAMES = {
    "relu6_self": "relu6",
    "relu_self": "relu",
    "gelu_self": "gelu",
    "smooth_clipped_self": "smooth_static",
    "identity": "identity",
    "no_gate": "no_gate",
}
GATE_ALIASES = {
    "relu6": "relu6_self",
    "relu": "relu_self",
    "gelu": "gelu_self",
    "smooth_static": "smooth_clipped_self",
    "smooth_clipped_static": "smooth_clipped_self",
    **{name: name for name in DIRECTORY_NAMES},
}
LAYER_ORDER = ("input", "stage1", "stage2", "stage3", "stage4", "pre_classifier")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--checkpoint-root",
        type=Path,
        default=Path("/tmp/gmnet_runs/e3_cifar100"),
    )
    parser.add_argument(
        "--data-root", type=Path, default=Path("/tmp/gmnet_data/cifar-100")
    )
    parser.add_argument("--output-dir", type=Path)
    parser.add_argument("--checkpoint-name", default="checkpoint_last.pt")
    parser.add_argument(
        "--gates",
        nargs="+",
        default=[
            "relu6_self",
            "relu_self",
            "gelu_self",
            "smooth_clipped_self",
            "identity",
            "no_gate",
        ],
    )
    parser.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2])
    parser.add_argument("--device", default="cuda:0")
    parser.add_argument("--batch-size", type=int, default=256)
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--num-samples", type=int, default=10_000)
    parser.add_argument("--sample-seed", type=int, default=250322841)
    parser.add_argument(
        "--cutoffs", nargs="+", type=float, default=[0.0, 0.125, 0.25, 0.5, 0.75, 1.0]
    )
    parser.add_argument("--butterworth-order", type=int, default=4)
    parser.add_argument("--high-low-split", type=float, default=0.5)
    parser.add_argument("--radial-bins", type=int, default=16)
    parser.add_argument("--allow-missing", action="store_true")
    parser.add_argument("--max-checkpoints", type=int)
    parser.add_argument("--require-epochs-completed", type=int)
    parser.add_argument(
        "--smoke",
        action="store_true",
        help="Use one available ETA checkpoint, 64 samples, and two cutoffs.",
    )
    return parser.parse_args()


def _canonical_gate(name: str) -> str:
    normalized = name.lower().replace("-", "_")
    if normalized not in GATE_ALIASES:
        raise ValueError(f"unknown gate {name!r}")
    return GATE_ALIASES[normalized]


def _write_csv(path: Path, rows: list[Row]) -> None:
    if not rows:
        raise ValueError(f"refusing to write empty table: {path}")
    fields: list[str] = []
    for row in rows:
        for field in row:
            if field not in fields:
                fields.append(field)
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)


def _mean_std(values: list[float]) -> tuple[float, float]:
    array = np.asarray(values, dtype=np.float64)
    return float(array.mean()), float(array.std(ddof=1)) if len(array) > 1 else 0.0


def _aggregate(rows: list[Row], keys: tuple[str, ...], metrics: tuple[str, ...]) -> list[Row]:
    groups: dict[tuple[Any, ...], list[Row]] = defaultdict(list)
    for row in rows:
        groups[tuple(row[key] for key in keys)].append(row)
    result: list[Row] = []
    for key, group in sorted(groups.items()):
        output: Row = dict(zip(keys, key, strict=True))
        output["count"] = len(group)
        for metric in metrics:
            observed = [float(row[metric]) for row in group if row.get(metric) is not None]
            finite = [value for value in observed if math.isfinite(value)]
            output[f"{metric}_finite_count"] = len(finite)
            output[f"{metric}_nonfinite_count"] = len(observed) - len(finite)
            output[f"{metric}_missing_count"] = len(group) - len(observed)
            if finite:
                output[f"{metric}_mean"], output[f"{metric}_std"] = _mean_std(finite)
            else:
                output[f"{metric}_mean"] = None
                output[f"{metric}_std"] = None
        result.append(output)
    return result


@dataclass(frozen=True)
class CheckpointSpec:
    gate: str
    seed: int
    path: Path


def discover_checkpoints(args: argparse.Namespace) -> tuple[list[CheckpointSpec], list[str]]:
    requested_gates = [_canonical_gate(name) for name in args.gates]
    found: list[CheckpointSpec] = []
    missing: list[str] = []
    for gate in requested_gates:
        directory_name = DIRECTORY_NAMES[gate]
        for seed in args.seeds:
            path = (
                args.checkpoint_root
                / f"e3_c100_s1_{directory_name}_seed{seed}"
                / args.checkpoint_name
            )
            if path.is_file():
                found.append(CheckpointSpec(gate, seed, path))
            else:
                missing.append(str(path))
    if missing and not args.allow_missing:
        preview = "\n".join(missing[:8])
        raise FileNotFoundError(
            f"{len(missing)} requested checkpoints are missing; use --allow-missing for an ETA audit:\n{preview}"
        )
    if args.max_checkpoints is not None:
        found = found[: args.max_checkpoints]
    if not found:
        raise FileNotFoundError(f"no checkpoints found under {args.checkpoint_root}")
    return found, missing


def _load_model(
    spec: CheckpointSpec,
    device: torch.device,
    require_epochs_completed: int | None,
) -> tuple[nn.Module, dict[str, Any], Row]:
    checkpoint = torch.load(spec.path, map_location="cpu", weights_only=False)
    if not isinstance(checkpoint, dict) or "model" not in checkpoint or "config" not in checkpoint:
        raise ValueError(f"invalid checkpoint: {spec.path}")
    config = checkpoint["config"]
    checkpoint_seed = int(checkpoint.get("seed", -1))
    if checkpoint_seed != spec.seed:
        raise ValueError(
            f"directory seed {spec.seed} disagrees with checkpoint seed {checkpoint_seed}: {spec.path}"
        )
    epochs_completed = int(checkpoint.get("epoch", -1)) + 1
    if (
        require_epochs_completed is not None
        and epochs_completed != require_epochs_completed
    ):
        raise ValueError(
            f"checkpoint has {epochs_completed} completed epochs, expected exactly "
            f"{require_epochs_completed}: {spec.path}"
        )
    model_config = dict(config["model"])
    variant = str(model_config.pop("variant"))
    num_classes = int(model_config.pop("num_classes"))
    configured_gate = _canonical_gate(str(model_config.get("gate_type", "relu6_self")))
    if configured_gate != spec.gate:
        raise ValueError(
            f"directory gate {spec.gate} disagrees with config gate {configured_gate}: {spec.path}"
        )
    model = create_gmnet(variant, num_classes=num_classes, **model_config)
    incompatible = model.load_state_dict(checkpoint["model"], strict=True)
    if incompatible.missing_keys or incompatible.unexpected_keys:
        raise RuntimeError(f"state_dict mismatch for {spec.path}: {incompatible}")
    model.to(device).eval()
    manifest = {
        "gate": spec.gate,
        "seed": spec.seed,
        "run_name": checkpoint.get("run_name", spec.path.parent.name),
        "checkpoint": str(spec.path.resolve()),
        "checkpoint_name": spec.path.name,
        "checkpoint_epoch_zero_based": int(checkpoint.get("epoch", -1)),
        "checkpoint_epochs_completed": epochs_completed,
        "checkpoint_best_top1": float(checkpoint.get("best_top1", float("nan"))),
    }
    return model, config, manifest


def _dataset_from_config(data_root: Path, config: dict[str, Any]) -> datasets.CIFAR100:
    data = config["data"]
    if str(data["dataset"]).lower() not in {"cifar100", "cifar-100"}:
        raise ValueError("trained feature audit only supports CIFAR-100")
    input_size = int(data.get("input_size", 32))
    operations: list[Any] = []
    if input_size != 32:
        operations.append(transforms.Resize((input_size, input_size)))
    operations.extend(
        [
            transforms.ToTensor(),
            transforms.Normalize(
                tuple(data.get("mean", (0.5071, 0.4867, 0.4408))),
                tuple(data.get("std", (0.2675, 0.2565, 0.2761))),
            ),
        ]
    )
    return datasets.CIFAR100(
        data_root, train=False, transform=transforms.Compose(operations), download=False
    )


class GateRegionAccumulator:
    """Count universal pre-gate regions and actual clipping crossings."""

    def __init__(self, gate_module: nn.Module) -> None:
        self.gate_module = gate_module
        self.total = 0
        self.negative = 0
        self.active_reference = 0
        self.above_reference = 0
        self.actual_clip_crossing = 0

    @property
    def clip_applies(self) -> bool:
        return isinstance(self.gate_module, SmoothClippedSelfGate) or getattr(
            self.gate_module, "name", None
        ) == "relu6_self"

    @property
    def clip_value_mean(self) -> float | None:
        if isinstance(self.gate_module, SmoothClippedSelfGate):
            return float(self.gate_module.clip_value.detach().mean().cpu())
        if getattr(self.gate_module, "name", None) == "relu6_self":
            return 6.0
        return None

    def update(self, value: Tensor) -> None:
        tensor = value.detach()
        self.total += tensor.numel()
        self.negative += int((tensor < 0).sum())
        self.active_reference += int(((tensor >= 0) & (tensor < 6)).sum())
        self.above_reference += int((tensor >= 6).sum())
        if isinstance(self.gate_module, SmoothClippedSelfGate):
            self.actual_clip_crossing += int(
                (tensor >= self.gate_module.clip_value.detach()).sum()
            )
        elif getattr(self.gate_module, "name", None) == "relu6_self":
            self.actual_clip_crossing += int((tensor >= 6).sum())

    def compute(self) -> Row:
        if self.total == 0:
            raise RuntimeError("no gate inputs accumulated")
        return {
            "element_count": self.total,
            "negative_fraction": self.negative / self.total,
            "active_0_to_6_fraction": self.active_reference / self.total,
            "above_reference_6_fraction": self.above_reference / self.total,
            "clip_applies": self.clip_applies,
            "clip_value_mean": self.clip_value_mean,
            "actual_clip_crossing_fraction": (
                self.actual_clip_crossing / self.total if self.clip_applies else None
            ),
        }


def _block_gates(model: nn.Module) -> list[tuple[str, int, str, nn.Module]]:
    result: list[tuple[str, int, str, nn.Module]] = []
    for stage_index, stage in enumerate(model.stages, start=1):
        block_index = 0
        for module in stage:
            if isinstance(module, GmNetBlock):
                block_index += 1
                result.append(
                    (f"stage{stage_index}", stage_index, f"block{block_index}", module.gate)
                )
    return result


def _evaluate_cutoff(
    model: nn.Module,
    loader: DataLoader,
    device: torch.device,
    cutoff: float,
    *,
    butterworth_order: int,
    high_low_split: float,
    radial_bins: int,
) -> tuple[Row, list[Row], list[Row]]:
    feature_accumulators: dict[str, RadialPSDAccumulator] = {
        "input": RadialPSDAccumulator(
            high_low_split=high_low_split, radial_bins=radial_bins
        )
    }
    gate_accumulators: dict[str, GateRegionAccumulator] = {}
    gate_metadata: dict[str, tuple[str, int, str]] = {}
    handles: list[Any] = []

    def feature_hook(name: str):
        def hook(_module: nn.Module, _inputs: tuple[Tensor, ...], output: Tensor) -> None:
            accumulator = feature_accumulators.setdefault(
                name,
                RadialPSDAccumulator(
                    high_low_split=high_low_split, radial_bins=radial_bins
                ),
            )
            accumulator.update(output)

        return hook

    for stage_index, stage in enumerate(model.stages, start=1):
        handles.append(stage.register_forward_hook(feature_hook(f"stage{stage_index}")))
    handles.append(model.norm.register_forward_hook(feature_hook("pre_classifier")))
    for stage_name, stage_index, block_name, gate_module in _block_gates(model):
        key = f"{stage_name}.{block_name}"
        accumulator = GateRegionAccumulator(gate_module)
        gate_accumulators[key] = accumulator
        gate_metadata[key] = (stage_name, stage_index, block_name)

        def gate_hook(
            _module: nn.Module,
            inputs: tuple[Tensor, ...],
            accumulator: GateRegionAccumulator = accumulator,
        ) -> None:
            accumulator.update(inputs[0])

        handles.append(gate_module.register_forward_pre_hook(gate_hook))

    total = 0
    top1 = 0
    top5 = 0
    try:
        with torch.inference_mode():
            for images, targets in loader:
                images = images.to(device, non_blocking=device.type == "cuda")
                targets = targets.to(device, non_blocking=device.type == "cuda")
                filtered = torch_fft_lowpass(
                    images, cutoff, order=butterworth_order
                )
                feature_accumulators["input"].update(filtered)
                logits = model(filtered)
                predictions = logits.topk(5, dim=1).indices
                total += targets.numel()
                top1 += int((predictions[:, 0] == targets).sum())
                top5 += int((predictions == targets[:, None]).any(dim=1).sum())
    finally:
        for handle in handles:
            handle.remove()

    accuracy = {
        "cutoff": cutoff,
        "filter": "dc_only" if cutoff == 0 else "identity" if cutoff == 1 else "butterworth",
        "samples": total,
        "top1": 100.0 * top1 / total,
        "top5": 100.0 * top5 / total,
    }
    features = [
        {"cutoff": cutoff, "layer": name, **feature_accumulators[name].compute().to_dict()}
        for name in LAYER_ORDER
    ]
    gates = []
    for key, accumulator in gate_accumulators.items():
        stage_name, stage_index, block_name = gate_metadata[key]
        gates.append(
            {
                "cutoff": cutoff,
                "layer": key,
                "stage": stage_name,
                "stage_index": stage_index,
                "block": block_name,
                **accumulator.compute(),
            }
        )
    return accuracy, features, gates


def _add_feature_transfer(rows: list[Row]) -> None:
    baseline = {
        (row["gate"], row["seed"], row["layer"]): row
        for row in rows
        if float(row["cutoff"]) == 1.0
    }
    for row in rows:
        reference = baseline[(row["gate"], row["seed"], row["layer"])]
        if not row["valid"] or not reference["valid"]:
            row["centroid_delta_vs_identity"] = None
            row["high_low_log_ratio_vs_identity"] = None
            row["entropy_delta_vs_identity"] = None
            continue
        row["centroid_delta_vs_identity"] = (
            row["spectral_centroid"] - reference["spectral_centroid"]
        )
        if row["high_low_valid"] and reference["high_low_valid"]:
            epsilon = np.finfo(float).eps
            row["high_low_log_ratio_vs_identity"] = math.log(
                (row["high_low_ratio"] + epsilon)
                / (reference["high_low_ratio"] + epsilon)
            )
        else:
            row["high_low_log_ratio_vs_identity"] = None
        row["entropy_delta_vs_identity"] = (
            row["spectral_entropy"] - reference["spectral_entropy"]
        )


def _accuracy_auc(curve_rows: list[Row]) -> list[Row]:
    groups: dict[tuple[str, int], list[Row]] = defaultdict(list)
    for row in curve_rows:
        groups[(row["gate"], row["seed"])].append(row)
    result: list[Row] = []
    for (gate, seed), rows in sorted(groups.items()):
        rows = sorted(rows, key=lambda row: float(row["cutoff"]))
        x = np.asarray([row["cutoff"] for row in rows], dtype=np.float64)
        if x[0] != 0.0 or x[-1] != 1.0:
            raise ValueError("accuracy AUC requires cutoff endpoints 0 and 1")
        top1 = np.asarray([row["top1"] for row in rows], dtype=np.float64)
        top5 = np.asarray([row["top5"] for row in rows], dtype=np.float64)
        result.append(
            {
                "gate": gate,
                "seed": seed,
                "frequency_accuracy_auc_top1": float(np.trapezoid(top1, x)),
                "frequency_accuracy_auc_top5": float(np.trapezoid(top5, x)),
                "identity_top1": float(top1[-1]),
                "identity_top5": float(top5[-1]),
                "dc_top1": float(top1[0]),
                "cutoff_count": len(x),
            }
        )
    return result


def _format(value: Any) -> str:
    if value is None:
        return "NA"
    return f"{float(value):.6g}"


def _make_report(
    args: argparse.Namespace,
    manifest: list[Row],
    accuracy_summary: list[Row],
    auc_summary: list[Row],
    feature_summary: list[Row],
    gate_summary: list[Row],
    missing: list[str],
    sample_hash: str,
) -> str:
    partial = args.smoke or bool(missing) or any(
        row["checkpoint_epochs_completed"] < 100 for row in manifest
    )
    if partial:
        status = "ETA checkpoint smoke; not a final comparison"
    elif len(manifest) == 18:
        status = "complete formal checkpoint matrix"
    else:
        status = "complete requested checkpoint subset; formal merge pending"
    lines = [
        "# E1 Trained CIFAR-100 Feature Audit",
        "",
        f"Status: {status}.",
        "",
        "## Protocol",
        "",
        f"- Fixed test subset hash: `{sample_hash}`",
        f"- Samples per checkpoint/cutoff: {accuracy_summary[0]['samples_mean']:.0f}",
        f"- Checkpoint policy: `{args.checkpoint_name}` at fixed epoch {args.require_epochs_completed or 'recorded in manifest'}; checkpoint_best.pt is not used for model selection.",
        f"- Butterworth order: {args.butterworth_order}; cutoffs: {sorted(set(row['cutoff'] for row in accuracy_summary))}",
        "- Feature PSD is spatially centered and measured after each stage and after final norm.",
        "- Universal gate regions are x<0, 0<=x<6, and x>=6; actual clip crossing is only defined for ReLU6 and smooth-clipped gates.",
        "",
        "## Checkpoints",
        "",
        "| Gate | Seed | Epochs completed | Stored best Top-1 | Measured identity Top-1 |",
        "|---|---:|---:|---:|---:|",
    ]
    measured = {
        (row["gate"], row["seed"]): row
        for row in accuracy_summary
        if float(row["cutoff"]) == 1.0
    }
    for row in manifest:
        accuracy = measured[(row["gate"], row["seed"])]
        lines.append(
            f"| {row['gate']} | {row['seed']} | {row['checkpoint_epochs_completed']} | "
            f"{_format(row['checkpoint_best_top1'])} | {_format(accuracy['top1_mean'])} |"
        )
    lines.extend(
        [
            "",
            "## 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(
        [
            "",
            "## Identity-Input Feature Spectrum",
            "",
            "| Gate | Layer | Spatial 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(
        [
            "",
            "## Pre-Gate Regions on Identity Input",
            "",
            "| Gate | Stage | Negative | Active [0,6) | Above 6 | 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['actual_clip_crossing_fraction_mean'])} |"
        )
    lines.extend(
        [
            "",
            "## Interpretation Limits",
            "",
            "- CIFAR-100 S1 reaches 1x1 at stage4. Stage4 and pre_classifier are retained in the table but their spatial PSD fields are NA by definition.",
            "- AUC integrates classification accuracy over progressively less filtered normalized inputs. It is causal sensitivity to the filter protocol, not model function frequency.",
            "- Comparisons from an ETA checkpoint or incomplete seed matrix must not be used as final gate rankings.",
            "- Per-layer transfer deltas for every cutoff are in feature_metrics.csv; per-block gate statistics are in gate_regions.csv.",
            "",
        ]
    )
    return "\n".join(lines)


def main() -> None:
    args = parse_args()
    if args.smoke:
        args.allow_missing = True
        args.max_checkpoints = 1
        args.num_samples = min(args.num_samples, 64)
        args.workers = 0
        args.cutoffs = [0.0, 1.0]
        if args.output_dir is None:
            args.output_dir = OUTPUT_ROOT / "smoke_eta"
    output_dir = (args.output_dir or OUTPUT_ROOT).resolve()
    allowed_root = OUTPUT_ROOT.resolve()
    if output_dir != allowed_root and allowed_root not in output_dir.parents:
        raise ValueError(f"output must stay under {allowed_root}")
    output_dir.mkdir(parents=True, exist_ok=True)

    cutoffs = sorted(set(float(value) for value in args.cutoffs))
    if not cutoffs or cutoffs[0] != 0.0 or cutoffs[-1] != 1.0:
        raise ValueError("cutoffs must include exact endpoints 0 and 1")
    if args.num_samples <= 0 or args.batch_size <= 0:
        raise ValueError("num-samples and batch-size must be positive")
    specs, missing = discover_checkpoints(args)
    requested_device = args.device
    if requested_device.startswith("cuda") and not torch.cuda.is_available():
        device = torch.device("cpu")
    else:
        device = torch.device(requested_device)

    first_checkpoint = torch.load(specs[0].path, map_location="cpu", weights_only=False)
    dataset = _dataset_from_config(args.data_root, first_checkpoint["config"])
    sample_count = min(args.num_samples, len(dataset))
    generator = np.random.default_rng(args.sample_seed)
    indices = generator.choice(len(dataset), size=sample_count, replace=False).astype(np.int64)
    sample_hash = hashlib.sha256(indices.tobytes()).hexdigest()
    subset = Subset(dataset, indices.tolist())
    loader = DataLoader(
        subset,
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=args.workers,
        pin_memory=device.type == "cuda",
        persistent_workers=args.workers > 0,
    )
    (output_dir / "sample_indices.json").write_text(
        json.dumps(
            {
                "dataset": "CIFAR-100 test",
                "dataset_size": len(dataset),
                "sample_seed": args.sample_seed,
                "sample_count": sample_count,
                "sha256_int64_ordered": sample_hash,
                "indices": indices.tolist(),
            },
            indent=2,
        )
        + "\n",
        encoding="utf-8",
    )

    manifest_rows: list[Row] = []
    accuracy_rows: list[Row] = []
    feature_rows: list[Row] = []
    gate_rows: list[Row] = []
    normalization_reference = json.dumps(first_checkpoint["config"]["data"], sort_keys=True)
    for checkpoint_index, spec in enumerate(specs, start=1):
        model, config, manifest = _load_model(
            spec, device, args.require_epochs_completed
        )
        if json.dumps(config["data"], sort_keys=True) != normalization_reference:
            raise ValueError(f"data config differs across checkpoints: {spec.path}")
        manifest_rows.append(manifest)
        print(
            f"[{checkpoint_index}/{len(specs)}] {manifest['run_name']} "
            f"epoch={manifest['checkpoint_epochs_completed']}"
        )
        for cutoff in cutoffs:
            accuracy, features, gates = _evaluate_cutoff(
                model,
                loader,
                device,
                cutoff,
                butterworth_order=args.butterworth_order,
                high_low_split=args.high_low_split,
                radial_bins=args.radial_bins,
            )
            common = {
                "gate": spec.gate,
                "seed": spec.seed,
                "run_name": manifest["run_name"],
                "checkpoint_epochs_completed": manifest["checkpoint_epochs_completed"],
            }
            accuracy_rows.append({**common, **accuracy})
            feature_rows.extend({**common, **row} for row in features)
            gate_rows.extend({**common, **row} for row in gates)
        del model
        if device.type == "cuda":
            torch.cuda.empty_cache()

    _add_feature_transfer(feature_rows)
    auc_rows = _accuracy_auc(accuracy_rows)
    accuracy_summary = _aggregate(
        accuracy_rows,
        ("gate", "seed", "cutoff"),
        ("samples", "top1", "top5"),
    )
    auc_summary = _aggregate(
        auc_rows,
        ("gate",),
        (
            "frequency_accuracy_auc_top1",
            "frequency_accuracy_auc_top5",
            "identity_top1",
            "identity_top5",
            "dc_top1",
        ),
    )
    feature_identity = [row for row in feature_rows if float(row["cutoff"]) == 1.0]
    feature_summary = _aggregate(
        feature_identity,
        ("gate", "layer", "height", "width"),
        ("spectral_centroid", "high_low_ratio", "spectral_entropy"),
    )
    feature_summary.sort(key=lambda row: (row["gate"], LAYER_ORDER.index(row["layer"])))
    gate_identity = [row for row in gate_rows if float(row["cutoff"]) == 1.0]
    gate_summary = _aggregate(
        gate_identity,
        ("gate", "stage"),
        (
            "negative_fraction",
            "active_0_to_6_fraction",
            "above_reference_6_fraction",
            "actual_clip_crossing_fraction",
        ),
    )

    _write_csv(output_dir / "checkpoint_manifest.csv", manifest_rows)
    _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 / "feature_summary.csv", feature_summary)
    _write_csv(output_dir / "gate_summary.csv", gate_summary)

    results = {
        "schema_version": 1,
        "experiment_id": "E1-trained-cifar100-feature-audit",
        "timestamp_utc": datetime.now(UTC).isoformat(),
        "status": "smoke" if args.smoke else "full",
        "environment": {
            "python": sys.version,
            "platform": platform.platform(),
            "torch": torch.__version__,
            "requested_device": requested_device,
            "actual_device": str(device),
            "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None,
        },
        "protocol": {
            "checkpoint_root": str(args.checkpoint_root.resolve()),
            "checkpoint_name": args.checkpoint_name,
            "require_epochs_completed": args.require_epochs_completed,
            "data_root": str(args.data_root.resolve()),
            "sample_count": sample_count,
            "sample_seed": args.sample_seed,
            "sample_indices_sha256": sample_hash,
            "cutoffs": cutoffs,
            "butterworth_order": args.butterworth_order,
            "high_low_split": args.high_low_split,
            "radial_bins": args.radial_bins,
        },
        "missing_requested_checkpoints": missing,
        "checkpoint_manifest": manifest_rows,
        "accuracy_auc": auc_rows,
        "accuracy_auc_summary": auc_summary,
        "feature_identity_summary": feature_summary,
        "gate_identity_summary": gate_summary,
    }
    (output_dir / "results.json").write_text(
        json.dumps(results, indent=2, allow_nan=False) + "\n", encoding="utf-8"
    )
    report = _make_report(
        args,
        manifest_rows,
        accuracy_summary,
        auc_summary,
        feature_summary,
        gate_summary,
        missing,
        sample_hash,
    )
    (output_dir / "REPORT.md").write_text(report, encoding="utf-8")
    print(f"E1 trained feature audit complete: {output_dir}")


if __name__ == "__main__":
    main()