Download gmnet/spectral_audit/scripts/test_alignment_source_equivalence.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/spectral_audit/scripts/test_alignment_source_equivalence.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/spectral_audit/scripts/test_alignment_source_equivalence.py
-
curl -L -o test_alignment_source_equivalence.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/spectral_audit/scripts/test_alignment_source_equivalence.py
11.2 kB
| #!/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()) | |