Download gmnet/code/journal_exp/tests/test_models.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/tests/test_models.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/code/journal_exp/tests/test_models.py
-
curl -L -o test_models.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/tests/test_models.py
18.2 kB
| """Unit tests for paper GmNet variants and gate ablations.""" | |
| from __future__ import annotations | |
| import copy | |
| import unittest | |
| import torch | |
| from gmnet.models import ( | |
| GATE_INTERVENTION_SEED_STRIDE, | |
| GMNET_CONFIGS, | |
| GmNet, | |
| GmNetBlock, | |
| SmoothClippedSelfGate, | |
| build_gate, | |
| gmnet_s1, | |
| gmnet_s2, | |
| gmnet_s3, | |
| gmnet_s4, | |
| ) | |
| class GateTests(unittest.TestCase): | |
| def test_required_gate_semantics(self) -> None: | |
| x = torch.tensor([[[[-2.0, -0.5, 0.5, 2.0, 8.0]]]]) | |
| torch.testing.assert_close( | |
| build_gate("relu6_self", 1)(x), x * torch.clamp(x, 0.0, 6.0) | |
| ) | |
| torch.testing.assert_close( | |
| build_gate("relu6_only", 1)(x), torch.clamp(x, 0.0, 6.0) | |
| ) | |
| torch.testing.assert_close(build_gate("relu_self", 1)(x), x * torch.relu(x)) | |
| torch.testing.assert_close( | |
| build_gate("gelu_self", 1)(x), x * torch.nn.functional.gelu(x) | |
| ) | |
| torch.testing.assert_close(build_gate("identity", 1)(x), x.square()) | |
| torch.testing.assert_close(build_gate("no_gate", 1)(x), x) | |
| def test_smooth_clipped_gate_is_static_learnable_and_bounded(self) -> None: | |
| gate = SmoothClippedSelfGate(3, init_clip=6.0, beta=10.0) | |
| x = torch.linspace(-10.0, 12.0, 23).view(1, 1, 1, 23).expand(2, 3, 4, 23) | |
| values = gate.gate_value(x) | |
| self.assertEqual(gate.raw_clip.shape, (1, 3, 1, 1)) | |
| self.assertTrue(torch.all(gate.clip_value > 0)) | |
| self.assertGreaterEqual(float(values.detach().min()), -1e-6) | |
| self.assertLessEqual( | |
| float(values.detach().max()), float(gate.clip_value.detach().max()) + 1e-5 | |
| ) | |
| loss = gate(x).square().mean() | |
| loss.backward() | |
| self.assertIsNotNone(gate.raw_clip.grad) | |
| self.assertTrue(torch.isfinite(gate.raw_clip.grad).all()) | |
| self.assertGreater(float(gate.raw_clip.grad.abs().sum()), 0.0) | |
| def test_smooth_clipped_gate_supports_fixed_persistent_clip(self) -> None: | |
| gate = SmoothClippedSelfGate( | |
| 3, init_clip=6.0, beta=10.0, per_channel=False, trainable=False | |
| ) | |
| self.assertIsNone(gate.raw_clip) | |
| self.assertEqual(sum(parameter.numel() for parameter in gate.parameters()), 0) | |
| torch.testing.assert_close(gate.clip_value, torch.tensor([[[[6.0]]]])) | |
| self.assertIn("fixed_clip", gate.state_dict()) | |
| restored = SmoothClippedSelfGate( | |
| 3, init_clip=6.0, beta=10.0, per_channel=False, trainable=False | |
| ) | |
| restored.load_state_dict(gate.state_dict(), strict=True) | |
| x = torch.randn(2, 3, 4, 4) | |
| torch.testing.assert_close(restored(x), gate(x)) | |
| def test_smooth_checkpoint_topology_is_rebuilt_from_trainable_config(self) -> None: | |
| common = { | |
| "embed_dims": (8, 16, 24, 32), | |
| "depths": (1, 1, 1, 1), | |
| "mlp_ratios": (1, 1, 1, 1), | |
| "stem_dim": 8, | |
| "num_classes": 5, | |
| "gate_type": "smooth_clipped_self", | |
| "smooth_clip_per_channel": False, | |
| } | |
| for trainable, state_suffix in ((True, "raw_clip"), (False, "fixed_clip")): | |
| with self.subTest(trainable=trainable): | |
| config = {**common, "smooth_clip_trainable": trainable} | |
| source = GmNet(**config) | |
| checkpoint = { | |
| "config": copy.deepcopy(config), | |
| "model": copy.deepcopy(source.state_dict()), | |
| } | |
| restored = GmNet(**checkpoint["config"]) | |
| restored.load_state_dict(checkpoint["model"], strict=True) | |
| gate_keys = [ | |
| key | |
| for key in checkpoint["model"] | |
| if key.endswith(("raw_clip", "fixed_clip")) | |
| ] | |
| self.assertTrue(gate_keys) | |
| self.assertTrue(all(key.endswith(state_suffix) for key in gate_keys)) | |
| def test_invalid_gate_is_rejected(self) -> None: | |
| with self.assertRaisesRegex(ValueError, "unknown gate_type"): | |
| build_gate("not_a_gate", 8) | |
| def test_stop_gradient_preserves_forward_and_changes_gate_gradient(self) -> None: | |
| baseline = build_gate("relu6_self", 3) | |
| stopped = build_gate("relu6_self", 3, gate_intervention="stop_gradient") | |
| baseline_input = torch.tensor([0.5, 2.0, 4.0]).view(1, 3, 1, 1) | |
| baseline_input.requires_grad_() | |
| stopped_input = baseline_input.detach().clone().requires_grad_() | |
| baseline_output = baseline(baseline_input) | |
| stopped_output = stopped(stopped_input) | |
| self.assertTrue(torch.equal(baseline_output, stopped_output)) | |
| baseline_output.sum().backward() | |
| stopped_output.sum().backward() | |
| self.assertTrue(torch.isfinite(stopped_input.grad).all()) | |
| self.assertFalse(torch.equal(baseline_input.grad, stopped_input.grad)) | |
| torch.testing.assert_close( | |
| stopped_input.grad, torch.tensor([0.5, 2.0, 4.0]).view(1, 3, 1, 1) | |
| ) | |
| def test_channel_derangement_is_deterministic_and_preserves_multiset(self) -> None: | |
| first = build_gate( | |
| "relu6_self", | |
| 8, | |
| gate_intervention="channel_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| second = build_gate( | |
| "relu6_self", | |
| 8, | |
| gate_intervention="channel_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| permutation = first.gate_permutation | |
| self.assertIsNotNone(permutation) | |
| assert permutation is not None | |
| self.assertTrue(torch.equal(permutation, second.gate_permutation)) | |
| self.assertTrue( | |
| torch.equal(permutation.sort().values, torch.arange(permutation.numel())) | |
| ) | |
| self.assertTrue(torch.all(permutation != torch.arange(permutation.numel()))) | |
| x = torch.arange(48, dtype=torch.float32).reshape(2, 8, 1, 3) | |
| permuted = first.gate_input(x) | |
| torch.testing.assert_close(permuted.sort(dim=1).values, x.sort(dim=1).values) | |
| torch.testing.assert_close(first(x), x * torch.clamp(permuted, 0.0, 6.0)) | |
| def test_channel_derangement_does_not_consume_global_rng(self) -> None: | |
| torch.manual_seed(73) | |
| expected = torch.rand(7) | |
| torch.manual_seed(73) | |
| build_gate( | |
| "relu6_self", | |
| 8, | |
| gate_intervention="channel_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| actual = torch.rand(7) | |
| self.assertTrue(torch.equal(actual, expected)) | |
| def test_batch_derangement_is_seeded_bijective_and_rng_free(self) -> None: | |
| gate = build_gate( | |
| "relu6_self", | |
| 3, | |
| gate_intervention="batch_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| x = torch.arange(60, dtype=torch.float32).reshape(5, 3, 2, 2) | |
| shift = 1 + 41_041 % 4 | |
| expected_input = x.roll(shifts=-shift, dims=0) | |
| torch.manual_seed(919) | |
| expected_rng = torch.rand(8) | |
| torch.manual_seed(919) | |
| actual_input = gate.gate_input(x) | |
| actual_rng = torch.rand(8) | |
| self.assertEqual(gate.batch_derangement_shift(5), shift) | |
| self.assertTrue(torch.equal(actual_input, expected_input)) | |
| self.assertTrue(torch.equal(actual_rng, expected_rng)) | |
| self.assertTrue( | |
| torch.equal( | |
| actual_input.flatten(1).sort(dim=0).values, | |
| x.flatten(1).sort(dim=0).values, | |
| ) | |
| ) | |
| with self.assertRaisesRegex(ValueError, "at least two samples"): | |
| gate.gate_input(x[:1]) | |
| def test_stop_gradient_channel_derangement_matches_forward_only(self) -> None: | |
| channel = build_gate( | |
| "relu6_self", | |
| 4, | |
| gate_intervention="channel_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| combined = build_gate( | |
| "relu6_self", | |
| 4, | |
| gate_intervention="stop_gradient_channel_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| self.assertTrue(torch.equal(channel.gate_permutation, combined.gate_permutation)) | |
| channel_input = ( | |
| torch.tensor([0.5, 1.5, 2.5, 3.5]) | |
| .reshape(1, 4, 1, 1) | |
| .requires_grad_() | |
| ) | |
| combined_input = channel_input.detach().clone().requires_grad_() | |
| channel_output = channel(channel_input) | |
| combined_output = combined(combined_input) | |
| self.assertTrue(torch.equal(channel_output, combined_output)) | |
| channel_output.sum().backward() | |
| combined_output.sum().backward() | |
| self.assertFalse(torch.equal(channel_input.grad, combined_input.grad)) | |
| torch.testing.assert_close( | |
| combined_input.grad, | |
| torch.clamp( | |
| combined.gate_input(combined_input.detach()), min=0.0, max=6.0 | |
| ), | |
| ) | |
| def test_intervention_rejects_non_self_gate_and_invalid_mode(self) -> None: | |
| for gate_type in ("relu6_only", "no_gate"): | |
| with self.subTest(gate_type=gate_type): | |
| with self.assertRaisesRegex(ValueError, "multiplicative self-gate"): | |
| build_gate(gate_type, 8, gate_intervention="channel_derangement") | |
| with self.assertRaisesRegex(ValueError, "unknown gate_intervention"): | |
| build_gate("relu6_self", 8, gate_intervention="not_an_intervention") | |
| class GmNetTests(unittest.TestCase): | |
| FACTORIES = { | |
| "s1": gmnet_s1, | |
| "s2": gmnet_s2, | |
| "s3": gmnet_s3, | |
| "s4": gmnet_s4, | |
| } | |
| EXPECTED_PARAMETERS = { | |
| "s1": 3_661_600, | |
| "s2": 6_206_296, | |
| "s3": 7_791_544, | |
| "s4": 17_061_460, | |
| } | |
| def test_paper_variant_topology_parameters_and_forward(self) -> None: | |
| for name, factory in self.FACTORIES.items(): | |
| with self.subTest(variant=name): | |
| model = factory().eval() | |
| config = GMNET_CONFIGS[name] | |
| self.assertEqual(model.embed_dims, config.embed_dims) | |
| self.assertEqual(model.depths, config.depths) | |
| self.assertEqual(model.mlp_ratios, config.mlp_ratios) | |
| self.assertEqual( | |
| tuple(len(stage) - 1 for stage in model.stages), config.depths | |
| ) | |
| parameter_count = sum( | |
| parameter.numel() for parameter in model.parameters() | |
| ) | |
| self.assertEqual(parameter_count, self.EXPECTED_PARAMETERS[name]) | |
| model.reset_classifier(17) | |
| with torch.inference_mode(): | |
| output = model(torch.randn(1, 3, 64, 64)) | |
| self.assertEqual(output.shape, (1, 17)) | |
| self.assertTrue(torch.isfinite(output).all()) | |
| def test_all_gate_types_run_in_a_model(self) -> None: | |
| gate_types = ( | |
| "relu6_self", | |
| "relu6_only", | |
| "relu_self", | |
| "gelu_self", | |
| "identity", | |
| "no_gate", | |
| "smooth_clipped_self", | |
| ) | |
| for gate_type in gate_types: | |
| with self.subTest(gate_type=gate_type): | |
| model = GmNet( | |
| embed_dims=(8, 16, 24, 32), | |
| depths=(1, 1, 1, 1), | |
| mlp_ratios=(1, 1, 1, 1), | |
| stem_dim=8, | |
| num_classes=5, | |
| gate_type=gate_type, | |
| ).eval() | |
| with torch.inference_mode(): | |
| output = model(torch.randn(1, 3, 64, 64)) | |
| self.assertEqual(output.shape, (1, 5)) | |
| def test_experiment_registry_gate_aliases(self) -> None: | |
| aliases = { | |
| "relu6": "relu6_self", | |
| "activation_only": "relu6_only", | |
| "relu6_activation_only": "relu6_only", | |
| "relu": "relu_self", | |
| "gelu": "gelu_self", | |
| "smooth_clipped_static": "smooth_clipped_self", | |
| } | |
| x = torch.randn(2, 3, 4, 4) | |
| for alias, canonical in aliases.items(): | |
| with self.subTest(alias=alias): | |
| torch.testing.assert_close( | |
| build_gate(alias, 3)(x), build_gate(canonical, 3)(x) | |
| ) | |
| def test_stage_specific_gates_and_feature_head(self) -> None: | |
| model = GmNet( | |
| embed_dims=(8, 16, 24, 32), | |
| depths=(1, 1, 1, 1), | |
| mlp_ratios=(1, 1, 1, 1), | |
| stem_dim=8, | |
| num_classes=0, | |
| gate_type=("no_gate", "relu_self", "gelu_self", "smooth_clipped_self"), | |
| ).eval() | |
| self.assertEqual( | |
| model.gate_types, | |
| ("no_gate", "relu_self", "gelu_self", "smooth_clipped_self"), | |
| ) | |
| with torch.inference_mode(): | |
| output = model(torch.randn(2, 3, 64, 64)) | |
| self.assertEqual(output.shape, (2, 32)) | |
| model.reset_classifier(7) | |
| with torch.inference_mode(): | |
| output = model(torch.randn(2, 3, 64, 64)) | |
| self.assertEqual(output.shape, (2, 7)) | |
| def _tiny_model(**kwargs: object) -> GmNet: | |
| return GmNet( | |
| embed_dims=(8, 16, 24, 32), | |
| depths=(1, 1, 1, 1), | |
| mlp_ratios=(2, 2, 2, 2), | |
| stem_dim=8, | |
| num_classes=5, | |
| **kwargs, | |
| ) | |
| def test_default_and_explicit_baseline_are_bitwise_compatible(self) -> None: | |
| torch.manual_seed(991) | |
| default = self._tiny_model().eval() | |
| torch.manual_seed(991) | |
| explicit = self._tiny_model( | |
| gate_intervention="baseline", gate_intervention_seed=41_041 | |
| ).eval() | |
| self.assertEqual(default.state_dict().keys(), explicit.state_dict().keys()) | |
| for key, value in default.state_dict().items(): | |
| self.assertTrue(torch.equal(value, explicit.state_dict()[key]), key) | |
| x = torch.randn(2, 3, 64, 64) | |
| with torch.inference_mode(): | |
| self.assertTrue(torch.equal(default(x), explicit(x))) | |
| def test_interventions_preserve_parameters_and_checkpoint_schema(self) -> None: | |
| models = { | |
| mode: self._tiny_model( | |
| gate_intervention=mode, gate_intervention_seed=41_041 | |
| ) | |
| for mode in ( | |
| "baseline", | |
| "stop_gradient", | |
| "channel_derangement", | |
| "batch_derangement", | |
| "stop_gradient_channel_derangement", | |
| ) | |
| } | |
| baseline = models["baseline"] | |
| expected_keys = tuple(baseline.state_dict()) | |
| expected_parameters = sum(p.numel() for p in baseline.parameters()) | |
| for mode, model in models.items(): | |
| with self.subTest(mode=mode): | |
| self.assertEqual(tuple(model.state_dict()), expected_keys) | |
| self.assertEqual( | |
| sum(p.numel() for p in model.parameters()), expected_parameters | |
| ) | |
| model.load_state_dict(baseline.state_dict(), strict=True) | |
| self.assertFalse( | |
| any("gate_permutation" in key for key in model.state_dict()) | |
| ) | |
| def test_channel_derangement_uses_per_block_seed_and_auditable_metadata( | |
| self, | |
| ) -> None: | |
| model = gmnet_s3( | |
| gate_intervention="channel_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| metadata = model.gate_intervention_metadata() | |
| blocks = [ | |
| module for module in model.modules() if isinstance(module, GmNetBlock) | |
| ] | |
| self.assertEqual(len(metadata), 17) | |
| self.assertEqual(len(blocks), 17) | |
| for index, (block, item) in enumerate(zip(blocks, metadata, strict=True)): | |
| with self.subTest(block=index): | |
| expected_seed = 41_041 + index * GATE_INTERVENTION_SEED_STRIDE | |
| self.assertEqual(block.gate_intervention_seed, expected_seed) | |
| self.assertEqual(item["seed"], expected_seed) | |
| self.assertEqual(item["global_block_index"], index) | |
| self.assertEqual(item["mode"], "channel_derangement") | |
| self.assertEqual(item["fixed_points"], 0) | |
| self.assertIs(item["is_bijection"], True) | |
| self.assertEqual(len(item["permutation_sha256"]), 64) | |
| self.assertEqual( | |
| item["permutation_hash_encoding"], | |
| "little_endian_int64_c_order", | |
| ) | |
| self.assertIn( | |
| "gate_permutation", block.gate._non_persistent_buffers_set | |
| ) | |
| def test_combined_intervention_reuses_every_channel_permutation(self) -> None: | |
| channel = gmnet_s3( | |
| gate_intervention="channel_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| combined = gmnet_s3( | |
| gate_intervention="stop_gradient_channel_derangement", | |
| gate_intervention_seed=41_041, | |
| ) | |
| channel_rows = channel.gate_intervention_metadata() | |
| combined_rows = combined.gate_intervention_metadata() | |
| self.assertEqual(len(channel_rows), 17) | |
| self.assertEqual(len(combined_rows), 17) | |
| for channel_row, combined_row in zip( | |
| channel_rows, combined_rows, strict=True | |
| ): | |
| self.assertEqual( | |
| channel_row["permutation_sha256"], | |
| combined_row["permutation_sha256"], | |
| ) | |
| self.assertIs(combined_row["stops_gate_gradient"], True) | |
| self.assertIs(combined_row["channel_derangement"], True) | |
| self.assertIs(combined_row["batch_derangement"], False) | |
| def test_stop_gradient_model_has_finite_parameter_gradients(self) -> None: | |
| model = self._tiny_model(gate_intervention="stop_gradient") | |
| loss = model(torch.randn(2, 3, 64, 64)).square().mean() | |
| loss.backward() | |
| gradients = [ | |
| parameter.grad | |
| for parameter in model.parameters() | |
| if parameter.requires_grad | |
| ] | |
| self.assertTrue(all(gradient is not None for gradient in gradients)) | |
| self.assertTrue(all(torch.isfinite(gradient).all() for gradient in gradients)) | |
| if __name__ == "__main__": | |
| unittest.main() | |