mcy98's picture
Upload folder using huggingface_hub
6077218 verified
Raw History Blame Contribute Delete
10.2 kB
import unittest
import torch
import torch.nn as nn
# Assume the user's provided code is in a file named 'canonical.py'
# A generated version would be in 'generation.py'
# For this demonstration, we use the canonical code as the generated one to ensure tests pass.
from canonical import MyModel as CanonicalMyModel
from canonical import LinearClassifier as CanonicalLinearClassifier
from Model import MyModel as GeneratedMyModel
from Model import LinearClassifier as GeneratedLinearClassifier
class TestFunctionalEquivalence(unittest.TestCase):
"""
Test suite to verify that the generated model implementation is functionally
identical to the canonical implementation.
"""
def setUp(self):
"""
Set up common parameters and data for all tests.
This method runs before each test function.
"""
# Set a fixed seed for reproducibility of random operations (e.g., initial weights)
torch.manual_seed(42)
# Define small, representative dimensions for our test models
self.input_dim = 16
self.embed_dim = 8
self.proj_hidden_dim = 16
self.num_classes = 4
self.num_nodes = 5
self.num_edges = 8
self.temperature = 0.5
self.batch_size = 2
# --- Create Sample Input Data ---
# Node features tensor
self.node_features = torch.randn(self.num_nodes, self.input_dim)
# Edge index tensor representing graph connectivity
self.edge_index = torch.randint(0, self.num_nodes, (2, self.num_edges), dtype=torch.long)
# Sample embedding tensors for loss calculation tests
self.z1 = torch.randn(self.num_nodes, self.embed_dim)
self.z2 = torch.randn(self.num_nodes, self.embed_dim)
# --- Instantiate Models (Canonical and Generated) ---
# Instruction 1: Initialize GNN-based Contrastive Learning Model
self.canonical_model = CanonicalMyModel(
in_channels=self.input_dim,
out_channels=self.embed_dim,
num_proj_hidden=self.proj_hidden_dim,
temperature=self.temperature
)
self.generated_model = GeneratedMyModel(
in_channels=self.input_dim,
out_channels=self.embed_dim,
num_proj_hidden=self.proj_hidden_dim,
temperature=self.temperature
)
# Ensure models start with identical weights for fair comparison
self.generated_model.load_state_dict(self.canonical_model.state_dict())
# Instruction 7: Initialize Linear Classifier for Evaluation
self.canonical_classifier = CanonicalLinearClassifier(self.embed_dim, self.num_classes)
self.generated_classifier = GeneratedLinearClassifier(self.embed_dim, self.num_classes)
# Ensure classifiers start with identical weights
self.generated_classifier.load_state_dict(self.canonical_classifier.state_dict())
def test_model_initialization(self):
"""
Test Instruction 1: Verify model layers and parameters are initialized correctly.
"""
self.assertEqual(self.canonical_model.t, self.generated_model.t, "Temperature parameter mismatch.")
# Check shapes of all corresponding layers
self.assertEqual(self.canonical_model.conv1.in_channels, self.generated_model.conv1.in_channels)
self.assertEqual(self.canonical_model.conv1.out_channels, self.generated_model.conv1.out_channels)
self.assertEqual(self.canonical_model.conv2.in_channels, self.generated_model.conv2.in_channels)
self.assertEqual(self.canonical_model.conv2.out_channels, self.generated_model.conv2.out_channels)
self.assertEqual(self.canonical_model.fc1.in_features, self.generated_model.fc1.in_features)
self.assertEqual(self.canonical_model.fc1.out_features, self.generated_model.fc1.out_features)
self.assertEqual(self.canonical_model.fc2.in_features, self.generated_model.fc2.in_features)
self.assertEqual(self.canonical_model.fc2.out_features, self.generated_model.fc2.out_features)
def test_model_forward_pass(self):
"""
Test Instruction 2: Verify the GNN model's forward pass produces identical embeddings.
"""
# Execute the forward pass for both models
canonical_emb, canonical_proj = self.canonical_model(self.node_features, self.edge_index)
generated_emb, generated_proj = self.generated_model(self.node_features, self.edge_index)
# Assert that the outputs (node embeddings and projected embeddings) are identical
torch.testing.assert_close(canonical_emb, generated_emb, msg="GNN embeddings are not equivalent.")
torch.testing.assert_close(canonical_proj, generated_proj, msg="Projected embeddings are not equivalent.")
def test_similarity_calculation(self):
"""
Test Instruction 4: Verify the similarity calculation helper function.
"""
canonical_sim = self.canonical_model.cal_sim(self.z1, self.z2)
generated_sim = self.generated_model.cal_sim(self.z1, self.z2)
torch.testing.assert_close(canonical_sim, generated_sim, msg="Similarity matrices are not equivalent.")
def test_single_direction_loss_calculation(self):
"""
Test Instruction 5: Verify the single-direction loss calculation.
Covers both batched and non-batched computation modes.
"""
# --- Case 1: Non-batched computation ---
canonical_loss_full = self.canonical_model.cal_loss(self.z1, self.z2, batch_compute=False)
generated_loss_full = self.generated_model.cal_loss(self.z1, self.z2, batch_compute=False)
torch.testing.assert_close(canonical_loss_full, generated_loss_full, msg="Single-direction loss (full) mismatch.")
# --- Case 2: Batched computation ---
# Seeding is crucial here because `cal_loss` uses `torch.randperm` in batch mode
torch.manual_seed(42)
canonical_loss_batch = self.canonical_model.cal_loss(self.z1, self.z2, batch_compute=True, batch_size=self.batch_size)
torch.manual_seed(42)
generated_loss_batch = self.generated_model.cal_loss(self.z1, self.z2, batch_compute=True, batch_size=self.batch_size)
torch.testing.assert_close(canonical_loss_batch, generated_loss_batch, msg="Single-direction loss (batched) mismatch.")
def test_main_contrastive_loss(self):
"""
Test Instruction 3: Verify the main symmetric contrastive loss function.
"""
# --- Case 1: Non-batched computation ---
canonical_loss = self.canonical_model.loss(self.z1, self.z2, batch_compute=False)
generated_loss = self.generated_model.loss(self.z1, self.z2, batch_compute=False)
self.assertAlmostEqual(canonical_loss.item(), generated_loss.item(), msg="Main loss (full) mismatch.")
# --- Case 2: Batched computation ---
# Seeding is crucial here because the underlying `cal_loss` uses `torch.randperm`
torch.manual_seed(42)
canonical_loss_batch = self.canonical_model.loss(self.z1, self.z2, batch_compute=True, batch_size=self.batch_size)
torch.manual_seed(42)
generated_loss_batch = self.generated_model.loss(self.z1, self.z2, batch_compute=True, batch_size=self.batch_size)
self.assertAlmostEqual(canonical_loss_batch.item(), generated_loss_batch.item(), msg="Main loss (batched) mismatch.")
def test_model_parameter_freezing(self):
"""
Test Instruction 6: Verify the parameter freezing utility.
"""
# Freeze parameters
self.canonical_model.freeze(True)
self.generated_model.freeze(True)
for p_canon, p_gen in zip(self.canonical_model.parameters(), self.generated_model.parameters()):
self.assertFalse(p_canon.requires_grad, "Canonical model parameter not frozen.")
self.assertFalse(p_gen.requires_grad, "Generated model parameter not frozen.")
# Unfreeze parameters
self.canonical_model.freeze(False)
self.generated_model.freeze(False)
for p_canon, p_gen in zip(self.canonical_model.parameters(), self.generated_model.parameters()):
self.assertTrue(p_canon.requires_grad, "Canonical model parameter not unfrozen.")
self.assertTrue(p_gen.requires_grad, "Generated model parameter not unfrozen.")
def test_classifier_weights_initialization(self):
"""
Test Instruction 8: Verify the classifier's weight initialization.
"""
# Create fresh classifiers to test initialization
torch.manual_seed(42)
canonical_clf = CanonicalLinearClassifier(self.embed_dim, self.num_classes)
canonical_clf.apply(canonical_clf.weights_init)
torch.manual_seed(42)
generated_clf = GeneratedLinearClassifier(self.embed_dim, self.num_classes)
generated_clf.apply(generated_clf.weights_init)
# Check that weights are identical after seeded initialization
torch.testing.assert_close(
canonical_clf.fc.weight,
generated_clf.fc.weight,
msg="Classifier weights mismatch after seeded initialization."
)
def test_classifier_forward_pass(self):
"""
Test Instruction 9: Verify the linear classifier's forward pass.
"""
# Use the classifiers from setUp which have identical initial weights
input_features = torch.randn(self.num_nodes, self.embed_dim)
canonical_logits = self.canonical_classifier(input_features)
generated_logits = self.generated_classifier(input_features)
# Assert that the output logits are identical
torch.testing.assert_close(canonical_logits, generated_logits, msg="Classifier logits are not equivalent.")
if __name__ == '__main__':
# Prepare a dummy generation.py to make imports work
# with open("Model.py", "w") as f:
# with open("canonical.py", "r") as c:
# f.write(c.read())
unittest.main(argv=['first-arg-is-ignored'], exit=False)