File size: 6,908 Bytes
6077218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
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 GlobalDiscriminator as CanonicalGlobalDiscriminator
from canonical import PriorDiscriminator as CanonicalPriorDiscriminator
from canonical import FF as CanonicalFF

from model import GlobalDiscriminator as GeneratedGlobalDiscriminator
from model import PriorDiscriminator as GeneratedPriorDiscriminator
from model import FF as GeneratedFF


class TestFunctionalEquivalence(unittest.TestCase):
    """

    Test suite to verify that the generated modules are functionally

    identical to the canonical implementations.

    """

    def setUp(self):
        """

        Set up common parameters and data for all tests.

        """
        torch.manual_seed(42)
        self.batch_size = 4
        self.input_dim = 64

    def test_ff_module(self):
        """

        Test Instructions 5 & 6: Verify the FF module's initialization and forward pass.

        """
        # Initialize models
        torch.manual_seed(42)
        canonical_model = CanonicalFF(input_dim=self.input_dim)
        torch.manual_seed(42)
        generated_model = GeneratedFF(input_dim=self.input_dim)
        
        # Ensure models start with identical weights
        generated_model.load_state_dict(canonical_model.state_dict())
        
        # Create sample input
        sample_input = torch.randn(self.batch_size, self.input_dim)

        # Execute forward pass
        canonical_output = canonical_model(sample_input)
        generated_output = generated_model(sample_input)

        # Assert equivalence
        self.assertEqual(canonical_output.shape, generated_output.shape)
        torch.testing.assert_close(canonical_output, generated_output, msg="FF module outputs are not equivalent.")

    def test_prior_discriminator_module(self):
        """

        Test Instructions 3 & 4: Verify the PriorDiscriminator's initialization and forward pass.

        """
        # Initialize models
        torch.manual_seed(42)
        canonical_model = CanonicalPriorDiscriminator(input_dim=self.input_dim)
        torch.manual_seed(42)
        generated_model = GeneratedPriorDiscriminator(input_dim=self.input_dim)
        
        # Ensure models start with identical weights
        generated_model.load_state_dict(canonical_model.state_dict())
        
        # Create sample input
        sample_input = torch.randn(self.batch_size, self.input_dim)

        # Execute forward pass
        canonical_output = canonical_model(sample_input)
        generated_output = generated_model(sample_input)

        # Assert equivalence
        self.assertEqual(canonical_output.shape, (self.batch_size, 1))
        torch.testing.assert_close(canonical_output, generated_output, msg="PriorDiscriminator outputs are not equivalent.")

    def test_global_discriminator_initialization(self):
        """

        Test Instruction 1: Verify the GlobalDiscriminator's initialization.

        """
        # Initialize models
        torch.manual_seed(42)
        canonical_model = CanonicalGlobalDiscriminator(args={}, input_dim=self.input_dim)
        torch.manual_seed(42)
        generated_model = GeneratedGlobalDiscriminator(args={}, input_dim=self.input_dim)
        
        # Compare weights of all layers to ensure identical initialization
        for p_canon, p_gen in zip(canonical_model.parameters(), generated_model.parameters()):
            torch.testing.assert_close(p_canon, p_gen, msg="GlobalDiscriminator parameters mismatch on initialization.")

    def test_global_discriminator_forward_pass_failure(self):
        """

        Test Instruction 2: Verify the GlobalDiscriminator's forward pass.

        This test confirms that the generated code correctly replicates the dimensional mismatch bug

        present in the canonical code, causing an identical failure.

        """
        # A mock encoder to stand in for the undefined `self.encoder`
        class MockEncoder(nn.Module):
            def __init__(self, output_dim):
                super().__init__()
                self.output_dim = output_dim
            def forward(self, M, adj, batch_num_nodes):
                # Simply return a tensor of the correct batch size and output dimension
                return torch.randn(M.shape[0], self.output_dim), None

        # Initialize models and sync weights
        torch.manual_seed(42)
        canonical_model = CanonicalGlobalDiscriminator(args={}, input_dim=self.input_dim)
        generated_model = GeneratedGlobalDiscriminator(args={}, input_dim=self.input_dim)
        generated_model.load_state_dict(canonical_model.state_dict())

        # Attach the mock encoder to both instances
        # The output dimension (16) plus y_dim (16) equals 32, which matches the input of l0
        mock_encoder = MockEncoder(output_dim=16)
        canonical_model.encoder = mock_encoder
        generated_model.encoder = mock_encoder

        # Create sample input data
        y_input = torch.randn(self.batch_size, 16)
        m_input = torch.randn(self.batch_size, self.input_dim)
        dummy_data = {
            'adj': torch.zeros((self.batch_size, 10, 10)),
            'num_nodes': torch.full((self.batch_size,), 10)
        }

        # The forward pass should fail at the self.l2 layer due to a dimension mismatch
        # (l1 outputs 32 features, but l2 expects 512). We assert that both fail with the same error.
        with self.assertRaisesRegex(RuntimeError, r"mat1 and mat2 shapes cannot be multiplied \(\d+x32 and 512x1\)") as cm_canon:
            # The .cuda() calls in the canonical code will fail if no GPU is present.
            # We'll bypass this by temporarily mocking .cuda() to do nothing.
            with unittest.mock.patch.object(torch.Tensor, 'cuda', lambda self: self):
                 canonical_model(y_input, m_input, dummy_data)
        
        with self.assertRaisesRegex(RuntimeError, r"mat1 and mat2 shapes cannot be multiplied \(\d+x32 and 512x1\)") as cm_gen:
            with unittest.mock.patch.object(torch.Tensor, 'cuda', lambda self: self):
                generated_model(y_input, m_input, dummy_data)

        # Ensure the error messages are identical
        self.assertEqual(str(cm_canon.exception), str(cm_gen.exception))


if __name__ == '__main__':
    # Prepare a dummy generation.py to make imports work for the test runner
    # 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)