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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
"""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))

    @staticmethod
    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()