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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
#!/usr/bin/env python3
"""Evaluate cheap frozen-weight gate interventions on validation data."""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import sys
import time
from pathlib import Path
from typing import Any

import torch
from torch.nn import functional as F
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
from torchvision.transforms import InterpolationMode

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

from gmnet.analysis import (
    INTERVENTION_MODES,
    install_gate_interventions,
    load_model_checkpoint,
    set_intervention_mode,
    summarize_intervention_coherence,
)


DEFAULT_CHECKPOINT = Path("/nfs/ywang29/GmNet/gmnet_s3.npy")
DEFAULT_OUTPUT_DIR = Path("/tmp/gmnet_runs/e4_interventions")
DEFAULT_DATA_ROOTS = {
    "imagenet": Path("/s3-code/ywang29/datasets/imagenet-1k"),
    "cifar100": Path("/tmp/gmnet_data/cifar-100"),
}
ECE_BINS = 15


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT)
    parser.add_argument("--data-root", type=Path)
    parser.add_argument(
        "--data-source-uri",
        help="canonical upstream dataset URI recorded in result provenance",
    )
    parser.add_argument(
        "--data-staging-manifest",
        type=Path,
        help="JSON manifest proving how a local dataset cache was staged",
    )
    parser.add_argument(
        "--dataset",
        choices=("auto", "imagenet", "cifar100"),
        default="auto",
    )
    parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
    parser.add_argument("--batch-size", type=int, default=128)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument(
        "--max-samples",
        type=int,
        default=5_000,
        help="deterministic random validation subset size; 0 evaluates all samples",
    )
    parser.add_argument("--seed", type=int, default=20260712)
    parser.add_argument(
        "--device",
        default="cuda:0" if torch.cuda.is_available() else "cpu",
    )
    parser.add_argument(
        "--modes",
        nargs="+",
        choices=INTERVENTION_MODES,
        default=list(INTERVENTION_MODES),
    )
    return parser.parse_args()


def build_validation_loader(
    args: argparse.Namespace,
    checkpoint_audit: dict[str, Any],
) -> tuple[DataLoader, dict[str, Any]]:
    checkpoint_dataset = str(
        checkpoint_audit.get("data_config", {}).get("dataset", "imagenet")
    ).lower()
    dataset_name = args.dataset if args.dataset != "auto" else checkpoint_dataset
    dataset_name = dataset_name.replace("-", "")
    if dataset_name not in DEFAULT_DATA_ROOTS:
        raise ValueError(f"unsupported validation dataset: {dataset_name}")
    data_root = (
        args.data_root
        if args.data_root is not None
        else DEFAULT_DATA_ROOTS[dataset_name]
    ).expanduser().resolve()

    if dataset_name == "imagenet":
        validation_root = data_root / "val"
        if not validation_root.is_dir():
            raise FileNotFoundError(
                f"ImageNet validation split not found: {validation_root}"
            )
        transform = transforms.Compose(
            [
                transforms.Resize(256, interpolation=InterpolationMode.BICUBIC),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=(0.485, 0.456, 0.406),
                    std=(0.229, 0.224, 0.225),
                ),
            ]
        )
        dataset = datasets.ImageFolder(validation_root, transform=transform)
        expected_classes = 1_000
        preprocess = "resize256_bicubic_centercrop224_imagenet_normalization"
    else:
        data_config = checkpoint_audit.get("data_config", {})
        mean = tuple(data_config.get("mean", (0.5071, 0.4867, 0.4408)))
        std = tuple(data_config.get("std", (0.2675, 0.2565, 0.2761)))
        transform = transforms.Compose(
            [transforms.ToTensor(), transforms.Normalize(mean=mean, std=std)]
        )
        dataset = datasets.CIFAR100(
            data_root,
            train=False,
            transform=transform,
            download=False,
        )
        validation_root = data_root
        expected_classes = 100
        preprocess = "tensor_cifar100_paper_normalization"
    if len(dataset.classes) != expected_classes:
        raise ValueError(
            f"expected {expected_classes} classes, found {len(dataset.classes)}"
        )

    total_samples = len(dataset)
    requested = total_samples if args.max_samples == 0 else args.max_samples
    sample_count = min(requested, total_samples)
    if sample_count == total_samples:
        indices = list(range(total_samples))
        subset_method = "full_validation_set_in_canonical_order"
    else:
        generator = torch.Generator().manual_seed(args.seed)
        indices = torch.randperm(
            total_samples, generator=generator
        )[:sample_count].tolist()
        subset_method = "torch_randperm_without_replacement"
    subset = Subset(dataset, indices)
    loader = DataLoader(
        subset,
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=args.workers,
        pin_memory=args.device.startswith("cuda"),
        persistent_workers=args.workers > 0,
    )
    index_digest = hashlib.sha256(
        ",".join(str(index) for index in indices).encode("ascii")
    ).hexdigest()
    provenance: dict[str, Any] = {
        "source_uri": args.data_source_uri or str(validation_root),
        "access_path": str(validation_root),
        "access_mode": "direct_path",
    }
    if args.data_staging_manifest is not None:
        manifest_path = args.data_staging_manifest.expanduser().resolve()
        if not manifest_path.is_file():
            raise FileNotFoundError(
                f"data staging manifest not found: {manifest_path}"
            )
        manifest_bytes = manifest_path.read_bytes()
        manifest = json.loads(manifest_bytes)
        if not isinstance(manifest, dict):
            raise TypeError("data staging manifest must be a JSON mapping")
        manifest_source = manifest.get("source")
        if not isinstance(manifest_source, str) or not manifest_source:
            raise ValueError("data staging manifest must identify its source")
        expected_manifest_values = {
            "classes": len(dataset.classes),
            "images": total_samples,
        }
        for key, expected_value in expected_manifest_values.items():
            if key in manifest and int(manifest[key]) != expected_value:
                raise ValueError(
                    f"staging manifest {key}={manifest[key]} does not match "
                    f"loaded dataset value {expected_value}"
                )
        provenance.update(
            {
                "access_mode": "local_staging_cache",
                "staging_manifest_path": str(manifest_path),
                "staging_manifest_sha256": hashlib.sha256(
                    manifest_bytes
                ).hexdigest(),
                "staging_manifest": manifest,
            }
        )
    return loader, {
        "root": str(validation_root),
        "dataset": dataset_name,
        "full_validation_samples": total_samples,
        "evaluated_samples": sample_count,
        "subset_method": subset_method,
        "subset_seed": args.seed,
        "subset_indices_sha256": index_digest,
        "class_count": len(dataset.classes),
        "preprocess": preprocess,
        "provenance": provenance,
    }


