Download gmnet/code/journal_exp/scripts/evaluate_e3_cifar100.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/evaluate_e3_cifar100.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/code/journal_exp/scripts/evaluate_e3_cifar100.py
-
curl -L -o evaluate_e3_cifar100.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/evaluate_e3_cifar100.py
15.4 kB
| #!/usr/bin/env python3 | |
| """Evaluate one E3 CIFAR-100 checkpoint on clean and fixed corruptions.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import os | |
| import platform | |
| import re | |
| import sys | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| from torch.nn import functional as F | |
| from torch.utils.data import DataLoader, Dataset, Subset | |
| from torchvision import datasets | |
| from torchvision.transforms import functional as TF | |
| 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 import CORRUPTION_SPECS, apply_corruption, classification_metrics | |
| from gmnet.models import SmoothClippedSelfGate, create_gmnet | |
| PROTOCOL_VERSION = "e3-cifar100-corruptions-v1" | |
| DEFAULT_CONDITIONS = tuple(CORRUPTION_SPECS) | |
| PER_SAMPLE_COLUMNS = ( | |
| "run_name", | |
| "gate", | |
| "seed", | |
| "condition", | |
| "sample_index", | |
| "target", | |
| "prediction", | |
| "confidence", | |
| "correct", | |
| "top5_correct", | |
| "nll", | |
| ) | |
| class CorruptedCIFAR100(Dataset): | |
| def __init__( | |
| self, | |
| root: str | Path, | |
| condition: str, | |
| mean: list[float], | |
| std: list[float], | |
| ) -> None: | |
| self.dataset = datasets.CIFAR100(root, train=False, download=False) | |
| self.condition = condition | |
| self.mean = mean | |
| self.std = std | |
| def __len__(self) -> int: | |
| return len(self.dataset) | |
| def __getitem__(self, index: int) -> tuple[torch.Tensor, int, int]: | |
| image, target = self.dataset[index] | |
| tensor = TF.to_tensor(image) | |
| tensor = apply_corruption(tensor, self.condition, index) | |
| tensor = TF.normalize(tensor, self.mean, self.std) | |
| return tensor, int(target), index | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--checkpoint", required=True) | |
| parser.add_argument("--data-root", default="/tmp/gmnet_data/cifar-100") | |
| parser.add_argument("--output-dir", default=None) | |
| parser.add_argument("--device", default="auto") | |
| parser.add_argument("--batch-size", type=int, default=512) | |
| parser.add_argument("--workers", type=int, default=4) | |
| parser.add_argument("--ece-bins", type=int, default=15) | |
| parser.add_argument("--max-samples", type=int, default=None) | |
| parser.add_argument("--conditions", nargs="+", choices=DEFAULT_CONDITIONS, default=None) | |
| parser.add_argument("--allow-incomplete", action="store_true") | |
| parser.add_argument("--overwrite", action="store_true") | |
| return parser.parse_args() | |
| def file_sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def assert_training_complete(checkpoint_path: Path, checkpoint: dict[str, Any]) -> None: | |
| expected_epochs = int(checkpoint["config"]["train"]["epochs"]) | |
| last_path = checkpoint_path.with_name("checkpoint_last.pt") | |
| if not last_path.is_file(): | |
| raise RuntimeError(f"missing completion checkpoint: {last_path}") | |
| last = torch.load(last_path, map_location="cpu", weights_only=False) | |
| completed_epoch = int(last.get("epoch", -1)) | |
| if completed_epoch < expected_epochs - 1: | |
| raise RuntimeError( | |
| f"training is incomplete: checkpoint_last epoch={completed_epoch}, " | |
| f"expected at least {expected_epochs - 1}; use --allow-incomplete only for ETA tests" | |
| ) | |
| def build_model(checkpoint: dict[str, Any], device: torch.device) -> torch.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}") | |
| return model.to(device).eval() | |
| def smooth_clip_diagnostics( | |
| model: torch.nn.Module, checkpoint: dict[str, Any] | |
| ) -> dict[str, Any] | None: | |
| """Extract the effective learned clip value from every smooth-gate block.""" | |
| initial = float(checkpoint["config"]["model"].get("smooth_clip_init", 6.0)) | |
| blocks: list[dict[str, Any]] = [] | |
| for name, module in model.named_modules(): | |
| if not isinstance(module, SmoothClippedSelfGate): | |
| continue | |
| values = module.clip_value.detach().float().cpu().numpy().reshape(-1) | |
| match = re.match(r"stages\.(\d+)\.(\d+)\.gate$", name) | |
| stage = int(match.group(1)) if match else -1 | |
| block = int(match.group(2)) if match else -1 | |
| blocks.append( | |
| { | |
| "module": name, | |
| "stage": stage, | |
| "block": block, | |
| "mean": float(values.mean()), | |
| "min": float(values.min()), | |
| "max": float(values.max()), | |
| "channels": int(values.size), | |
| "min_clip_boundary": float(module.min_clip), | |
| } | |
| ) | |
| if not blocks: | |
| return None | |
| stages: list[dict[str, Any]] = [] | |
| for stage in sorted({int(item["stage"]) for item in blocks}): | |
| values = np.asarray( | |
| [item["mean"] for item in blocks if item["stage"] == stage], dtype=np.float64 | |
| ) | |
| stages.append( | |
| { | |
| "stage": stage, | |
| "mean": float(values.mean()), | |
| "min": float(values.min()), | |
| "max": float(values.max()), | |
| "blocks": int(len(values)), | |
| } | |
| ) | |
| strict_boundary_threshold = min(item["min_clip_boundary"] for item in blocks) + 0.05 | |
| severe_collapse_threshold = 0.1 * initial | |
| minimum = min(item["min"] for item in blocks) | |
| return { | |
| "initial_clip": initial, | |
| "blocks": blocks, | |
| "stages": stages, | |
| "global_mean": float(np.mean([item["mean"] for item in blocks])), | |
| "global_min": float(minimum), | |
| "global_max": float(max(item["max"] for item in blocks)), | |
| "strict_boundary_threshold": strict_boundary_threshold, | |
| "severe_collapse_threshold": severe_collapse_threshold, | |
| "near_min_boundary": bool(minimum <= strict_boundary_threshold), | |
| "below_10pct_initial": bool(minimum <= severe_collapse_threshold), | |
| "phase2_boundary_check_pass": bool(minimum > severe_collapse_threshold), | |
| } | |
| def evaluate_condition( | |
| model: torch.nn.Module, | |
| loader: DataLoader, | |
| device: torch.device, | |
| *, | |
| run_name: str, | |
| gate: str, | |
| seed: int, | |
| condition: str, | |
| writer: csv.DictWriter, | |
| ece_bins: int, | |
| ) -> dict[str, float]: | |
| all_correct: list[np.ndarray] = [] | |
| all_top5: list[np.ndarray] = [] | |
| all_nll: list[np.ndarray] = [] | |
| all_confidence: list[np.ndarray] = [] | |
| for images, targets, indices in loader: | |
| images = images.to(device, non_blocking=True) | |
| targets_device = targets.to(device, non_blocking=True) | |
| logits = model(images) | |
| probabilities = logits.float().softmax(dim=1) | |
| confidence, predictions = probabilities.max(dim=1) | |
| top5_predictions = logits.topk(5, dim=1).indices | |
| correct = predictions.eq(targets_device) | |
| top5 = top5_predictions.eq(targets_device[:, None]).any(dim=1) | |
| nll = F.cross_entropy(logits.float(), targets_device, reduction="none") | |
| targets_array = targets.numpy() | |
| indices_array = indices.numpy() | |
| predictions_array = predictions.cpu().numpy() | |
| confidence_array = confidence.cpu().numpy() | |
| correct_array = correct.cpu().numpy() | |
| top5_array = top5.cpu().numpy() | |
| nll_array = nll.cpu().numpy() | |
| all_correct.append(correct_array) | |
| all_top5.append(top5_array) | |
| all_nll.append(nll_array) | |
| all_confidence.append(confidence_array) | |
| writer.writerows( | |
| { | |
| "run_name": run_name, | |
| "gate": gate, | |
| "seed": seed, | |
| "condition": condition, | |
| "sample_index": int(sample_index), | |
| "target": int(target), | |
| "prediction": int(prediction), | |
| "confidence": f"{float(conf):.9g}", | |
| "correct": int(is_correct), | |
| "top5_correct": int(is_top5), | |
| "nll": f"{float(sample_nll):.9g}", | |
| } | |
| for sample_index, target, prediction, conf, is_correct, is_top5, sample_nll in zip( | |
| indices_array, | |
| targets_array, | |
| predictions_array, | |
| confidence_array, | |
| correct_array, | |
| top5_array, | |
| nll_array, | |
| strict=True, | |
| ) | |
| ) | |
| return classification_metrics( | |
| np.concatenate(all_correct), | |
| np.concatenate(all_top5), | |
| np.concatenate(all_nll), | |
| np.concatenate(all_confidence), | |
| ece_bins=ece_bins, | |
| ) | |
| def main() -> None: | |
| args = parse_args() | |
| checkpoint_path = Path(args.checkpoint).expanduser().resolve() | |
| checkpoint_hash = file_sha256(checkpoint_path) | |
| checkpoint = torch.load(checkpoint_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 training checkpoint: {checkpoint_path}") | |
| if not args.allow_incomplete: | |
| assert_training_complete(checkpoint_path, checkpoint) | |
| run_name = str(checkpoint["run_name"]) | |
| seed = int(checkpoint["seed"]) | |
| gate = str(checkpoint["config"]["model"]["gate_type"]) | |
| output_dir = Path(args.output_dir or checkpoint_path.parent / "evaluation").resolve() | |
| if (output_dir / "results.json").exists() and not args.overwrite: | |
| raise FileExistsError(f"evaluation already exists: {output_dir}; pass --overwrite") | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| temporary_csv = output_dir / ".per_sample_correctness.csv.tmp" | |
| result_csv = output_dir / "per_sample_correctness.csv" | |
| if args.device == "auto": | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| else: | |
| device = torch.device(args.device) | |
| model = build_model(checkpoint, device) | |
| clip_diagnostics = smooth_clip_diagnostics(model, checkpoint) | |
| data_config = checkpoint["config"]["data"] | |
| conditions = tuple(args.conditions or DEFAULT_CONDITIONS) | |
| if "clean" not in conditions: | |
| raise ValueError("clean must be included so corruption retention is identifiable") | |
| condition_metrics: dict[str, dict[str, float]] = {} | |
| started = datetime.now(timezone.utc) | |
| with temporary_csv.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=PER_SAMPLE_COLUMNS) | |
| writer.writeheader() | |
| for condition in conditions: | |
| dataset: Dataset = CorruptedCIFAR100( | |
| args.data_root, | |
| condition, | |
| list(data_config["mean"]), | |
| list(data_config["std"]), | |
| ) | |
| if len(dataset) != 10_000: | |
| raise RuntimeError(f"expected 10000 CIFAR-100 test images, got {len(dataset)}") | |
| if args.max_samples is not None: | |
| dataset = Subset(dataset, range(min(args.max_samples, len(dataset)))) | |
| loader = DataLoader( | |
| dataset, | |
| batch_size=args.batch_size, | |
| shuffle=False, | |
| num_workers=args.workers, | |
| pin_memory=device.type == "cuda", | |
| persistent_workers=args.workers > 0, | |
| ) | |
| metrics = evaluate_condition( | |
| model, | |
| loader, | |
| device, | |
| run_name=run_name, | |
| gate=gate, | |
| seed=seed, | |
| condition=condition, | |
| writer=writer, | |
| ece_bins=args.ece_bins, | |
| ) | |
| condition_metrics[condition] = metrics | |
| print(condition, json.dumps(metrics, sort_keys=True), flush=True) | |
| os.replace(temporary_csv, result_csv) | |
| clean_top1 = condition_metrics["clean"]["top1"] | |
| corruption_names = [name for name in conditions if name != "clean"] | |
| mean_corruption_top1 = ( | |
| float(np.mean([condition_metrics[name]["top1"] for name in corruption_names])) | |
| if corruption_names | |
| else None | |
| ) | |
| overall = { | |
| "clean_top1": clean_top1, | |
| "clean_top5": condition_metrics["clean"]["top5"], | |
| "clean_nll": condition_metrics["clean"]["nll"], | |
| "clean_ece": condition_metrics["clean"]["ece"], | |
| "mean_corruption_top1": mean_corruption_top1, | |
| "mean_corruption_nll": float( | |
| np.mean([condition_metrics[name]["nll"] for name in corruption_names]) | |
| ) if corruption_names else None, | |
| "mean_corruption_ece": float( | |
| np.mean([condition_metrics[name]["ece"] for name in corruption_names]) | |
| ) if corruption_names else None, | |
| "retention": 100.0 * mean_corruption_top1 / max(clean_top1, 1e-12) | |
| if mean_corruption_top1 is not None | |
| else None, | |
| } | |
| finished = datetime.now(timezone.utc) | |
| final_hash = file_sha256(checkpoint_path) | |
| if final_hash != checkpoint_hash: | |
| raise RuntimeError("checkpoint changed during evaluation; discard results and rerun") | |
| payload = { | |
| "protocol_version": PROTOCOL_VERSION, | |
| "run_name": run_name, | |
| "gate": gate, | |
| "seed": seed, | |
| "checkpoint": str(checkpoint_path), | |
| "checkpoint_sha256": checkpoint_hash, | |
| "checkpoint_epoch": int(checkpoint["epoch"]), | |
| "checkpoint_best_top1": float(checkpoint["best_top1"]), | |
| "complete_training_required": not args.allow_incomplete, | |
| "partial_evaluation": args.max_samples is not None, | |
| "conditions": condition_metrics, | |
| "overall": overall, | |
| "smooth_clip_diagnostics": clip_diagnostics, | |
| "corruption_specs": {name: CORRUPTION_SPECS[name] for name in conditions}, | |
| "metadata": { | |
| "started_at_utc": started.isoformat(), | |
| "finished_at_utc": finished.isoformat(), | |
| "duration_seconds": (finished - started).total_seconds(), | |
| "device": str(device), | |
| "batch_size": args.batch_size, | |
| "workers": args.workers, | |
| "ece_bins": args.ece_bins, | |
| "torch": torch.__version__, | |
| "python": platform.python_version(), | |
| }, | |
| } | |
| temporary_json = output_dir / ".results.json.tmp" | |
| temporary_json.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") | |
| os.replace(temporary_json, output_dir / "results.json") | |
| rows = [] | |
| for condition, metrics in condition_metrics.items(): | |
| rows.append({"condition": condition, **metrics}) | |
| with (output_dir / "condition_metrics.csv").open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=["condition", "samples", "top1", "top5", "nll", "ece"]) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| print(output_dir) | |
| if __name__ == "__main__": | |
| main() | |