mcy98's picture
Upload folder using huggingface_hub
6077218 verified
Raw History Blame Contribute Delete
7.09 kB
import unittest
import torch
import dgl
# Assume the user's provided code is in a file named 'canonical.py'
# and the generated version is in 'generation.py'.
# A utility file 'utils.py' with a 'sim' function is also required.
from canonical import HomoGCL as CanonicalHomoGCL
from model import HomoGCL as GeneratedHomoGCL
class TestFunctionalEquivalence(unittest.TestCase):
"""
Test suite to verify that the generated HomoGCL model implementation is functionally
identical to the canonical implementation.
"""
def setUp(self):
"""
Set up common parameters and data for all tests.
"""
torch.manual_seed(42)
# Define model and data parameters
self.in_dim = 16
self.hid_dim = 12
self.out_dim = 8
self.n_layers = 2
self.num_nodes = 10
self.num_proj_hidden = 16
self.tau = 0.5
# --- Instantiate Models ---
# Instruction 1: Initialize HomoGCL Model
torch.manual_seed(42)
self.canonical_model = CanonicalHomoGCL(
self.in_dim, self.hid_dim, self.out_dim, self.n_layers,
self.num_nodes, self.num_proj_hidden, self.tau
)
torch.manual_seed(42)
self.generated_model = GeneratedHomoGCL(
self.in_dim, self.hid_dim, self.out_dim, self.n_layers,
self.num_nodes, self.num_proj_hidden, self.tau
)
# Ensure models start with identical weights
self.generated_model.load_state_dict(self.canonical_model.state_dict())
# --- Create Sample Data ---
self.graph = dgl.rand_graph(self.num_nodes, 20)
# FIX: Add self-loops to the graph to prevent the DGLError
self.graph = dgl.add_self_loop(self.graph)
self.features = torch.randn(self.num_nodes, self.in_dim)
# Edge weights need to be adjusted for the new self-loop edges
self.edge_weights = torch.randn(self.graph.number_of_edges())
# For posaug, features must have dimension `num_nodes`
self.posaug_features = torch.eye(self.num_nodes)
# For the loss function, create embeddings and dense adjacency matrices
self.z1 = torch.randn(self.num_nodes, self.out_dim)
self.z2 = torch.randn(self.num_nodes, self.out_dim)
self.adj_matrix1 = torch.randint(0, 2, (self.num_nodes, self.num_nodes)).float()
self.adj_matrix2 = torch.randint(0, 2, (self.num_nodes, self.num_nodes)).float()
self.confmatrix = torch.rand(self.num_nodes, self.num_nodes)
def test_model_initialization(self):
"""
Test Instruction 1: Verify the HomoGCL model initializes correctly.
"""
# Compare parameters of the encoder
for p_canon, p_gen in zip(self.canonical_model.encoder.parameters(), self.generated_model.encoder.parameters()):
torch.testing.assert_close(p_canon, p_gen, rtol=1e-5, atol=1e-8, msg="Encoder weights mismatch on initialization.")
# Compare parameters of the projection head
for p_canon, p_gen in zip(self.canonical_model.fc1.parameters(), self.generated_model.fc1.parameters()):
torch.testing.assert_close(p_canon, p_gen, rtol=1e-5, atol=1e-8, msg="Projection head fc1 weights mismatch on initialization.")
for p_canon, p_gen in zip(self.canonical_model.fc2.parameters(), self.generated_model.fc2.parameters()):
torch.testing.assert_close(p_canon, p_gen, rtol=1e-5, atol=1e-8, msg="Projection head fc2 weights mismatch on initialization.")
def test_positive_feature_augmentation(self):
"""
Test Instruction 2: Verify the positive feature augmentation function.
"""
canonical_aug = self.canonical_model.posaug(self.graph, self.posaug_features, self.edge_weights)
generated_aug = self.generated_model.posaug(self.graph, self.posaug_features, self.edge_weights)
torch.testing.assert_close(canonical_aug, generated_aug, rtol=1e-5, atol=1e-8, msg="`posaug` outputs are not equivalent.")
def test_forward_pass_for_encoding(self):
"""
Test Instruction 3: Verify the main forward pass for encoding multiple views.
"""
c_z1, c_z2, c_z = self.canonical_model(self.graph, self.features, self.graph, self.features, self.graph, self.features)
g_z1, g_z2, g_z = self.generated_model(self.graph, self.features, self.graph, self.features, self.graph, self.features)
torch.testing.assert_close(c_z1, g_z1, rtol=1e-5, atol=1e-8, msg="Encoder output z1 is not equivalent.")
torch.testing.assert_close(c_z2, g_z2, rtol=1e-5, atol=1e-8, msg="Encoder output z2 is not equivalent.")
torch.testing.assert_close(c_z, g_z, rtol=1e-5, atol=1e-8, msg="Encoder output z is not equivalent.")
def test_projection_head(self):
"""
Test Instruction 4: Verify the projection head function.
"""
sample_z = torch.randn(self.num_nodes, self.out_dim)
canonical_proj = self.canonical_model.projection(sample_z)
generated_proj = self.generated_model.projection(sample_z)
torch.testing.assert_close(canonical_proj, generated_proj, rtol=1e-5, atol=1e-8, msg="`projection` outputs are not equivalent.")
def test_contrastive_loss_calculation(self):
"""
Test Instruction 5: Verify the contrastive loss calculation.
"""
# Case 1: mean=True
canonical_loss_mean = self.canonical_model.loss(self.z1, self.adj_matrix1, self.z2, self.adj_matrix2, self.confmatrix, mean=True)
generated_loss_mean = self.generated_model.loss(self.z1, self.adj_matrix1, self.z2, self.adj_matrix2, self.confmatrix, mean=True)
torch.testing.assert_close(canonical_loss_mean, generated_loss_mean, rtol=1e-5, atol=1e-8, msg="Loss values (mean=True) are not equivalent.")
# Case 2: mean=False
canonical_loss_sum = self.canonical_model.loss(self.z1, self.adj_matrix1, self.z2, self.adj_matrix2, self.confmatrix, mean=False)
generated_loss_sum = self.generated_model.loss(self.z1, self.adj_matrix1, self.z2, self.adj_matrix2, self.confmatrix, mean=False)
torch.testing.assert_close(canonical_loss_sum, generated_loss_sum, rtol=1e-5, atol=1e-8, msg="Loss values (mean=False) are not equivalent.")
def test_embedding_retrieval(self):
"""
Test Instruction 6: Verify the function for retrieving final embeddings.
"""
canonical_emb = self.canonical_model.get_embedding(self.graph, self.features)
generated_emb = self.generated_model.get_embedding(self.graph, self.features)
self.assertFalse(canonical_emb.requires_grad, "Embeddings should be detached from the graph.")
torch.testing.assert_close(canonical_emb, generated_emb, rtol=1e-5, atol=1e-8, msg="`get_embedding` outputs are not equivalent.")
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)