def _empty_metrics() -> dict[str, Any]:
    return {
        "samples": 0.0,
        "top1_correct": 0.0,
        "top5_correct": 0.0,
        "baseline_agreement": 0.0,
        "kl_from_baseline_sum": 0.0,
        "logit_squared_error_sum": 0.0,
        "logit_values": 0.0,
        "nll_sum": 0.0,
        "ece_counts": [0.0] * ECE_BINS,
        "ece_confidence_sums": [0.0] * ECE_BINS,
        "ece_correct_sums": [0.0] * ECE_BINS,
    }


def _update_metrics(
    metrics: dict[str, Any],
    logits: torch.Tensor,
    targets: torch.Tensor,
    baseline_logits: torch.Tensor,
) -> None:
    batch_size = targets.numel()
    predictions = logits.argmax(dim=1)
    baseline_predictions = baseline_logits.argmax(dim=1)
    top5 = logits.topk(5, dim=1).indices
    probabilities = F.softmax(logits, dim=1)
    confidence, _ = probabilities.max(dim=1)
    metrics["samples"] += batch_size
    metrics["top1_correct"] += (predictions == targets).sum().item()
    metrics["top5_correct"] += top5.eq(targets[:, None]).any(dim=1).sum().item()
    metrics["baseline_agreement"] += (
        predictions == baseline_predictions
    ).sum().item()
    metrics["kl_from_baseline_sum"] += F.kl_div(
        F.log_softmax(logits, dim=1),
        F.softmax(baseline_logits, dim=1),
        reduction="sum",
    ).item()
    metrics["logit_squared_error_sum"] += (
        logits - baseline_logits
    ).square().sum().item()
    metrics["logit_values"] += logits.numel()
    metrics["nll_sum"] += F.cross_entropy(
        logits, targets, reduction="sum"
    ).item()
    bin_indices = torch.clamp((confidence * ECE_BINS).long(), max=ECE_BINS - 1)
    correct = predictions.eq(targets).float()
    for bin_index in range(ECE_BINS):
        mask = bin_indices.eq(bin_index)
        if mask.any():
            metrics["ece_counts"][bin_index] += mask.sum().item()
            metrics["ece_confidence_sums"][bin_index] += confidence[mask].sum().item()
            metrics["ece_correct_sums"][bin_index] += correct[mask].sum().item()


def _finalize_metrics(metrics: dict[str, Any]) -> dict[str, float | int]:
    samples = int(metrics["samples"])
    if samples == 0:
        raise ValueError("no samples were evaluated")
    ece = 0.0
    for count, confidence_sum, correct_sum in zip(
        metrics["ece_counts"],
        metrics["ece_confidence_sums"],
        metrics["ece_correct_sums"],
        strict=True,
    ):
        if count:
            ece += count / samples * abs(confidence_sum / count - correct_sum / count)
    return {
        "samples": samples,
        "top1_percent": 100.0 * metrics["top1_correct"] / samples,
        "top5_percent": 100.0 * metrics["top5_correct"] / samples,
        "nll": metrics["nll_sum"] / samples,
        "ece_percent": 100.0 * ece,
        "prediction_agreement_with_baseline_percent": (
            100.0 * metrics["baseline_agreement"] / samples
        ),
        "mean_kl_from_baseline": max(
            metrics["kl_from_baseline_sum"] / samples, 0.0
        ),
        "logit_rmse_from_baseline": math.sqrt(
            metrics["logit_squared_error_sum"] / metrics["logit_values"]
        ),
    }


