import unittest import torch import torch.nn as nn from types import SimpleNamespace import numpy.testing as npt # Assume the provided code is in a file named "canonical.py" # To adhere to the test structure, we will treat it as both the canonical # and the generated implementation. from canonical import NAD as CanonicalSmoothGNN from model import NAD as GeneratedSmoothGNN class TestSmoothGNNEquivalence(unittest.TestCase): """ Test suite to verify the functional equivalence between the generated SmoothGNN implementation and a canonical version. """ @classmethod def setUpClass(cls): """ Set up the test environment. This method is run once for the entire class. It prepares shared data and model configurations. """ # --- Define Hyperparameters --- cls.input_dim = 16 cls.hidden_dim = 32 cls.num_hops = 3 cls.num_nodes = 20 cls.num_class = 5 # This parameter is required by __init__ but unused in forward cls.initialization_std_dev = 0.1 cls.seed = 42 # --- Create Mock Input Data --- # The canonical implementation expects a `graphdata` object containing pre-processed # tensors. We create a mock object for this purpose. torch.manual_seed(cls.seed) # This object simulates the structure the model expects for holding data. graphdata = SimpleNamespace() graphdata.hop = cls.num_hops # `features` and `xlx` are used as initial node features. In the paper's # context, this is the matrix X. graphdata.features = torch.randn(cls.num_nodes, cls.input_dim) graphdata.xlx = torch.randn(cls.num_nodes, cls.input_dim) # Used for coefficient calculation # `embeddings` and `distances` are lists of per-hop features. These correspond to # the inputs for the two parallel processing streams in the forward pass. # Conceptually, they align with the per-hop inputs for SSGNN and SLC. graphdata.embeddings = [torch.randn(cls.num_nodes, cls.input_dim) for _ in range(cls.num_hops)] graphdata.distances = [torch.randn(cls.num_nodes, cls.input_dim) for _ in range(cls.num_hops)] cls.graphdata = graphdata # --- Instantiate Models --- # Set a seed right before initialization to ensure both models start # with identical random weights. This is crucial for comparing them. torch.manual_seed(cls.seed) cls.canonical_model = CanonicalSmoothGNN( in_dim=cls.input_dim, hidden_dim=cls.hidden_dim, num_class=cls.num_class, graphdata=cls.graphdata, init=cls.initialization_std_dev ) torch.manual_seed(cls.seed) cls.generated_model = GeneratedSmoothGNN( in_dim=cls.input_dim, hidden_dim=cls.hidden_dim, num_class=cls.num_class, graphdata=cls.graphdata, init=cls.initialization_std_dev ) # Set models to evaluation mode. This is good practice to ensure # layers like BatchNorm or Dropout behave deterministically. cls.canonical_model.eval() cls.generated_model.eval() def test_model_initialization(self): """ Instruction 1 Test: Verify that the model initialization is identical. This test compares the state dictionaries of the canonical and generated models. A successful pass indicates that both `__init__` methods constructed the same architecture with the same layers and that the `init_weight` method initialized all parameters identically. """ canonical_state_dict = self.canonical_model.state_dict() generated_state_dict = self.generated_model.state_dict() # Check if both models have the same number of parameters/layers. self.assertEqual(len(canonical_state_dict), len(generated_state_dict), "Models have a different number of layers.") # Check each parameter tensor for equality. for param_name in canonical_state_dict: with self.subTest(param=param_name): self.assertIn(param_name, generated_state_dict, f"Parameter '{param_name}' not found in the generated model.") canonical_param = canonical_state_dict[param_name] generated_param = generated_state_dict[param_name] # Use torch's testing utility for robust float tensor comparison. torch.testing.assert_close( canonical_param, generated_param, rtol=1e-5, atol=1e-8, msg=f"Parameter mismatch for '{param_name}'" ) def test_forward_pass_equivalence(self): """ Instruction 2 Test: Verify that the forward pass is functionally identical. This test executes the `forward` method on both models with the same input data (provided via the `graphdata` object in `setUpClass`). It then asserts that the outputs (reconstructed features and anomaly scores) are identical. """ # Execute the forward pass for both models. # No arguments are needed as the model pulls data from `self.graphdata`. canonical_recon, canonical_anomaly = self.canonical_model.forward() generated_recon, generated_anomaly = self.generated_model.forward() # --- Verify Output Shapes and Types --- self.assertIsInstance(generated_recon, torch.Tensor, "Reconstructed features should be a Tensor.") self.assertIsInstance(generated_anomaly, torch.Tensor, "Anomaly scores should be a Tensor.") self.assertEqual(canonical_recon.shape, generated_recon.shape, "Shape mismatch for reconstructed features.") self.assertEqual(canonical_anomaly.shape, generated_anomaly.shape, "Shape mismatch for anomaly scores.") # --- Verify Output Values --- # Compare the reconstructed feature error tensors. torch.testing.assert_close( canonical_recon, generated_recon, rtol=1e-5, atol=1e-8, msg="Output mismatch for reconstructed features." ) # Compare the final anomaly score tensors. torch.testing.assert_close( canonical_anomaly, generated_anomaly, rtol=1e-5, atol=1e-8, msg="Output mismatch for anomaly scores." ) if __name__ == '__main__': # This allows the test to be run from the command line unittest.main(argv=['first-arg-is-ignored'], exit=False)