File size: 72,188 Bytes
12c2325 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 | #!/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()),
}
@dataclass
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)
@property
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
@torch.inference_mode()
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()
|