File size: 11,231 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 | #!/usr/bin/env python3
"""Compare historical and current B/S/C model behavior and gradients."""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import platform
import sys
from pathlib import Path
from types import ModuleType
from typing import Any
import torch
from torch import nn
AUDIT_ROOT = Path("/nfs/ywang29/GmNet/e4_spectral_audit")
SNAPSHOT_ROOT = AUDIT_ROOT / "source_snapshots/alignment_4a62"
OLD_SOURCE = SNAPSHOT_ROOT / "gmnet/models/gmnet.py"
NEW_SOURCE = Path("/nfs/ywang29/GmNet/journal_exp/gmnet/models/gmnet.py")
SNAPSHOT_MANIFEST = SNAPSHOT_ROOT / "source_manifest.json"
EXPECTED_OLD_SHA256 = (
"5291156084aaf72936d1f8896057e7e606f74ef05aed856df4940e4838dbe3ac"
)
EXPECTED_NEW_SHA256 = (
"8446a0ed7d6863f81e88929f3277d363c961372210279de7d0e770f636852f3c"
)
ARMS = {
"B": "baseline",
"S": "stop_gradient",
"C": "channel_derangement",
}
COMMON_METADATA_KEYS = (
"global_block_index",
"stage_index",
"stage_block_index",
"mode",
"seed",
"channels",
"permutation_sha256",
"permutation_hash_encoding",
"fixed_points",
"is_bijection",
)
def 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 load_module(name: str, path: Path) -> ModuleType:
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise RuntimeError(f"cannot create import spec for {path}")
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
def model_kwargs(intervention: str) -> dict[str, Any]:
return {
"num_classes": 1000,
"gate_type": "relu6_self",
"stem_activation": "relu6",
"kernel_size": 7,
"layer_scale": 1e-6,
"drop_path_rate": 0.02,
"f12_bn": False,
"projection_bn": True,
"second_dw_bn": False,
"gate_intervention": intervention,
"gate_intervention_seed": 41041,
}
def maximum_abs(left: torch.Tensor, right: torch.Tensor) -> float:
return float((left.detach() - right.detach()).abs().max().item())
def assert_exact(left: torch.Tensor, right: torch.Tensor, label: str) -> float:
delta = maximum_abs(left, right)
if not torch.equal(left, right):
raise AssertionError(f"{label} is not bitwise equal; max_abs={delta}")
return delta
def compare_parameter_gradients(
old_model: nn.Module, new_model: nn.Module, arm: str
) -> tuple[int, float]:
old_parameters = dict(old_model.named_parameters())
new_parameters = dict(new_model.named_parameters())
if old_parameters.keys() != new_parameters.keys():
raise AssertionError(f"{arm}: named parameter keys differ")
maximum = 0.0
compared = 0
for name in old_parameters:
old_gradient = old_parameters[name].grad
new_gradient = new_parameters[name].grad
if (old_gradient is None) != (new_gradient is None):
raise AssertionError(f"{arm}:{name}: gradient None pattern differs")
if old_gradient is None:
continue
maximum = max(
maximum,
assert_exact(old_gradient, new_gradient, f"{arm}:{name} gradient"),
)
compared += 1
return compared, maximum
def project_metadata(rows: list[dict[str, object]]) -> list[dict[str, object]]:
return [{key: row[key] for key in COMMON_METADATA_KEYS} for row in rows]
def compare_permutations(
old_model: nn.Module, new_model: nn.Module, intervention: str
) -> dict[str, object]:
old_buffers = {
name: value
for name, value in old_model.named_buffers()
if name.endswith("gate_permutation")
}
new_buffers = {
name: value
for name, value in new_model.named_buffers()
if name.endswith("gate_permutation")
}
if old_buffers.keys() != new_buffers.keys():
raise AssertionError(f"{intervention}: gate permutation buffer keys differ")
for name in old_buffers:
assert_exact(old_buffers[name], new_buffers[name], f"{intervention}:{name}")
old_metadata = old_model.gate_intervention_metadata()
new_metadata = new_model.gate_intervention_metadata()
if project_metadata(old_metadata) != project_metadata(new_metadata):
raise AssertionError(f"{intervention}: common metadata projection differs")
expected = 17 if intervention == "channel_derangement" else 0
populated = sum(row["permutation_sha256"] is not None for row in old_metadata)
if populated != expected:
raise AssertionError(
f"{intervention}: expected {expected} populated permutations, got {populated}"
)
if len(old_metadata) != 17:
raise AssertionError(
f"{intervention}: expected 17 GmNet-S3 blocks, got {len(old_metadata)}"
)
return {
"block_count": len(old_metadata),
"populated_permutation_count": populated,
"buffer_count": len(old_buffers),
"common_metadata_equal": True,
}
def assert_stop_gradient_semantics(module: ModuleType) -> dict[str, object]:
values = torch.tensor(
[-2.0, -0.5, 0.5, 2.0, 5.5, 7.0], dtype=torch.float32
).reshape(1, 6, 1, 1)
stop_input = values.clone().requires_grad_(True)
stop_gate = module.SelfGate(
nn.ReLU6(),
"relu6_self",
channels=6,
gate_intervention="stop_gradient",
gate_intervention_seed=41041,
)
stop_gate(stop_input).sum().backward()
expected_stop = values.clamp(0.0, 6.0)
stop_delta = assert_exact(
stop_input.grad, expected_stop, "stop-gradient gate input derivative"
)
baseline_input = values.clone().requires_grad_(True)
baseline_gate = module.SelfGate(
nn.ReLU6(),
"relu6_self",
channels=6,
gate_intervention="baseline",
gate_intervention_seed=41041,
)
baseline_gate(baseline_input).sum().backward()
expected_baseline = values.clamp(0.0, 6.0) + values * (
(values > 0.0) & (values < 6.0)
)
baseline_delta = assert_exact(
baseline_input.grad,
expected_baseline,
"baseline gate input derivative",
)
if torch.equal(stop_input.grad, baseline_input.grad):
raise AssertionError("stop-gradient and baseline derivatives unexpectedly match")
return {
"stop_gradient_matches_detached_formula": True,
"baseline_matches_full_formula": True,
"stop_vs_baseline_derivative_differs": True,
"maximum_abs_error": max(stop_delta, baseline_delta),
}
def compare_arm(
old_module: ModuleType, new_module: ModuleType, arm: str, intervention: str
) -> dict[str, object]:
torch.manual_seed(73421)
old_model = old_module.create_gmnet("s3", **model_kwargs(intervention))
new_model = new_module.create_gmnet("s3", **model_kwargs(intervention))
incompatible = new_model.load_state_dict(old_model.state_dict(), strict=True)
if incompatible.missing_keys or incompatible.unexpected_keys:
raise AssertionError(f"{arm}: strict state load returned incompatible keys")
old_model.eval()
new_model.eval()
generator = torch.Generator(device="cpu")
generator.manual_seed(91173)
value = torch.randn(2, 3, 64, 64, generator=generator)
loss_weight = torch.randn(2, 1000, generator=generator)
old_input = value.clone().requires_grad_(True)
new_input = value.clone().requires_grad_(True)
old_output = old_model(old_input)
new_output = new_model(new_input)
output_delta = assert_exact(old_output, new_output, f"{arm} forward")
old_loss = (old_output * loss_weight).sum()
new_loss = (new_output * loss_weight).sum()
assert_exact(old_loss, new_loss, f"{arm} fixed random loss")
old_loss.backward()
new_loss.backward()
input_gradient_delta = assert_exact(
old_input.grad, new_input.grad, f"{arm} input gradient"
)
gradient_count, parameter_gradient_delta = compare_parameter_gradients(
old_model, new_model, arm
)
permutation = compare_permutations(old_model, new_model, intervention)
return {
"arm": arm,
"gate_intervention": intervention,
"parameter_count": sum(value.numel() for value in old_model.parameters()),
"state_tensor_count": len(old_model.state_dict()),
"compared_parameter_gradients": gradient_count,
"forward_bitwise_equal": True,
"input_gradient_bitwise_equal": True,
"parameter_gradients_bitwise_equal": True,
"maximum_abs": {
"forward": output_delta,
"input_gradient": input_gradient_delta,
"parameter_gradient": parameter_gradient_delta,
},
"permutation_and_metadata": permutation,
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--output", type=Path)
args = parser.parse_args()
old_sha256 = sha256(OLD_SOURCE)
new_sha256 = sha256(NEW_SOURCE)
if old_sha256 != EXPECTED_OLD_SHA256:
raise RuntimeError(f"old source SHA256 mismatch: {old_sha256}")
if new_sha256 != EXPECTED_NEW_SHA256:
raise RuntimeError(f"new source SHA256 mismatch: {new_sha256}")
manifest = json.loads(SNAPSHOT_MANIFEST.read_text(encoding="utf-8"))
manifest_hashes = {row["path"]: row["sha256"] for row in manifest["files"]}
if manifest_hashes.get("gmnet/models/gmnet.py") != old_sha256:
raise RuntimeError("snapshot manifest does not bind old gmnet.py")
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
old_module = load_module("gmnet_alignment_4a62", OLD_SOURCE)
new_module = load_module("gmnet_mechanism_f6bd", NEW_SOURCE)
results = [
compare_arm(old_module, new_module, arm, intervention)
for arm, intervention in ARMS.items()
]
stop_old = assert_stop_gradient_semantics(old_module)
stop_new = assert_stop_gradient_semantics(new_module)
if stop_old != stop_new:
raise AssertionError("old/new explicit stop-gradient assertions differ")
payload = {
"schema_version": 1,
"status": "passed",
"scope": "B/S/C full GmNet-S3 forward, input gradients, parameter gradients",
"old_source": {"path": str(OLD_SOURCE), "sha256": old_sha256},
"new_source": {"path": str(NEW_SOURCE), "sha256": new_sha256},
"runtime": {
"python": platform.python_version(),
"torch": torch.__version__,
"threads": torch.get_num_threads(),
"deterministic_algorithms": torch.are_deterministic_algorithms_enabled(),
},
"arms": results,
"explicit_stop_gradient_semantics": stop_old,
}
rendered = json.dumps(payload, indent=2, sort_keys=True) + "\n"
if args.output is not None:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(rendered, encoding="utf-8")
print(rendered, end="")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|