Download annotations/annotation_43/test.py from mcy98/RECODE-H: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_43/test.py
- Command line
-
hf download hf://datasets/mcy98/RECODE-H/annotations/annotation_43/test.py
-
curl -L -o test.py https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_43/test.py
10.3 kB
| # test_graph_acl.py | |
| import unittest | |
| import torch | |
| import dgl # For creating sample graph objects | |
| import copy # For deepcopying models if needed for state comparison | |
| import numpy as np # For comparing numpy arrays if scores are returned as such | |
| import sys | |
| import os | |
| from homo.canonical import Model as CanonicalModel | |
| from homo.model import Model as GeneratedModel | |
| # --- Sample Data --- | |
| def create_sample_graph_data(): | |
| """Creates a few small DGL graph instances for testing.""" | |
| data = [] | |
| # Graph 1: 3 nodes, 2 edges | |
| g1 = dgl.graph(([0, 1], [1, 2])) | |
| g1 = dgl.add_self_loop(g1) | |
| g1_feat = torch.randn(3, 10) # 3 nodes, 10 features | |
| data.append({"id": "g1", "graph": g1, "feat": g1_feat, "in_dim": 10, "out_dim": 8}) | |
| # Graph 2: 4 nodes, 4 edges (including a self-loop for variety) | |
| g2 = dgl.graph(([0, 1, 2, 0], [1, 2, 3, 0])) | |
| g2 = dgl.add_self_loop(g2) | |
| g2_feat = torch.randn(4, 16) # 4 nodes, 16 features | |
| data.append({"id": "g2", "graph": g2, "feat": g2_feat, "in_dim": 16, "out_dim": 8}) | |
| # Graph 3: Disconnected components | |
| g3 = dgl.graph(([0, 2], [1, 3])) # Edges 0-1 and 2-3 | |
| g3 = dgl.add_self_loop(g3) | |
| g3_feat = torch.randn(4, 5) # 4 nodes, 5 features | |
| data.append({"id": "g3_disconnected", "graph": g3, "feat": g3_feat, "in_dim": 5, "out_dim": 4}) | |
| return data | |
| sample_graph_data = create_sample_graph_data() | |
| # --- Model Parameters --- | |
| # Common parameters for initializing models, can be varied per test if needed | |
| model_common_params = { | |
| "hid_dim": 16, # GCN hidden | |
| # "out_dim": 8, # GCN output & Projector I/O - will be taken from sample_graph_data | |
| "num_layers": 2, # GCN layers | |
| "temp": 0.5, | |
| "moving_average_decay": 0.99, | |
| "num_MLP": 1 # Predictor layers | |
| } | |
| class TestGraphACLImplementations(unittest.TestCase): | |
| def setUpClass(cls): | |
| """Initialize canonical and generated Model instances.""" | |
| cls.canonical_instance = None | |
| cls.generated_instance = None | |
| cls.skip_all_tests = False | |
| print("\nAttempting to initialize Canonical GraphACL Model instance...") | |
| try: | |
| # Use first sample's dims for a generic instance, can be re-init per test | |
| # FIX: Align out_dim and hid_dim for setup instance to prevent crash if it were used directly | |
| params = {**model_common_params, | |
| "in_dim": sample_graph_data[0]["in_dim"], | |
| "out_dim": model_common_params["hid_dim"]} | |
| cls.canonical_instance = CanonicalModel(**params) | |
| print("Canonical GraphACL Model instance created successfully.") | |
| except Exception as e: | |
| print(f"Failed to initialize CanonicalModel: {e}") | |
| cls.skip_all_tests = True # Skip tests if canonical fails | |
| raise unittest.SkipTest(f"Skipping all tests due to CanonicalModel initialization failure: {e}") | |
| if GeneratedModel is None: | |
| print("GeneratedModel could not be imported. Skipping tests involving generated model.") | |
| cls.skip_all_tests = True | |
| raise unittest.SkipTest("Skipping all tests because GeneratedModel could not be imported.") | |
| print("\nAttempting to initialize Generated GraphACL Model instance...") | |
| try: | |
| params = {**model_common_params, | |
| "in_dim": sample_graph_data[0]["in_dim"], | |
| "out_dim": model_common_params["hid_dim"]} | |
| cls.generated_instance = GeneratedModel(**params) | |
| print("Generated GraphACL Model instance created successfully.") | |
| except Exception as e: | |
| print(f"Failed to initialize GeneratedModel: {e}") | |
| cls.skip_all_tests = True # Skip tests if generated fails | |
| raise unittest.SkipTest(f"Skipping all tests due to GeneratedModel initialization failure: {e}") | |
| def assertTensorsAlmostEqual(self, tensor1, tensor2, places=5, msg_prefix=""): | |
| """Helper to compare two tensors.""" | |
| self.assertIsInstance(tensor1, torch.Tensor, f"{msg_prefix}: Canonical output is not a tensor.") | |
| self.assertIsInstance(tensor2, torch.Tensor, f"{msg_prefix}: Generated output is not a tensor.") | |
| self.assertEqual(tensor1.shape, tensor2.shape, | |
| f"{msg_prefix}: Tensor shapes differ - Canonical={tensor1.shape}, Generated={tensor2.shape}") | |
| self.assertTrue(torch.allclose(tensor1, tensor2, atol=10 ** (-places)), | |
| f"{msg_prefix}: Tensor values differ.\nCanonical:\n{tensor1}\nGenerated:\n{tensor2}") | |
| def test_forward_pass_and_loss(self): | |
| """Compare the output of the forward pass (loss value).""" | |
| if self.skip_all_tests: | |
| self.skipTest("Skipping test_forward_pass_and_loss due to setup failure.") | |
| print("\nComparing forward pass (loss)...") | |
| for data in sample_graph_data: | |
| g = data["graph"] | |
| feat = data["feat"] | |
| # FIX: The canonical model expects the GCN output dim (out_dim) to be the same as the | |
| # projector's input dim (hid_dim). We align them here to fix the crash. | |
| current_params = {**model_common_params, | |
| "in_dim": data["in_dim"], | |
| "out_dim": model_common_params["hid_dim"]} | |
| try: | |
| canonical_model = CanonicalModel(**current_params) | |
| generated_model = GeneratedModel(**current_params) | |
| generated_model.load_state_dict(canonical_model.state_dict()) | |
| except Exception as e: | |
| self.fail(f"Failed to re-initialize/load state_dict for graph {data['id']}: {e}") | |
| with self.subTest(msg=f"Testing forward pass for graph: {data['id']}"): | |
| canonical_model.train() | |
| generated_model.train() | |
| canonical_loss = canonical_model(g, feat) | |
| generated_loss = generated_model(g, feat) | |
| self.assertTensorsAlmostEqual(canonical_loss, generated_loss, msg_prefix=f"Loss for {data['id']}") | |
| print( | |
| f" Graph '{data['id']}': Canonical Loss={canonical_loss.item():.4f}, Generated Loss={generated_loss.item():.4f}") | |
| def test_get_embedding(self): | |
| """Compare the output of get_embedding.""" | |
| if self.skip_all_tests: | |
| self.skipTest("Skipping test_get_embedding due to setup failure.") | |
| print("\nComparing get_embedding...") | |
| for data in sample_graph_data: | |
| g = data["graph"] | |
| feat = data["feat"] | |
| # FIX: Aligning out_dim with hid_dim to match the model's architecture. | |
| current_params = {**model_common_params, | |
| "in_dim": data["in_dim"], | |
| "out_dim": model_common_params["hid_dim"]} | |
| try: | |
| canonical_model = CanonicalModel(**current_params) | |
| generated_model = GeneratedModel(**current_params) | |
| generated_model.load_state_dict(canonical_model.state_dict()) | |
| except Exception as e: | |
| self.fail(f"Failed to re-initialize/load state_dict for graph {data['id']} (get_embedding): {e}") | |
| with self.subTest(msg=f"Testing get_embedding for graph: {data['id']}"): | |
| canonical_model.eval() | |
| generated_model.eval() | |
| canonical_emb = canonical_model.get_embedding(g, feat) | |
| generated_emb = generated_model.get_embedding(g, feat) | |
| self.assertTensorsAlmostEqual(canonical_emb, generated_emb, msg_prefix=f"Embeddings for {data['id']}") | |
| print(f" Graph '{data['id']}': Embeddings compared (shape: {canonical_emb.shape}).") | |
| self.assertFalse(canonical_emb.requires_grad, f"Canonical embedding for {data['id']} requires grad.") | |
| self.assertFalse(generated_emb.requires_grad, f"Generated embedding for {data['id']} requires grad.") | |
| def test_update_moving_average(self): | |
| """Test the update_moving_average functionality.""" | |
| if self.skip_all_tests: | |
| self.skipTest("Skipping test_update_moving_average due to setup failure.") | |
| print("\nTesting update_moving_average...") | |
| data = sample_graph_data[0] | |
| # FIX: Aligning out_dim with hid_dim to match the model's architecture. | |
| current_params = {**model_common_params, | |
| "in_dim": data["in_dim"], | |
| "out_dim": model_common_params["hid_dim"], | |
| "moving_average_decay": 0.9 | |
| } | |
| try: | |
| canonical_model = CanonicalModel(**current_params) | |
| generated_model = GeneratedModel(**current_params) | |
| generated_model.encoder.load_state_dict(canonical_model.encoder.state_dict()) | |
| generated_model.encoder_target.load_state_dict(canonical_model.encoder_target.state_dict()) | |
| except Exception as e: | |
| self.fail(f"Failed to initialize models for update_moving_average test: {e}") | |
| initial_canonical_target_params = [p.clone() for p in canonical_model.encoder_target.parameters()] | |
| with torch.no_grad(): | |
| for param in canonical_model.encoder.parameters(): | |
| param.data.add_(torch.randn_like(param.data) * 0.01) | |
| generated_model.encoder.load_state_dict(canonical_model.encoder.state_dict()) | |
| canonical_model.update_moving_average() | |
| generated_model.update_moving_average() | |
| for i, (can_param, gen_param) in enumerate(zip(canonical_model.encoder_target.parameters(), | |
| generated_model.encoder_target.parameters())): | |
| self.assertTensorsAlmostEqual(can_param.data, gen_param.data, | |
| msg_prefix=f"Target encoder param {i} after update_moving_average") | |
| self.assertFalse(torch.equal(can_param.data, initial_canonical_target_params[i]), | |
| f"Canonical target encoder param {i} did not change after EMA update.") | |
| print(" update_moving_average: Target encoder parameters compared and confirmed change.") | |
| if __name__ == '__main__': | |
| unittest.main(verbosity=2) |