def render_markdown(result: dict[str, Any]) -> str:
    rows = []
    for mode, metrics in result["interventions"].items():
        coherence = metrics["intervention_reference_coherence"][
            "mean_gate_input_pearson"
        ]
        rows.append(
            f"| {mode} | {metrics['top1_percent']:.3f} | "
            f"{metrics['top5_percent']:.3f} | "
            f"{metrics['nll']:.5f} | {metrics['ece_percent']:.3f} | "
            f"{metrics['prediction_agreement_with_baseline_percent']:.3f} | "
            f"{metrics['mean_kl_from_baseline']:.6f} | "
            f"{coherence!s} |"
        )
    audit = result["checkpoint"]
    data = result["data"]
    return "\n".join(
        [
            "# E4 Frozen Gate Intervention Audit",
            "",
            "## Scope",
            "",
            f"- Checkpoint: `{audit['path']}` (`{audit['sha256']}`).",
            f"- Selected topology: `{audit['selected_topology']}`.",
            f"- Data: deterministic random {data['evaluated_samples']}-image subset "
            f"of {data['full_validation_samples']} {data['dataset']} validation "
            "images.",
            f"- Data source: `{data['provenance']['source_uri']}` via "
            f"`{data['provenance']['access_mode']}` at "
            f"`{data['provenance']['access_path']}`.",
            "- This is a frozen-checkpoint sensitivity diagnostic. It is not a "
            "matched-retraining causal accuracy result.",
            "",
            "## Results",
            "",
            "| Intervention | Top-1 (%) | Top-5 (%) | NLL | ECE (%) | "
            "Baseline agreement (%) | KL from baseline | Reference Pearson |",
            "|---|---:|---:|---:|---:|---:|---:|---:|",
            *rows,
            "",
            "`stop_gradient` is intentionally excluded: it is forward-identical "
            "during inference and can only be evaluated through retraining. "
            "`mean_gate` uses the per-channel mean gate value over batch and "
            "spatial dimensions at every block.",
            "",
        ]
    )


def main() -> int:
    args = parse_args()
    if "baseline" not in args.modes:
        raise ValueError("baseline must be included to compute paired diagnostics")
    device = torch.device(args.device)
    if device.type == "cuda":
        torch.cuda.set_device(device)

    model, checkpoint_audit = load_model_checkpoint(args.checkpoint, device=device)
    installed_gates = install_gate_interventions(model, seed=args.seed)
    loader, data_audit = build_validation_loader(args, checkpoint_audit)
    accumulators = {mode: _empty_metrics() for mode in args.modes}

    started = time.time()
    model.eval()
    with torch.inference_mode():
        for images, targets in loader:
            images = images.to(device, non_blocking=True)
            targets = targets.to(device, non_blocking=True)

            set_intervention_mode(model, "baseline")
            baseline_logits = model(images)
            for mode in args.modes:
                if mode == "baseline":
                    logits = baseline_logits
                else:
                    set_intervention_mode(model, mode)
                    logits = model(images)
                _update_metrics(
                    accumulators[mode], logits, targets, baseline_logits
                )

    if device.type == "cuda":
        torch.cuda.synchronize(device)
    interventions = {}
    for mode, accumulator in accumulators.items():
        metrics = _finalize_metrics(accumulator)
        metrics["intervention_reference_coherence"] = (
            summarize_intervention_coherence(model, mode)
        )
        interventions[mode] = metrics

    result = {
        "schema_version": 1,
        "experiment": "E4",
        "status": "completed_frozen_checkpoint_diagnostic",
        "claim_scope": (
            "Frozen-checkpoint forward intervention only. Accuracy differences "
            "do not establish matched-retraining causality."
        ),
        "device": str(device),
        "torch_version": torch.__version__,
        "elapsed_seconds": time.time() - started,
        "installed_gate_count": installed_gates,
        "intervention_scope": "all_self_gate_blocks_jointly",
        "intervention_definitions": {
            "batch_shuffle": "fixed seeded batch permutation per gate block",
            "spatial_shuffle": "fixed seeded spatial permutation per gate block",
            "channel_shuffle": "fixed seeded channel permutation per gate block",
            "mean_gate": (
                "per-channel gate-value mean over batch and spatial dimensions"
            ),
            "stop_gradient": "training-only; deliberately not evaluated",
        },
        "checkpoint": checkpoint_audit,
        "data": data_audit,
        "interventions": interventions,
    }
    args.output_dir.mkdir(parents=True, exist_ok=True)
    json_path = args.output_dir / "results.json"
    markdown_path = args.output_dir / "RESULTS.md"
    json_path.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8")
    markdown_path.write_text(render_markdown(result), encoding="utf-8")
    print(json.dumps({"results": str(json_path), "markdown": str(markdown_path)}))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())