Download gmnet/code/journal_exp/scripts/evaluate_imagenet_long.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 72.2 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/evaluate_imagenet_long.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/code/journal_exp/scripts/evaluate_imagenet_long.py
-
curl -L -o evaluate_imagenet_long.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/evaluate_imagenet_long.py
72.2 kB
| #!/usr/bin/env python3 | |
| """Strict fixed-last evaluation for completed ImageNet-1K long runs.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import platform | |
| import re | |
| import shutil | |
| import sys | |
| import tempfile | |
| from dataclasses import dataclass, field | |
| 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.nn import functional as F | |
| from torch.utils.data import DataLoader, Dataset | |
| from torchvision import datasets, transforms | |
| from torchvision.transforms import InterpolationMode | |
| PROJECT_ROOT = Path(__file__).resolve().parents[1] | |
| if str(PROJECT_ROOT) not in sys.path: | |
| sys.path.insert(0, str(PROJECT_ROOT)) | |
| from gmnet.evaluation.metrics import classification_metrics | |
| from gmnet.data import imagefolder_split_fingerprint | |
| from gmnet.engine import state_dict_schema_sha256 | |
| from gmnet.models import ( | |
| CHANNEL_DERANGEMENT_INTERVENTIONS, | |
| STOP_GRADIENT_INTERVENTIONS, | |
| SUPPORTED_GATE_INTERVENTIONS, | |
| GmNetBlock, | |
| SmoothClippedSelfGate, | |
| create_gmnet, | |
| ) | |
| PROTOCOL_VERSION = "imagenet1k-fixed-last-v2" | |
| EXPECTED_SAMPLES = 50_000 | |
| EXPECTED_TRAIN_SAMPLES = 1_281_167 | |
| EXPECTED_CLASSES = 1_000 | |
| ECE_BINS = 15 | |
| GATE_INTERVENTION_MODES = SUPPORTED_GATE_INTERVENTIONS | |
| CHANNEL_DERANGEMENT_MODES = CHANNEL_DERANGEMENT_INTERVENTIONS | |
| STOP_GRADIENT_MODES = STOP_GRADIENT_INTERVENTIONS | |
| DEFAULT_GATE_INTERVENTION_SEED = 0 | |
| GATE_INTERVENTION_BLOCK_SEED_STRIDE = 10_007 | |
| COHERENCE_MAX_VALUES = 65_536 | |
| REQUIRED_FILES = ( | |
| "results.json", | |
| "per_sample.npz", | |
| "gate_diagnostics.json", | |
| "config.json", | |
| "data_manifest.json", | |
| "artifacts.json", | |
| "COMPLETE", | |
| ) | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--checkpoint", required=True, type=Path) | |
| parser.add_argument("--data-root", type=Path) | |
| parser.add_argument("--output-dir", type=Path) | |
| parser.add_argument("--device", default="cuda:0") | |
| parser.add_argument("--batch-size", type=int, default=None) | |
| parser.add_argument("--workers", type=int, default=None) | |
| parser.add_argument("--overwrite", action="store_true") | |
| parser.add_argument( | |
| "--check-only", | |
| action="store_true", | |
| help="validate an existing official_eval directory without loading data/model", | |
| ) | |
| return parser.parse_args() | |
| def file_sha256(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(chunk_size), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def stable_sha256(value: Any) -> str: | |
| encoded = json.dumps( | |
| value, | |
| sort_keys=True, | |
| separators=(",", ":"), | |
| ensure_ascii=True, | |
| allow_nan=False, | |
| ).encode("utf-8") | |
| return hashlib.sha256(encoded).hexdigest() | |
| def write_json(path: Path, value: Any) -> None: | |
| path.write_text( | |
| json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n", | |
| encoding="utf-8", | |
| ) | |
| def configured_gate_intervention(model_config: dict[str, Any]) -> dict[str, Any]: | |
| """Normalize the checkpoint-owned intervention identity. | |
| Historical checkpoints predate these fields. They are reconstructed as the | |
| forward-compatible baseline while retaining an explicit marker that the | |
| identity was not present in their resolved configuration. | |
| """ | |
| has_mode = "gate_intervention" in model_config | |
| has_seed = "gate_intervention_seed" in model_config | |
| if has_mode != has_seed: | |
| raise ValueError( | |
| "model.gate_intervention and model.gate_intervention_seed must be " | |
| "specified together" | |
| ) | |
| mode = str(model_config.get("gate_intervention", "baseline")) | |
| if mode not in GATE_INTERVENTION_MODES: | |
| choices = ", ".join(GATE_INTERVENTION_MODES) | |
| raise ValueError( | |
| f"unsupported model.gate_intervention {mode!r}; expected one of: {choices}" | |
| ) | |
| seed_value = model_config.get( | |
| "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED | |
| ) | |
| if isinstance(seed_value, bool): | |
| raise TypeError("model.gate_intervention_seed must be an integer") | |
| try: | |
| seed = int(seed_value) | |
| except (TypeError, ValueError) as error: | |
| raise TypeError("model.gate_intervention_seed must be an integer") from error | |
| if seed < 0: | |
| raise ValueError("model.gate_intervention_seed cannot be negative") | |
| return { | |
| "mode": mode, | |
| "seed": seed, | |
| "config_explicit": has_mode, | |
| "block_seed_stride": GATE_INTERVENTION_BLOCK_SEED_STRIDE, | |
| } | |
| def resolve_official_batch_size( | |
| requested: int | None, configured: int, intervention_mode: str | |
| ) -> int: | |
| """Resolve evaluation batching and freeze sample-pairing interventions.""" | |
| batch_size = int(requested if requested is not None else configured) | |
| if batch_size <= 0: | |
| raise ValueError("official evaluation batch size must be positive") | |
| if intervention_mode == "batch_derangement": | |
| if batch_size != int(configured): | |
| raise ValueError( | |
| "batch_derangement official evaluation requires the configured " | |
| f"eval_batch_size={configured}, got {batch_size}" | |
| ) | |
| tail = EXPECTED_SAMPLES % batch_size | |
| if batch_size < 2 or tail == 1: | |
| raise ValueError( | |
| "batch_derangement official evaluation requires every batch to " | |
| "contain at least two samples" | |
| ) | |
| return batch_size | |
| def validate_checkpoint_identity( | |
| checkpoint_path: Path, checkpoint: dict[str, Any] | |
| ) -> dict[str, Any]: | |
| """Enforce the fixed-last, fully completed ImageNet protocol.""" | |
| if checkpoint_path.name != "checkpoint_last.pt": | |
| raise ValueError( | |
| "official ImageNet evaluation only accepts a file named checkpoint_last.pt" | |
| ) | |
| required = { | |
| "model", | |
| "config", | |
| "config_fingerprint", | |
| "epoch", | |
| "global_step", | |
| "epoch_complete", | |
| "steps_in_epoch", | |
| "expected_steps_per_epoch", | |
| "training_complete", | |
| "parameter_count", | |
| "model_state_schema_sha256", | |
| "run_name", | |
| "seed", | |
| "world_size", | |
| "data_manifest", | |
| } | |
| missing = sorted(required - checkpoint.keys()) | |
| if missing: | |
| raise ValueError(f"checkpoint is missing required fields: {missing}") | |
| config = checkpoint["config"] | |
| if not isinstance(config, dict): | |
| raise TypeError("checkpoint config must be a mapping") | |
| train = config.get("train") | |
| model = config.get("model") | |
| data = config.get("data") | |
| if not all(isinstance(value, dict) for value in (train, model, data)): | |
| raise ValueError("checkpoint must contain train/model/data configuration mappings") | |
| epochs = int(train["epochs"]) | |
| expected_epoch = epochs - 1 | |
| epoch = int(checkpoint["epoch"]) | |
| if epoch != expected_epoch: | |
| raise RuntimeError( | |
| f"training is incomplete or not fixed-last: epoch={epoch}, " | |
| f"expected exactly train.epochs-1={expected_epoch}" | |
| ) | |
| if checkpoint["epoch_complete"] is not True: | |
| raise RuntimeError("official checkpoint does not contain a complete final epoch") | |
| if checkpoint["training_complete"] is not True: | |
| raise RuntimeError("official checkpoint is not marked training_complete") | |
| dataset_name = str(data.get("dataset", "")).lower() | |
| if dataset_name not in {"imagenet", "imagefolder"}: | |
| raise ValueError(f"official evaluator requires ImageNet, got {dataset_name!r}") | |
| if int(data.get("num_classes", -1)) != EXPECTED_CLASSES: | |
| raise ValueError("data.num_classes must be 1000") | |
| if int(model.get("num_classes", -1)) != EXPECTED_CLASSES: | |
| raise ValueError("model.num_classes must be 1000") | |
| config_hash = stable_sha256(config) | |
| recorded_hash = checkpoint["config_fingerprint"] | |
| if recorded_hash != config_hash: | |
| raise ValueError( | |
| "checkpoint config fingerprint mismatch: " | |
| f"recorded={recorded_hash}, computed={config_hash}" | |
| ) | |
| manifest = checkpoint["data_manifest"] | |
| if not isinstance(manifest, dict): | |
| raise TypeError("checkpoint data_manifest must be a mapping") | |
| if int(manifest.get("num_classes", -1)) != EXPECTED_CLASSES: | |
| raise ValueError("checkpoint data manifest does not contain 1000 classes") | |
| train_samples = int(manifest.get("samples", {}).get("train", -1)) | |
| if train_samples != EXPECTED_TRAIN_SAMPLES: | |
| raise ValueError( | |
| "checkpoint data manifest does not contain 1281167 train samples" | |
| ) | |
| if int(manifest.get("samples", {}).get("val", -1)) != EXPECTED_SAMPLES: | |
| raise ValueError("checkpoint data manifest does not contain 50000 val samples") | |
| world_size = int(checkpoint["world_size"]) | |
| batch_size = int(data.get("batch_size", 0)) | |
| if world_size <= 0 or batch_size <= 0: | |
| raise ValueError("world_size and data.batch_size must be positive") | |
| expected_steps_per_epoch = train_samples // (world_size * batch_size) | |
| if int(checkpoint["expected_steps_per_epoch"]) != expected_steps_per_epoch: | |
| raise RuntimeError( | |
| "checkpoint expected_steps_per_epoch does not match the ImageNet recipe: " | |
| f"recorded={checkpoint['expected_steps_per_epoch']}, " | |
| f"derived={expected_steps_per_epoch}" | |
| ) | |
| if int(checkpoint["steps_in_epoch"]) != expected_steps_per_epoch: | |
| raise RuntimeError("checkpoint final epoch did not contain every optimizer step") | |
| expected_global_step = epochs * expected_steps_per_epoch | |
| if int(checkpoint["global_step"]) != expected_global_step: | |
| raise RuntimeError( | |
| "checkpoint global_step does not prove complete training: " | |
| f"recorded={checkpoint['global_step']}, expected={expected_global_step}" | |
| ) | |
| parameter_count = int(checkpoint["parameter_count"]) | |
| if parameter_count <= 0: | |
| raise ValueError("checkpoint parameter_count must be positive") | |
| checkpoint_schema_hash = state_dict_schema_sha256(checkpoint["model"]) | |
| if checkpoint["model_state_schema_sha256"] != checkpoint_schema_hash: | |
| raise ValueError("checkpoint model state schema hash is invalid") | |
| intervention = configured_gate_intervention(model) | |
| return { | |
| "epochs": epochs, | |
| "epoch": epoch, | |
| "global_step": int(checkpoint["global_step"]), | |
| "epoch_complete": True, | |
| "steps_in_epoch": expected_steps_per_epoch, | |
| "expected_steps_per_epoch": expected_steps_per_epoch, | |
| "training_complete": True, | |
| "expected_global_step": expected_global_step, | |
| "world_size": world_size, | |
| "parameter_count": parameter_count, | |
| "model_state_schema_sha256": checkpoint_schema_hash, | |
| "config_sha256": config_hash, | |
| "data_manifest_sha256": manifest.get("manifest_sha256"), | |
| "gate_intervention": intervention, | |
| } | |
| def _interpolation(name: str) -> InterpolationMode: | |
| choices = { | |
| "bicubic": InterpolationMode.BICUBIC, | |
| "bilinear": InterpolationMode.BILINEAR, | |
| "nearest": InterpolationMode.NEAREST, | |
| } | |
| try: | |
| return choices[name.lower()] | |
| except KeyError as error: | |
| raise ValueError(f"unsupported interpolation: {name}") from error | |
| def imagenet_val_transform(data_config: dict[str, Any]) -> transforms.Compose: | |
| input_size = int(data_config.get("input_size", 224)) | |
| crop_pct = float(data_config.get("crop_pct", 0.875)) | |
| resize_size = int(input_size / crop_pct) | |
| return transforms.Compose( | |
| [ | |
| transforms.Resize( | |
| resize_size, | |
| interpolation=_interpolation(str(data_config.get("interpolation", "bicubic"))), | |
| ), | |
| transforms.CenterCrop(input_size), | |
| transforms.ToTensor(), | |
| transforms.Normalize( | |
| tuple(data_config.get("mean", (0.485, 0.456, 0.406))), | |
| tuple(data_config.get("std", (0.229, 0.224, 0.225))), | |
| ), | |
| ] | |
| ) | |
| class IndexedImageFolder(Dataset[tuple[Tensor, int, int]]): | |
| def __init__(self, root: Path, transform: transforms.Compose) -> None: | |
| self.dataset = datasets.ImageFolder(root, transform=transform) | |
| def __len__(self) -> int: | |
| return len(self.dataset) | |
| def __getitem__(self, index: int) -> tuple[Tensor, int, int]: | |
| image, target = self.dataset[index] | |
| return image, int(target), index | |
| def imagefolder_data_manifest( | |
| dataset: IndexedImageFolder, val_root: Path | |
| ) -> dict[str, Any]: | |
| imagefolder = dataset.dataset | |
| if len(imagefolder) != EXPECTED_SAMPLES: | |
| raise RuntimeError( | |
| f"expected exactly {EXPECTED_SAMPLES} ImageNet val samples, got {len(imagefolder)}" | |
| ) | |
| if len(imagefolder.classes) != EXPECTED_CLASSES: | |
| raise RuntimeError( | |
| f"expected exactly {EXPECTED_CLASSES} ImageNet classes, " | |
| f"got {len(imagefolder.classes)}" | |
| ) | |
| class_hash = stable_sha256(imagefolder.class_to_idx) | |
| fingerprint = imagefolder_split_fingerprint(imagefolder, val_root) | |
| payload = { | |
| "schema_version": 2, | |
| "dataset": "imagenet", | |
| "split": "val", | |
| "samples": len(imagefolder), | |
| "num_classes": len(imagefolder.classes), | |
| "class_to_idx_sha256": class_hash, | |
| "sample_fingerprint_kind": ( | |
| "relative_path_and_target_plus_sampled_raw_file_bytes" | |
| ), | |
| **fingerprint, | |
| } | |
| payload["evaluation_manifest_sha256"] = stable_sha256(payload) | |
| return payload | |
| def validate_data_against_checkpoint( | |
| current: dict[str, Any], checkpoint_manifest: dict[str, Any] | |
| ) -> None: | |
| expected_class_hash = checkpoint_manifest.get("class_to_idx_sha256") | |
| expected_val_hash = checkpoint_manifest.get("sample_index_sha256", {}).get("val") | |
| expected_content_hash = checkpoint_manifest.get("sampled_content_sha256", {}).get( | |
| "val" | |
| ) | |
| expected_content_samples = checkpoint_manifest.get( | |
| "sampled_content_samples", {} | |
| ).get("val") | |
| mismatches = [] | |
| if current["class_to_idx_sha256"] != expected_class_hash: | |
| mismatches.append( | |
| "class_to_idx_sha256 " | |
| f"checkpoint={expected_class_hash} current={current['class_to_idx_sha256']}" | |
| ) | |
| if current["sample_index_sha256"] != expected_val_hash: | |
| mismatches.append( | |
| "val sample_index_sha256 " | |
| f"checkpoint={expected_val_hash} current={current['sample_index_sha256']}" | |
| ) | |
| if current["sampled_content_sha256"] != expected_content_hash: | |
| mismatches.append( | |
| "val sampled_content_sha256 " | |
| f"checkpoint={expected_content_hash} " | |
| f"current={current['sampled_content_sha256']}" | |
| ) | |
| if current["sampled_content_samples"] != expected_content_samples: | |
| mismatches.append( | |
| "val sampled_content_samples " | |
| f"checkpoint={expected_content_samples} " | |
| f"current={current['sampled_content_samples']}" | |
| ) | |
| if mismatches: | |
| raise RuntimeError("evaluation data differs from training manifest: " + "; ".join(mismatches)) | |
| def build_model(checkpoint: dict[str, Any], device: torch.device) -> nn.Module: | |
| model_config = dict(checkpoint["config"]["model"]) | |
| variant = str(model_config.pop("variant")) | |
| num_classes = int(model_config.pop("num_classes")) | |
| 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"checkpoint/model mismatch: {incompatible}") | |
| if bool(checkpoint["config"]["train"].get("channels_last", False)): | |
| model = model.to(memory_format=torch.channels_last) | |
| return model.to(device).eval() | |
| def validate_model_gate_intervention( | |
| model: nn.Module, expected: dict[str, Any] | |
| ) -> dict[str, Any]: | |
| """Prove that checkpoint configuration selected the reconstructed mode.""" | |
| actual_mode = str(getattr(model, "gate_intervention", "baseline")) | |
| actual_seed = int( | |
| getattr(model, "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED) | |
| ) | |
| if actual_mode != expected["mode"] or actual_seed != int(expected["seed"]): | |
| raise RuntimeError( | |
| "reconstructed gate intervention differs from checkpoint config: " | |
| f"configured=({expected['mode']}, {expected['seed']}), " | |
| f"model=({actual_mode}, {actual_seed})" | |
| ) | |
| return { | |
| **expected, | |
| "model_mode": actual_mode, | |
| "model_seed": actual_seed, | |
| } | |
| def validate_model_topology(model: nn.Module, identity: dict[str, Any]) -> dict[str, Any]: | |
| parameter_count = sum(parameter.numel() for parameter in model.parameters()) | |
| schema_hash = state_dict_schema_sha256(model.state_dict()) | |
| if parameter_count != int(identity["parameter_count"]): | |
| raise RuntimeError( | |
| "configured model parameter count differs from checkpoint: " | |
| f"model={parameter_count}, checkpoint={identity['parameter_count']}" | |
| ) | |
| if schema_hash != identity["model_state_schema_sha256"]: | |
| raise RuntimeError("configured model state schema differs from checkpoint") | |
| return { | |
| "parameter_count": parameter_count, | |
| "model_state_schema_sha256": schema_hash, | |
| "state_tensor_count": len(model.state_dict()), | |
| } | |
| class GateRegionAccumulator: | |
| module_name: str | |
| stage: int | |
| block: int | |
| gate: nn.Module | |
| global_block_index: int = 0 | |
| intervention_mode: str = "baseline" | |
| intervention_seed: int = DEFAULT_GATE_INTERVENTION_SEED | |
| gate_permutation: Tensor | None = None | |
| native_intervention_metadata: dict[str, Any] | None = None | |
| counts: Tensor | None = None | |
| actual_crossing: Tensor | None = None | |
| coherence: dict[str, Any] | None = None | |
| batch_derangements: dict[int, dict[str, Any]] = field(default_factory=dict) | |
| def clip_kind(self) -> str | None: | |
| if isinstance(self.gate, SmoothClippedSelfGate): | |
| return ( | |
| "smooth_learned_clip" | |
| if self.gate.trainable | |
| else "smooth_fixed_clip" | |
| ) | |
| if getattr(self.gate, "name", None) in {"relu6_self", "relu6_only"}: | |
| return "relu6_fixed_clip" | |
| return None | |
| def update(self, value: Tensor) -> None: | |
| value = value.detach() | |
| if self.coherence is None: | |
| self.coherence = self._compute_coherence(value) | |
| self._record_batch_derangement(value) | |
| finite = torch.isfinite(value).sum(dtype=torch.int64) | |
| negative = (value < 0).sum(dtype=torch.int64) | |
| above_six = (value >= 6).sum(dtype=torch.int64) | |
| active = finite - negative - above_six | |
| batch_counts = torch.stack( | |
| ( | |
| torch.as_tensor(value.numel(), device=value.device, dtype=torch.int64), | |
| finite, | |
| negative, | |
| active, | |
| above_six, | |
| ) | |
| ) | |
| if self.counts is None: | |
| self.counts = batch_counts | |
| else: | |
| self.counts += batch_counts | |
| crossing: Tensor | None = None | |
| if isinstance(self.gate, SmoothClippedSelfGate): | |
| crossing = (value >= self.gate.clip_value.detach()).sum(dtype=torch.int64) | |
| elif self.clip_kind == "relu6_fixed_clip": | |
| crossing = above_six | |
| if crossing is not None: | |
| if self.actual_crossing is None: | |
| self.actual_crossing = crossing | |
| else: | |
| self.actual_crossing += crossing | |
| def _record_batch_derangement(self, value: Tensor) -> None: | |
| if self.intervention_mode != "batch_derangement": | |
| return | |
| batch_size = int(value.shape[0]) | |
| shift_method = getattr(self.gate, "batch_derangement_shift", None) | |
| if not callable(shift_method): | |
| raise RuntimeError( | |
| f"{self.module_name} does not expose its batch derangement shift" | |
| ) | |
| shift = int(shift_method(batch_size)) | |
| permutation = ( | |
| torch.arange(batch_size, dtype=torch.int64) + shift | |
| ) % batch_size | |
| encoded = permutation.numpy().astype("<i8", copy=False).tobytes(order="C") | |
| identity = { | |
| "local_batch_size": batch_size, | |
| "shift": shift, | |
| "source_index_sha256": hashlib.sha256(encoded).hexdigest(), | |
| "encoding": "little_endian_int64_c_order", | |
| "is_bijection": bool( | |
| torch.equal( | |
| torch.sort(permutation).values, | |
| torch.arange(batch_size, dtype=torch.int64), | |
| ) | |
| ), | |
| "fixed_points": int( | |
| (permutation == torch.arange(batch_size, dtype=torch.int64)) | |
| .sum() | |
| .item() | |
| ), | |
| } | |
| record = self.batch_derangements.get(batch_size) | |
| if record is None: | |
| self.batch_derangements[batch_size] = { | |
| **identity, | |
| "batches": 1, | |
| "receiver_samples": batch_size, | |
| } | |
| return | |
| for key, expected in identity.items(): | |
| if record.get(key) != expected: | |
| raise RuntimeError( | |
| f"{self.module_name} batch derangement drifted for " | |
| f"local batch size {batch_size}: {key}" | |
| ) | |
| record["batches"] = int(record["batches"]) + 1 | |
| record["receiver_samples"] = int(record["receiver_samples"]) + batch_size | |
| def _compute_coherence(self, value: Tensor) -> dict[str, Any]: | |
| # Evaluation is canonically ordered, so the first image is ImageNet val | |
| # sample 0 regardless of the evaluator batch size. | |
| gate_input_method = getattr(self.gate, "gate_input", None) | |
| if callable(gate_input_method): | |
| # Batch derangement must see the complete canonical first batch | |
| # before receiver sample 0 and its gate source are selected. | |
| gate_input_batch = gate_input_method(value) | |
| elif self.intervention_mode in STOP_GRADIENT_MODES: | |
| gate_input_batch = value.detach() | |
| elif self.intervention_mode == "baseline": | |
| gate_input_batch = value | |
| else: | |
| raise RuntimeError( | |
| f"{self.module_name} does not expose gate_input for " | |
| f"{self.intervention_mode}" | |
| ) | |
| reference = value[:1] | |
| gate_input = gate_input_batch[:1] | |
| x_flat = reference.detach().float().reshape(-1) | |
| y_flat = gate_input.detach().float().reshape(-1) | |
| if x_flat.shape != y_flat.shape: | |
| raise RuntimeError( | |
| f"{self.module_name} gate input changed tensor shape during coherence audit" | |
| ) | |
| step = max(1, (x_flat.numel() + COHERENCE_MAX_VALUES - 1) // COHERENCE_MAX_VALUES) | |
| x_sample = x_flat[::step][:COHERENCE_MAX_VALUES].cpu().double() | |
| y_sample = y_flat[::step][:COHERENCE_MAX_VALUES].cpu().double() | |
| if not bool(torch.isfinite(x_sample).all() and torch.isfinite(y_sample).all()): | |
| raise FloatingPointError( | |
| f"{self.module_name} produced non-finite intervention coherence values" | |
| ) | |
| x_centered = x_sample - x_sample.mean() | |
| y_centered = y_sample - y_sample.mean() | |
| denominator = torch.linalg.vector_norm(x_centered) * torch.linalg.vector_norm( | |
| y_centered | |
| ) | |
| pearson = ( | |
| float(torch.dot(x_centered, y_centered) / denominator) | |
| if float(denominator) > 0.0 | |
| else None | |
| ) | |
| batch_size = int(value.shape[0]) | |
| batch_shift = None | |
| gate_source_batch_index = 0 | |
| if self.intervention_mode == "batch_derangement": | |
| shift_method = getattr(self.gate, "batch_derangement_shift", None) | |
| if not callable(shift_method): | |
| raise RuntimeError( | |
| f"{self.module_name} does not expose its batch derangement shift" | |
| ) | |
| batch_shift = int(shift_method(batch_size)) | |
| gate_source_batch_index = batch_shift % batch_size | |
| if gate_source_batch_index == 0: | |
| raise RuntimeError( | |
| f"{self.module_name} batch derangement retained sample 0" | |
| ) | |
| return { | |
| "definition": "pearson(pre_gate_x, intervention_gate_input)", | |
| "canonical_val_sample_indices": [0], | |
| "sampling": "strided_flatten_first_canonical_image", | |
| "maximum_values": COHERENCE_MAX_VALUES, | |
| "sampled_values": int(x_sample.numel()), | |
| "pearson": pearson, | |
| "intervention_batch_size": batch_size, | |
| "batch_shift": batch_shift, | |
| "gate_source_batch_index": gate_source_batch_index, | |
| } | |
| def _permutation_identity(self) -> dict[str, Any]: | |
| if self.gate_permutation is None: | |
| if self.intervention_mode in CHANNEL_DERANGEMENT_MODES: | |
| raise RuntimeError( | |
| f"{self.module_name} channel derangement has no permutation" | |
| ) | |
| return { | |
| "sha256": None, | |
| "encoding": None, | |
| "size": None, | |
| "is_bijection": None, | |
| "fixed_points": None, | |
| } | |
| permutation = ( | |
| self.gate_permutation.detach().cpu().to(dtype=torch.int64).reshape(-1) | |
| ) | |
| expected = torch.arange(permutation.numel(), dtype=torch.int64) | |
| is_bijection = bool(torch.equal(torch.sort(permutation).values, expected)) | |
| fixed_points = int((permutation == expected).sum().item()) | |
| encoded = permutation.numpy().astype("<i8", copy=False).tobytes(order="C") | |
| identity = { | |
| "sha256": hashlib.sha256(encoded).hexdigest(), | |
| "encoding": "little_endian_int64_c_order", | |
| "size": int(permutation.numel()), | |
| "is_bijection": is_bijection, | |
| "fixed_points": fixed_points, | |
| } | |
| native = self.native_intervention_metadata | |
| if native is not None and ( | |
| native.get("permutation_sha256") != identity["sha256"] | |
| or native.get("permutation_hash_encoding") != identity["encoding"] | |
| or int(native.get("channels", -1)) != identity["size"] | |
| or native.get("is_bijection") != identity["is_bijection"] | |
| or int(native.get("fixed_points", -1)) != identity["fixed_points"] | |
| ): | |
| raise RuntimeError( | |
| f"{self.module_name} permutation differs from model-native metadata" | |
| ) | |
| return identity | |
| def compute(self) -> dict[str, Any]: | |
| if self.counts is None: | |
| raise RuntimeError(f"no pre-gate observations for {self.module_name}") | |
| total, finite, negative, active, above = ( | |
| int(value) for value in self.counts.detach().cpu().tolist() | |
| ) | |
| if finite != total: | |
| raise FloatingPointError( | |
| f"{self.module_name} produced {total - finite} non-finite pre-gate values" | |
| ) | |
| if negative + active + above != total: | |
| raise RuntimeError(f"gate region counts do not partition {self.module_name}") | |
| actual = ( | |
| int(self.actual_crossing.detach().cpu()) | |
| if self.actual_crossing is not None | |
| else None | |
| ) | |
| return { | |
| "module": self.module_name, | |
| "stage": self.stage, | |
| "block": self.block, | |
| "global_block_index": self.global_block_index, | |
| "gate_type": getattr(self.gate, "name", type(self.gate).__name__), | |
| "element_count": total, | |
| "negative_count": negative, | |
| "active_0_to_6_count": active, | |
| "above_reference_6_count": above, | |
| "negative_fraction": negative / total, | |
| "active_0_to_6_fraction": active / total, | |
| "above_reference_6_fraction": above / total, | |
| "actual_clip_kind": self.clip_kind, | |
| "actual_clip_crossing_count": actual, | |
| "actual_clip_crossing_fraction": actual / total if actual is not None else None, | |
| "gate_intervention": { | |
| "mode": self.intervention_mode, | |
| "seed": self.intervention_seed, | |
| "permutation": self._permutation_identity(), | |
| "batch_derangements": [ | |
| self.batch_derangements[size] | |
| for size in sorted(self.batch_derangements) | |
| ], | |
| "coherence": self.coherence, | |
| }, | |
| } | |
| def attach_gate_region_hooks( | |
| model: nn.Module, | |
| ) -> tuple[list[GateRegionAccumulator], list[torch.utils.hooks.RemovableHandle]]: | |
| accumulators: list[GateRegionAccumulator] = [] | |
| handles: list[torch.utils.hooks.RemovableHandle] = [] | |
| native_metadata_method = getattr(model, "gate_intervention_metadata", None) | |
| native_metadata = ( | |
| native_metadata_method() if callable(native_metadata_method) else None | |
| ) | |
| if native_metadata is not None and not isinstance(native_metadata, list): | |
| raise RuntimeError("model gate_intervention_metadata() must return a list") | |
| pattern = re.compile(r"^stages\.(\d+)\.(\d+)$") | |
| for name, module in model.named_modules(): | |
| if not isinstance(module, GmNetBlock): | |
| continue | |
| match = pattern.match(name) | |
| if match is None: | |
| raise RuntimeError(f"cannot identify GmNet block position: {name}") | |
| global_block_index = len(accumulators) | |
| intervention_mode = str( | |
| getattr( | |
| module, | |
| "gate_intervention", | |
| getattr(module.gate, "gate_intervention", "baseline"), | |
| ) | |
| ) | |
| intervention_seed = int( | |
| getattr( | |
| module, | |
| "gate_intervention_seed", | |
| getattr( | |
| module.gate, | |
| "gate_intervention_seed", | |
| DEFAULT_GATE_INTERVENTION_SEED | |
| + global_block_index * GATE_INTERVENTION_BLOCK_SEED_STRIDE, | |
| ), | |
| ) | |
| ) | |
| expected_seed = int( | |
| getattr(model, "gate_intervention_seed", DEFAULT_GATE_INTERVENTION_SEED) | |
| ) + global_block_index * GATE_INTERVENTION_BLOCK_SEED_STRIDE | |
| if intervention_seed != expected_seed: | |
| raise RuntimeError( | |
| f"{name} intervention seed is {intervention_seed}, expected {expected_seed}" | |
| ) | |
| native_row = ( | |
| native_metadata[global_block_index] | |
| if native_metadata is not None and global_block_index < len(native_metadata) | |
| else None | |
| ) | |
| expected_components = { | |
| "stops_gate_gradient": intervention_mode in STOP_GRADIENT_MODES, | |
| "channel_derangement": ( | |
| intervention_mode in CHANNEL_DERANGEMENT_MODES | |
| ), | |
| "batch_derangement": intervention_mode == "batch_derangement", | |
| "batch_shift_rule": ( | |
| "1 + seed % (local_batch_size - 1)" | |
| if intervention_mode == "batch_derangement" | |
| else None | |
| ), | |
| } | |
| if native_metadata is not None and ( | |
| not isinstance(native_row, dict) | |
| or int(native_row.get("global_block_index", -1)) != global_block_index | |
| or int(native_row.get("stage_index", -1)) != int(match.group(1)) | |
| or int(native_row.get("stage_block_index", -1)) | |
| != int(match.group(2)) - 1 | |
| or native_row.get("mode") != intervention_mode | |
| or int(native_row.get("seed", -1)) != intervention_seed | |
| or any( | |
| native_row.get(key) != expected | |
| for key, expected in expected_components.items() | |
| ) | |
| ): | |
| raise RuntimeError(f"{name} differs from model-native intervention metadata") | |
| gate_permutation = getattr( | |
| module, | |
| "gate_permutation", | |
| getattr(module.gate, "gate_permutation", None), | |
| ) | |
| accumulator = GateRegionAccumulator( | |
| module_name=f"{name}.gate", | |
| stage=int(match.group(1)) + 1, | |
| block=int(match.group(2)), | |
| global_block_index=global_block_index, | |
| gate=module.gate, | |
| intervention_mode=intervention_mode, | |
| intervention_seed=intervention_seed, | |
| gate_permutation=gate_permutation, | |
| native_intervention_metadata=native_row, | |
| ) | |
| def pre_hook( | |
| gate: nn.Module, | |
| inputs: tuple[Tensor, ...], | |
| *, | |
| accumulator: GateRegionAccumulator = accumulator, | |
| ) -> None: | |
| del gate | |
| if len(inputs) != 1: | |
| raise RuntimeError("GmNet gate must receive exactly one tensor") | |
| accumulator.update(inputs[0]) | |
| handles.append(module.gate.register_forward_pre_hook(pre_hook)) | |
| accumulators.append(accumulator) | |
| if not accumulators: | |
| raise RuntimeError("model contains no GmNet blocks") | |
| if native_metadata is not None and len(native_metadata) != len(accumulators): | |
| raise RuntimeError("model-native intervention metadata block count is invalid") | |
| return accumulators, handles | |
| def summarize_gate_intervention( | |
| gate_rows: list[dict[str, Any]], identity: dict[str, Any] | |
| ) -> dict[str, Any]: | |
| block_identities: list[dict[str, Any]] = [] | |
| permutation_blocks = 0 | |
| batch_derangement_blocks = 0 | |
| for index, row in enumerate(gate_rows): | |
| intervention = row["gate_intervention"] | |
| if intervention["mode"] != identity["mode"]: | |
| raise RuntimeError( | |
| f"{row['module']} mode differs from reconstructed model identity" | |
| ) | |
| expected_seed = int(identity["seed"]) + ( | |
| index * GATE_INTERVENTION_BLOCK_SEED_STRIDE | |
| ) | |
| if int(intervention["seed"]) != expected_seed: | |
| raise RuntimeError( | |
| f"{row['module']} seed is {intervention['seed']}, expected {expected_seed}" | |
| ) | |
| permutation = intervention["permutation"] | |
| if identity["mode"] in CHANNEL_DERANGEMENT_MODES: | |
| if ( | |
| permutation["is_bijection"] is not True | |
| or int(permutation["fixed_points"]) != 0 | |
| or int(permutation["size"]) <= 1 | |
| ): | |
| raise RuntimeError( | |
| f"{row['module']} does not contain a valid channel derangement" | |
| ) | |
| permutation_blocks += 1 | |
| elif permutation["sha256"] is not None: | |
| raise RuntimeError( | |
| f"{row['module']} unexpectedly contains a channel permutation" | |
| ) | |
| batch_mappings = intervention.get("batch_derangements") | |
| if not isinstance(batch_mappings, list): | |
| raise RuntimeError( | |
| f"{row['module']} is missing batch derangement metadata" | |
| ) | |
| if identity["mode"] == "batch_derangement": | |
| if not batch_mappings: | |
| raise RuntimeError( | |
| f"{row['module']} does not record a batch derangement" | |
| ) | |
| batch_derangement_blocks += 1 | |
| elif batch_mappings: | |
| raise RuntimeError( | |
| f"{row['module']} unexpectedly records a batch derangement" | |
| ) | |
| block_identity = { | |
| "module": row["module"], | |
| "stage": row["stage"], | |
| "block": row["block"], | |
| "global_block_index": row["global_block_index"], | |
| "seed": intervention["seed"], | |
| "permutation_sha256": permutation["sha256"], | |
| } | |
| if identity["mode"] == "batch_derangement": | |
| block_identity["batch_derangements"] = batch_mappings | |
| block_identities.append(block_identity) | |
| mode = str(identity["mode"]) | |
| return { | |
| "schema_version": 2, | |
| "mode": mode, | |
| "seed": int(identity["seed"]), | |
| "config_explicit": bool(identity["config_explicit"]), | |
| "block_seed_stride": GATE_INTERVENTION_BLOCK_SEED_STRIDE, | |
| "components": { | |
| "stops_gate_gradient": mode in STOP_GRADIENT_MODES, | |
| "channel_derangement": mode in CHANNEL_DERANGEMENT_MODES, | |
| "batch_derangement": mode == "batch_derangement", | |
| }, | |
| "pairing_scope": ( | |
| "single_device_canonical_contiguous_batch" | |
| if mode == "batch_derangement" | |
| else None | |
| ), | |
| "block_count": len(gate_rows), | |
| "permutation_blocks": permutation_blocks, | |
| "batch_derangement_blocks": batch_derangement_blocks, | |
| "permutation_manifest_sha256": ( | |
| stable_sha256(block_identities) | |
| if mode in CHANNEL_DERANGEMENT_MODES | |
| else None | |
| ), | |
| "batch_derangement_manifest_sha256": ( | |
| stable_sha256(block_identities) | |
| if mode == "batch_derangement" | |
| else None | |
| ), | |
| "block_identities": block_identities, | |
| } | |
| def smooth_clip_values(model: nn.Module) -> list[dict[str, Any]]: | |
| rows: list[dict[str, Any]] = [] | |
| for name, module in model.named_modules(): | |
| if not isinstance(module, SmoothClippedSelfGate): | |
| continue | |
| match = re.match(r"^stages\.(\d+)\.(\d+)\.gate$", name) | |
| values = module.clip_value.detach().float().cpu().reshape(-1).numpy() | |
| rows.append( | |
| { | |
| "module": name, | |
| "stage": int(match.group(1)) + 1 if match else None, | |
| "block": int(match.group(2)) if match else None, | |
| "channels": int(values.size), | |
| "trainable": bool(module.trainable), | |
| "minimum": float(values.min()), | |
| "maximum": float(values.max()), | |
| "mean": float(values.mean()), | |
| "std": float(values.std()), | |
| "values": values.tolist(), | |
| } | |
| ) | |
| return rows | |
| def evaluate_loader( | |
| model: nn.Module, | |
| loader: DataLoader, | |
| device: torch.device, | |
| *, | |
| channels_last: bool, | |
| ) -> tuple[dict[str, float], dict[str, np.ndarray]]: | |
| indices: list[np.ndarray] = [] | |
| targets_all: list[np.ndarray] = [] | |
| predictions_all: list[np.ndarray] = [] | |
| confidence_all: list[np.ndarray] = [] | |
| correct_all: list[np.ndarray] = [] | |
| top5_all: list[np.ndarray] = [] | |
| nll_all: list[np.ndarray] = [] | |
| for images, targets, sample_indices in loader: | |
| images = images.to(device, non_blocking=True) | |
| if channels_last: | |
| images = images.contiguous(memory_format=torch.channels_last) | |
| targets_device = targets.to(device, non_blocking=True) | |
| logits = model(images).float() | |
| if logits.ndim != 2 or logits.shape[1] != EXPECTED_CLASSES: | |
| raise RuntimeError(f"expected [batch, 1000] logits, got {tuple(logits.shape)}") | |
| if not bool(torch.isfinite(logits).all()): | |
| raise FloatingPointError("model produced non-finite logits") | |
| probabilities = logits.softmax(dim=1) | |
| confidence, predictions = probabilities.max(dim=1) | |
| top5 = logits.topk(5, dim=1).indices.eq(targets_device[:, None]).any(dim=1) | |
| correct = predictions.eq(targets_device) | |
| nll = F.cross_entropy(logits, targets_device, reduction="none") | |
| indices.append(sample_indices.numpy().astype(np.int64, copy=False)) | |
| targets_all.append(targets.numpy().astype(np.int16, copy=False)) | |
| predictions_all.append(predictions.cpu().numpy().astype(np.int16, copy=False)) | |
| confidence_all.append(confidence.cpu().numpy().astype(np.float32, copy=False)) | |
| correct_all.append(correct.cpu().numpy()) | |
| top5_all.append(top5.cpu().numpy()) | |
| nll_all.append(nll.cpu().numpy().astype(np.float32, copy=False)) | |
| arrays = { | |
| "sample_index": np.concatenate(indices), | |
| "target": np.concatenate(targets_all), | |
| "prediction": np.concatenate(predictions_all), | |
| "confidence": np.concatenate(confidence_all), | |
| "correct": np.concatenate(correct_all), | |
| "top5_correct": np.concatenate(top5_all), | |
| "nll": np.concatenate(nll_all), | |
| } | |
| if not np.array_equal(arrays["sample_index"], np.arange(len(arrays["sample_index"]))): | |
| raise RuntimeError("validation sampler did not preserve canonical sample order") | |
| metrics = classification_metrics( | |
| arrays["correct"], | |
| arrays["top5_correct"], | |
| arrays["nll"], | |
| arrays["confidence"], | |
| ece_bins=ECE_BINS, | |
| ) | |
| return metrics, arrays | |
| def validate_gate_intervention_artifacts( | |
| config: dict[str, Any], result: dict[str, Any], gates: dict[str, Any] | |
| ) -> None: | |
| model_config = config.get("model", {}) | |
| if not isinstance(model_config, dict): | |
| raise RuntimeError("config.json model field must be a mapping") | |
| configured = configured_gate_intervention(model_config) | |
| result_identity = result.get("gate_intervention") | |
| gate_identity = gates.get("gate_intervention") | |
| has_new_artifacts = result_identity is not None or gate_identity is not None | |
| if not configured["config_explicit"] and not has_new_artifacts: | |
| # Compatibility path for completed evaluations produced before E4 was | |
| # encoded in the model/checkpoint contract. | |
| return | |
| if not isinstance(result_identity, dict) or not isinstance(gate_identity, dict): | |
| raise RuntimeError( | |
| "model-native gate intervention is missing from official artifacts" | |
| ) | |
| if result_identity != gate_identity: | |
| raise RuntimeError( | |
| "results.json and gate_diagnostics.json disagree on gate intervention identity" | |
| ) | |
| for key in ("mode", "seed", "config_explicit", "block_seed_stride"): | |
| if result_identity.get(key) != configured[key]: | |
| raise RuntimeError( | |
| f"gate intervention {key} does not match config.json" | |
| ) | |
| block_identities = result_identity.get("block_identities") | |
| blocks = gates.get("blocks") | |
| if not isinstance(block_identities, list) or not isinstance(blocks, list): | |
| raise RuntimeError("gate intervention block identities are missing") | |
| if ( | |
| int(result_identity.get("block_count", -1)) != len(blocks) | |
| or len(block_identities) != len(blocks) | |
| ): | |
| raise RuntimeError("gate intervention block identity count is inconsistent") | |
| reconstructed: list[dict[str, Any]] = [] | |
| permutation_blocks = 0 | |
| batch_derangement_blocks = 0 | |
| mode = str(configured["mode"]) | |
| schema_version = int(result_identity.get("schema_version", 1)) | |
| expected_components = { | |
| "stops_gate_gradient": mode in STOP_GRADIENT_MODES, | |
| "channel_derangement": mode in CHANNEL_DERANGEMENT_MODES, | |
| "batch_derangement": mode == "batch_derangement", | |
| } | |
| if schema_version >= 2 and result_identity.get("components") != expected_components: | |
| raise RuntimeError("gate intervention component identity is invalid") | |
| if mode in {"batch_derangement", "stop_gradient_channel_derangement"}: | |
| if schema_version != 2: | |
| raise RuntimeError("new gate interventions require artifact schema version 2") | |
| eval_batch_size = int(config.get("data", {}).get("eval_batch_size", 0)) | |
| if mode == "batch_derangement" and eval_batch_size < 2: | |
| raise RuntimeError("batch derangement requires config eval_batch_size >= 2") | |
| for index, (identity_row, block_row) in enumerate( | |
| zip(block_identities, blocks, strict=True) | |
| ): | |
| if not isinstance(identity_row, dict) or not isinstance(block_row, dict): | |
| raise RuntimeError("gate intervention block identity must be a mapping") | |
| block_intervention = block_row.get("gate_intervention") | |
| if not isinstance(block_intervention, dict): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} is missing intervention metadata" | |
| ) | |
| expected_seed = int(configured["seed"]) + ( | |
| index * GATE_INTERVENTION_BLOCK_SEED_STRIDE | |
| ) | |
| if ( | |
| int(block_row.get("global_block_index", -1)) != index | |
| or block_intervention.get("mode") != mode | |
| or int(block_intervention.get("seed", -1)) != expected_seed | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has an invalid intervention identity" | |
| ) | |
| permutation = block_intervention.get("permutation") | |
| batch_mappings = block_intervention.get("batch_derangements", []) | |
| coherence = block_intervention.get("coherence") | |
| if ( | |
| not isinstance(permutation, dict) | |
| or not isinstance(batch_mappings, list) | |
| or not isinstance(coherence, dict) | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} is missing intervention metadata" | |
| ) | |
| if ( | |
| coherence.get("canonical_val_sample_indices") != [0] | |
| or int(coherence.get("sampled_values", 0)) <= 0 | |
| or int(coherence.get("maximum_values", -1)) != COHERENCE_MAX_VALUES | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has an invalid coherence sample" | |
| ) | |
| pearson = coherence.get("pearson") | |
| if pearson is not None and ( | |
| not np.isfinite(float(pearson)) or not -1.000_001 <= float(pearson) <= 1.000_001 | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has an invalid coherence value" | |
| ) | |
| if mode == "batch_derangement": | |
| expected_shift = 1 + expected_seed % (eval_batch_size - 1) | |
| if ( | |
| int(coherence.get("intervention_batch_size", -1)) | |
| != eval_batch_size | |
| or int(coherence.get("batch_shift", -1)) != expected_shift | |
| or int(coherence.get("gate_source_batch_index", -1)) | |
| != expected_shift | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has an invalid canonical " | |
| "batch donor" | |
| ) | |
| permutation_hash = permutation.get("sha256") | |
| if mode in CHANNEL_DERANGEMENT_MODES: | |
| if ( | |
| not isinstance(permutation_hash, str) | |
| or re.fullmatch(r"[0-9a-f]{64}", permutation_hash) is None | |
| or permutation.get("encoding") != "little_endian_int64_c_order" | |
| or permutation.get("is_bijection") is not True | |
| or int(permutation.get("fixed_points", -1)) != 0 | |
| or int(permutation.get("size", 0)) <= 1 | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has an invalid channel derangement" | |
| ) | |
| permutation_blocks += 1 | |
| elif any( | |
| permutation.get(key) is not None | |
| for key in ("sha256", "encoding", "size", "is_bijection", "fixed_points") | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} unexpectedly records a permutation" | |
| ) | |
| if mode == "batch_derangement": | |
| expected_batch_records: dict[int, int] = { | |
| eval_batch_size: EXPECTED_SAMPLES // eval_batch_size | |
| } | |
| tail = EXPECTED_SAMPLES % eval_batch_size | |
| if tail: | |
| if tail < 2: | |
| raise RuntimeError( | |
| "official batch derangement would create a singleton tail batch" | |
| ) | |
| expected_batch_records[tail] = 1 | |
| observed_sizes: set[int] = set() | |
| observed_receivers = 0 | |
| for mapping in batch_mappings: | |
| if not isinstance(mapping, dict): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has an invalid batch mapping" | |
| ) | |
| local_batch_size = int(mapping.get("local_batch_size", -1)) | |
| batches = int(mapping.get("batches", -1)) | |
| if ( | |
| local_batch_size not in expected_batch_records | |
| or batches != expected_batch_records[local_batch_size] | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has unexpected batch grouping" | |
| ) | |
| shift = 1 + expected_seed % (local_batch_size - 1) | |
| source_indices = ( | |
| np.arange(local_batch_size, dtype="<i8") + shift | |
| ) % local_batch_size | |
| expected_hash = hashlib.sha256( | |
| source_indices.astype("<i8", copy=False).tobytes(order="C") | |
| ).hexdigest() | |
| if ( | |
| int(mapping.get("shift", -1)) != shift | |
| or mapping.get("source_index_sha256") != expected_hash | |
| or mapping.get("encoding") != "little_endian_int64_c_order" | |
| or mapping.get("is_bijection") is not True | |
| or int(mapping.get("fixed_points", -1)) != 0 | |
| or int(mapping.get("receiver_samples", -1)) | |
| != local_batch_size * batches | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has an invalid batch derangement" | |
| ) | |
| observed_sizes.add(local_batch_size) | |
| observed_receivers += local_batch_size * batches | |
| if ( | |
| observed_sizes != set(expected_batch_records) | |
| or observed_receivers != EXPECTED_SAMPLES | |
| ): | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} has incomplete batch derangement coverage" | |
| ) | |
| batch_derangement_blocks += 1 | |
| elif batch_mappings: | |
| raise RuntimeError( | |
| f"gate diagnostic block {index} unexpectedly records batch mappings" | |
| ) | |
| reconstructed_row = { | |
| "module": block_row.get("module"), | |
| "stage": block_row.get("stage"), | |
| "block": block_row.get("block"), | |
| "global_block_index": index, | |
| "seed": expected_seed, | |
| "permutation_sha256": permutation_hash, | |
| } | |
| if mode == "batch_derangement": | |
| reconstructed_row["batch_derangements"] = batch_mappings | |
| if identity_row != reconstructed_row: | |
| raise RuntimeError( | |
| f"gate intervention block identity {index} does not match diagnostics" | |
| ) | |
| reconstructed.append(reconstructed_row) | |
| if int(result_identity.get("permutation_blocks", -1)) != permutation_blocks: | |
| raise RuntimeError("gate intervention permutation block count is inconsistent") | |
| if schema_version >= 2 and int( | |
| result_identity.get("batch_derangement_blocks", -1) | |
| ) != batch_derangement_blocks: | |
| raise RuntimeError("gate intervention batch block count is inconsistent") | |
| expected_manifest = ( | |
| stable_sha256(reconstructed) if mode in CHANNEL_DERANGEMENT_MODES else None | |
| ) | |
| if result_identity.get("permutation_manifest_sha256") != expected_manifest: | |
| raise RuntimeError("gate intervention permutation manifest hash is invalid") | |
| if schema_version >= 2: | |
| expected_batch_manifest = ( | |
| stable_sha256(reconstructed) if mode == "batch_derangement" else None | |
| ) | |
| if ( | |
| result_identity.get("batch_derangement_manifest_sha256") | |
| != expected_batch_manifest | |
| ): | |
| raise RuntimeError("gate intervention batch manifest hash is invalid") | |
| def validate_official_eval( | |
| output_dir: Path, | |
| *, | |
| full: bool = True, | |
| checkpoint_path: Path | None = None, | |
| require_check_certificate: bool = False, | |
| ) -> dict[str, Any]: | |
| output_dir = output_dir.expanduser().resolve() | |
| missing = [name for name in REQUIRED_FILES if not (output_dir / name).is_file()] | |
| if missing: | |
| raise RuntimeError(f"incomplete official evaluation, missing: {missing}") | |
| artifacts = json.loads((output_dir / "artifacts.json").read_text(encoding="utf-8")) | |
| for filename, expected_hash in artifacts["sha256"].items(): | |
| actual_hash = file_sha256(output_dir / filename) | |
| if actual_hash != expected_hash: | |
| raise RuntimeError( | |
| f"official evaluation artifact changed: {filename} " | |
| f"expected={expected_hash}, actual={actual_hash}" | |
| ) | |
| result = json.loads((output_dir / "results.json").read_text(encoding="utf-8")) | |
| if result.get("protocol_version") != PROTOCOL_VERSION: | |
| raise RuntimeError("unexpected official evaluation protocol version") | |
| if result.get("status") != "complete" or result.get("partial_evaluation") is not False: | |
| raise RuntimeError("official evaluation is not marked complete") | |
| if int(result.get("ece_bins", -1)) != ECE_BINS: | |
| raise RuntimeError("official evaluation did not use 15-bin ECE") | |
| expected_epoch = int(result["training_epochs"]) - 1 | |
| if int(result["checkpoint_epoch"]) != expected_epoch: | |
| raise RuntimeError("official evaluation is not from the fixed last epoch") | |
| completion = result.get("training_completion") | |
| if not isinstance(completion, dict): | |
| raise RuntimeError("official evaluation is missing training completion evidence") | |
| if completion.get("epoch_complete") is not True: | |
| raise RuntimeError("official evaluation used an incomplete final epoch") | |
| if completion.get("training_complete") is not True: | |
| raise RuntimeError("official evaluation used incomplete training") | |
| expected_steps = int(completion.get("expected_steps_per_epoch", -1)) | |
| if expected_steps <= 0 or int(completion.get("steps_in_epoch", -1)) != expected_steps: | |
| raise RuntimeError("official evaluation has inconsistent final-epoch steps") | |
| expected_global_step = int(result["training_epochs"]) * expected_steps | |
| if int(completion.get("expected_global_step", -1)) != expected_global_step: | |
| raise RuntimeError("official evaluation has an invalid expected global step") | |
| if int(completion.get("global_step", -1)) != expected_global_step: | |
| raise RuntimeError("official evaluation checkpoint has incomplete global steps") | |
| topology = result.get("topology") | |
| if not isinstance(topology, dict) or int(topology.get("parameter_count", 0)) <= 0: | |
| raise RuntimeError("official evaluation is missing model topology evidence") | |
| schema_hash = topology.get("model_state_schema_sha256") | |
| if not isinstance(schema_hash, str) or re.fullmatch(r"[0-9a-f]{64}", schema_hash) is None: | |
| raise RuntimeError("official evaluation has an invalid model state schema hash") | |
| config = json.loads((output_dir / "config.json").read_text(encoding="utf-8")) | |
| if stable_sha256(config) != result["hashes"]["config_sha256"]: | |
| raise RuntimeError("config.json does not match the recorded configuration hash") | |
| gates = json.loads( | |
| (output_dir / "gate_diagnostics.json").read_text(encoding="utf-8") | |
| ) | |
| validate_gate_intervention_artifacts(config, result, gates) | |
| data_manifest = json.loads( | |
| (output_dir / "data_manifest.json").read_text(encoding="utf-8") | |
| ) | |
| recorded_data_hash = data_manifest.pop("evaluation_manifest_sha256", None) | |
| if recorded_data_hash != stable_sha256(data_manifest): | |
| raise RuntimeError("data_manifest.json has an invalid evaluation manifest hash") | |
| if recorded_data_hash != result["hashes"]["evaluation_data_manifest_sha256"]: | |
| raise RuntimeError("data_manifest.json does not match results.json") | |
| if data_manifest.get("class_to_idx_sha256") != result["hashes"]["class_to_idx_sha256"]: | |
| raise RuntimeError("class mapping hash does not match results.json") | |
| if data_manifest.get("sample_index_sha256") != result["hashes"]["val_sample_index_sha256"]: | |
| raise RuntimeError("validation index hash does not match results.json") | |
| if data_manifest.get("sampled_content_sha256") != result["hashes"].get( | |
| "val_sampled_content_sha256" | |
| ): | |
| raise RuntimeError("validation sampled content hash does not match results.json") | |
| if checkpoint_path is not None: | |
| checkpoint_path = checkpoint_path.expanduser().resolve() | |
| if checkpoint_path.name != "checkpoint_last.pt" or not checkpoint_path.is_file(): | |
| raise RuntimeError("completion check requires the evaluated checkpoint_last.pt") | |
| current_checkpoint_hash = file_sha256(checkpoint_path) | |
| if current_checkpoint_hash != result["hashes"]["checkpoint_sha256"]: | |
| raise RuntimeError("official_eval belongs to a different checkpoint_last.pt") | |
| if full: | |
| if int(result["metrics"]["samples"]) != EXPECTED_SAMPLES: | |
| raise RuntimeError("official evaluation does not contain 50000 samples") | |
| with np.load(output_dir / "per_sample.npz", allow_pickle=False) as per_sample: | |
| required_arrays = { | |
| "sample_index", | |
| "target", | |
| "prediction", | |
| "confidence", | |
| "correct", | |
| "top5_correct", | |
| "nll", | |
| } | |
| if set(per_sample.files) != required_arrays: | |
| raise RuntimeError("per_sample.npz has an unexpected schema") | |
| if any(per_sample[name].shape != (EXPECTED_SAMPLES,) for name in required_arrays): | |
| raise RuntimeError("per_sample.npz arrays must all contain 50000 samples") | |
| if not np.array_equal(per_sample["sample_index"], np.arange(EXPECTED_SAMPLES)): | |
| raise RuntimeError("per_sample.npz sample indices are not canonical") | |
| for name in ("confidence", "nll"): | |
| if not np.isfinite(per_sample[name]).all(): | |
| raise RuntimeError(f"per_sample.npz contains non-finite {name}") | |
| recomputed = classification_metrics( | |
| per_sample["correct"], | |
| per_sample["top5_correct"], | |
| per_sample["nll"], | |
| per_sample["confidence"], | |
| ece_bins=ECE_BINS, | |
| ) | |
| for name in ("top1", "top5", "nll", "ece"): | |
| if not np.isclose(recomputed[name], result["metrics"][name], rtol=1e-7, atol=1e-7): | |
| raise RuntimeError(f"recorded {name} does not match per_sample.npz") | |
| blocks = gates.get("blocks", []) | |
| if len(blocks) != int(result["gate_diagnostics"]["blocks"]): | |
| raise RuntimeError("gate diagnostic block count does not match results.json") | |
| if len(gates.get("smooth_clip_values", [])) != int( | |
| result["gate_diagnostics"]["smooth_clip_blocks"] | |
| ): | |
| raise RuntimeError("smooth clip block count does not match results.json") | |
| for block in blocks: | |
| fractions = ( | |
| float(block["negative_fraction"]), | |
| float(block["active_0_to_6_fraction"]), | |
| float(block["above_reference_6_fraction"]), | |
| ) | |
| if int(block["element_count"]) <= 0 or not np.isclose(sum(fractions), 1.0): | |
| raise RuntimeError(f"invalid gate region partition: {block.get('module')}") | |
| complete = json.loads((output_dir / "COMPLETE").read_text(encoding="utf-8")) | |
| if complete.get("artifacts_sha256") != file_sha256(output_dir / "artifacts.json"): | |
| raise RuntimeError("COMPLETE marker does not match artifacts.json") | |
| if complete.get("checkpoint_sha256") != result["hashes"]["checkpoint_sha256"]: | |
| raise RuntimeError("COMPLETE marker does not match the evaluated checkpoint") | |
| certificate_path = output_dir / "checks.json" | |
| if require_check_certificate and not certificate_path.is_file(): | |
| raise RuntimeError("official evaluation is missing checks.json certification") | |
| if certificate_path.is_file(): | |
| certificate = json.loads(certificate_path.read_text(encoding="utf-8")) | |
| if ( | |
| certificate.get("schema_version") != 1 | |
| or certificate.get("status") != "passed" | |
| or certificate.get("protocol_version") != PROTOCOL_VERSION | |
| or certificate.get("checkpoint_sha256") | |
| != result["hashes"]["checkpoint_sha256"] | |
| or certificate.get("artifacts_sha256") | |
| != file_sha256(output_dir / "artifacts.json") | |
| ): | |
| raise RuntimeError("official evaluation has an invalid checks.json certificate") | |
| return result | |
| def write_check_certificate(output_dir: Path, result: dict[str, Any]) -> None: | |
| payload = { | |
| "schema_version": 1, | |
| "status": "passed", | |
| "protocol_version": PROTOCOL_VERSION, | |
| "validated_at_utc": datetime.now(UTC).isoformat(), | |
| "checkpoint_sha256": result["hashes"]["checkpoint_sha256"], | |
| "artifacts_sha256": file_sha256(output_dir / "artifacts.json"), | |
| "validation_scope": "full_artifacts_per_sample_topology_completion_and_checkpoint", | |
| } | |
| temporary = output_dir / ".checks.json.tmp" | |
| write_json(temporary, payload) | |
| os.replace(temporary, output_dir / "checks.json") | |
| def publish_directory(temporary_dir: Path, output_dir: Path, *, overwrite: bool) -> None: | |
| if output_dir.exists() and not overwrite: | |
| raise FileExistsError(f"official evaluation appeared concurrently: {output_dir}") | |
| backup: Path | None = None | |
| if output_dir.exists(): | |
| backup = output_dir.with_name(f".{output_dir.name}.backup.{os.getpid()}") | |
| if backup.exists(): | |
| shutil.rmtree(backup) | |
| os.replace(output_dir, backup) | |
| try: | |
| os.replace(temporary_dir, output_dir) | |
| except BaseException: | |
| if backup is not None and backup.exists() and not output_dir.exists(): | |
| os.replace(backup, output_dir) | |
| raise | |
| if backup is not None: | |
| shutil.rmtree(backup) | |
| def main() -> None: | |
| args = parse_args() | |
| checkpoint_argument = args.checkpoint.expanduser() | |
| if checkpoint_argument.name != "checkpoint_last.pt": | |
| raise ValueError( | |
| "official ImageNet evaluation only accepts a file named checkpoint_last.pt" | |
| ) | |
| checkpoint_path = checkpoint_argument.resolve() | |
| output_dir = (args.output_dir or checkpoint_path.parent / "official_eval").expanduser().resolve() | |
| if output_dir.name != "official_eval": | |
| raise ValueError("official ImageNet results must be written to a directory named official_eval") | |
| if args.check_only: | |
| result = validate_official_eval(output_dir, checkpoint_path=checkpoint_path) | |
| write_check_certificate(output_dir, result) | |
| validate_official_eval( | |
| output_dir, | |
| checkpoint_path=checkpoint_path, | |
| require_check_certificate=True, | |
| ) | |
| print(json.dumps(result["metrics"], sort_keys=True), flush=True) | |
| return | |
| if args.data_root is None: | |
| raise ValueError("--data-root is required unless --check-only is used") | |
| if args.batch_size is not None and args.batch_size <= 0: | |
| raise ValueError("--batch-size must be positive") | |
| if args.workers is not None and args.workers < 0: | |
| raise ValueError("--workers cannot be negative") | |
| checkpoint_hash = file_sha256(checkpoint_path) | |
| if output_dir.exists() and not args.overwrite: | |
| result = validate_official_eval(output_dir, checkpoint_path=checkpoint_path) | |
| print(f"existing official evaluation is complete: {output_dir}", flush=True) | |
| print(json.dumps(result["metrics"], sort_keys=True), flush=True) | |
| return | |
| checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) | |
| if not isinstance(checkpoint, dict): | |
| raise TypeError("checkpoint must contain a mapping") | |
| identity = validate_checkpoint_identity(checkpoint_path, checkpoint) | |
| config = checkpoint["config"] | |
| data_config = config["data"] | |
| val_root = args.data_root.expanduser().resolve() / str(data_config.get("val_split", "val")) | |
| if not val_root.is_dir(): | |
| raise FileNotFoundError(f"missing ImageNet validation split: {val_root}") | |
| dataset = IndexedImageFolder(val_root, imagenet_val_transform(data_config)) | |
| data_manifest = imagefolder_data_manifest(dataset, val_root) | |
| validate_data_against_checkpoint(data_manifest, checkpoint["data_manifest"]) | |
| device = torch.device(args.device) | |
| if device.type == "cuda" and not torch.cuda.is_available(): | |
| raise RuntimeError("CUDA was requested but is unavailable") | |
| model = build_model(checkpoint, device) | |
| topology = validate_model_topology(model, identity) | |
| intervention_identity = validate_model_gate_intervention( | |
| model, identity["gate_intervention"] | |
| ) | |
| clips = smooth_clip_values(model) | |
| accumulators, handles = attach_gate_region_hooks(model) | |
| configured_eval_batch_size = int(data_config.get("eval_batch_size", 256)) | |
| batch_size = resolve_official_batch_size( | |
| args.batch_size, | |
| configured_eval_batch_size, | |
| str(intervention_identity["mode"]), | |
| ) | |
| workers = int(args.workers if args.workers is not None else data_config.get("workers", 8)) | |
| loader_options: dict[str, Any] = { | |
| "batch_size": batch_size, | |
| "shuffle": False, | |
| "num_workers": workers, | |
| "pin_memory": device.type == "cuda" and bool(data_config.get("pin_memory", True)), | |
| "persistent_workers": workers > 0 and bool(data_config.get("persistent_workers", True)), | |
| } | |
| if workers > 0: | |
| loader_options["prefetch_factor"] = int(data_config.get("prefetch_factor", 2)) | |
| loader = DataLoader(dataset, **loader_options) | |
| started = datetime.now(UTC) | |
| try: | |
| metrics, per_sample = evaluate_loader( | |
| model, | |
| loader, | |
| device, | |
| channels_last=bool(config["train"].get("channels_last", False)), | |
| ) | |
| finally: | |
| for handle in handles: | |
| handle.remove() | |
| finished = datetime.now(UTC) | |
| if int(metrics["samples"]) != EXPECTED_SAMPLES: | |
| raise RuntimeError(f"formal evaluation must contain 50000 samples, got {metrics['samples']}") | |
| gate_rows = [accumulator.compute() for accumulator in accumulators] | |
| expected_blocks = sum(int(value) for value in model.depths) | |
| if len(gate_rows) != expected_blocks: | |
| raise RuntimeError(f"expected {expected_blocks} block diagnostics, got {len(gate_rows)}") | |
| intervention_summary = summarize_gate_intervention( | |
| gate_rows, intervention_identity | |
| ) | |
| final_checkpoint_hash = file_sha256(checkpoint_path) | |
| if final_checkpoint_hash != checkpoint_hash: | |
| raise RuntimeError("checkpoint changed during evaluation; results were discarded") | |
| final_data_manifest = imagefolder_data_manifest(dataset, val_root) | |
| if final_data_manifest != data_manifest: | |
| raise RuntimeError("validation index changed during evaluation; results were discarded") | |
| output_dir.parent.mkdir(parents=True, exist_ok=True) | |
| temporary_dir = Path( | |
| tempfile.mkdtemp(prefix=f".{output_dir.name}.", dir=output_dir.parent) | |
| ) | |
| try: | |
| write_json(temporary_dir / "config.json", config) | |
| write_json(temporary_dir / "data_manifest.json", data_manifest) | |
| gate_payload = { | |
| "schema_version": 2, | |
| "reference_regions": ["x<0", "0<=x<6", "x>=6"], | |
| "actual_crossing_definition": ( | |
| "x>=6 for ReLU6 gates; x>=configured clip for learned/fixed smooth gates; " | |
| "null when no clipping operator applies" | |
| ), | |
| "blocks": gate_rows, | |
| "smooth_clip_values": clips, | |
| "gate_intervention": intervention_summary, | |
| } | |
| write_json(temporary_dir / "gate_diagnostics.json", gate_payload) | |
| np.savez_compressed(temporary_dir / "per_sample.npz", **per_sample) | |
| result = { | |
| "protocol_version": PROTOCOL_VERSION, | |
| "status": "complete", | |
| "partial_evaluation": False, | |
| "run_name": str(checkpoint["run_name"]), | |
| "seed": int(checkpoint["seed"]), | |
| "gate_type": config["model"]["gate_type"], | |
| "gate_intervention": intervention_summary, | |
| "checkpoint": str(checkpoint_path), | |
| "checkpoint_epoch": identity["epoch"], | |
| "training_epochs": identity["epochs"], | |
| "training_completion": { | |
| "epoch_complete": identity["epoch_complete"], | |
| "training_complete": identity["training_complete"], | |
| "steps_in_epoch": identity["steps_in_epoch"], | |
| "expected_steps_per_epoch": identity["expected_steps_per_epoch"], | |
| "global_step": identity["global_step"], | |
| "expected_global_step": identity["expected_global_step"], | |
| "world_size": identity["world_size"], | |
| }, | |
| "topology": topology, | |
| "metrics": metrics, | |
| "ece_bins": ECE_BINS, | |
| "hashes": { | |
| "checkpoint_sha256": checkpoint_hash, | |
| "config_sha256": identity["config_sha256"], | |
| "checkpoint_data_manifest_sha256": identity["data_manifest_sha256"], | |
| "evaluation_data_manifest_sha256": data_manifest[ | |
| "evaluation_manifest_sha256" | |
| ], | |
| "class_to_idx_sha256": data_manifest["class_to_idx_sha256"], | |
| "val_sample_index_sha256": data_manifest["sample_index_sha256"], | |
| "val_sampled_content_sha256": data_manifest[ | |
| "sampled_content_sha256" | |
| ], | |
| }, | |
| "gate_diagnostics": { | |
| "blocks": len(gate_rows), | |
| "smooth_clip_blocks": len(clips), | |
| "file": "gate_diagnostics.json", | |
| }, | |
| "metadata": { | |
| "started_at_utc": started.isoformat(), | |
| "finished_at_utc": finished.isoformat(), | |
| "duration_seconds": (finished - started).total_seconds(), | |
| "device": str(device), | |
| "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, | |
| "inference_precision": "float32", | |
| "batch_size": batch_size, | |
| "workers": workers, | |
| "torch": torch.__version__, | |
| "torchvision": __import__("torchvision").__version__, | |
| "python": platform.python_version(), | |
| }, | |
| } | |
| write_json(temporary_dir / "results.json", result) | |
| artifact_names = ( | |
| "results.json", | |
| "per_sample.npz", | |
| "gate_diagnostics.json", | |
| "config.json", | |
| "data_manifest.json", | |
| ) | |
| artifact_payload = { | |
| "schema_version": 1, | |
| "sha256": { | |
| filename: file_sha256(temporary_dir / filename) for filename in artifact_names | |
| }, | |
| } | |
| write_json(temporary_dir / "artifacts.json", artifact_payload) | |
| write_json( | |
| temporary_dir / "COMPLETE", | |
| { | |
| "protocol_version": PROTOCOL_VERSION, | |
| "checkpoint_sha256": checkpoint_hash, | |
| "artifacts_sha256": file_sha256(temporary_dir / "artifacts.json"), | |
| }, | |
| ) | |
| validate_official_eval(temporary_dir, checkpoint_path=checkpoint_path) | |
| publish_directory(temporary_dir, output_dir, overwrite=args.overwrite) | |
| except BaseException: | |
| if temporary_dir.exists(): | |
| shutil.rmtree(temporary_dir) | |
| raise | |
| print(json.dumps(metrics, sort_keys=True), flush=True) | |
| print(output_dir, flush=True) | |
| if __name__ == "__main__": | |
| main() | |