File size: 9,016 Bytes
2d13eb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import unittest
import torch
import torch.nn as nn
from types import SimpleNamespace

# Assume the user's generated code is in a file named 'generation.py'
# and the canonical implementation is in a file named 'canonical.py'.
# Both files are expected to have the 'Model' class and its dependencies.
# To make this test runnable, we will mock the dependencies.

# --- Mock Dependencies ---
# These mock classes simulate the behavior of the external dependencies
# required by the iTransformer Model. They ensure that the Model's internal
# logic can be tested without needing the actual complex layer implementations.
# The key is that both canonical and generated code will use these exact same mocks.

class MockFullAttention(nn.Module):
    def __init__(self, *args, **kwargs):
        super().__init__()
    def forward(self, queries, keys, values, attn_mask):
        return values, None # Simply pass through the values

class MockAttentionLayer(nn.Module):
    def __init__(self, attention, d_model, n_heads, *args, **kwargs):
        super().__init__()
        self.d_model = d_model
        # This linear layer simulates the projection after attention
        self.out_projection = nn.Linear(d_model, d_model)
    def forward(self, queries, keys, values, attn_mask):
        # We ignore the mock attention and just project
        return self.out_projection(values), None

class MockEncoderLayer(nn.Module):
    def __init__(self, attention_layer, d_model, d_ff, dropout, activation):
        super().__init__()
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.attention = attention_layer
        self.ffn = nn.Sequential(
            nn.Linear(d_model, d_ff),
            nn.ReLU(),
            nn.Linear(d_ff, d_model)
        )
        self.dropout = nn.Dropout(dropout)

    def forward(self, x, attn_mask):
        # Simplified forward pass mimicking a transformer block
        attn_output, _ = self.attention(x, x, x, attn_mask)
        x = x + self.dropout(attn_output)
        x = self.norm1(x)
        ffn_output = self.ffn(x)
        x = x + self.dropout(ffn_output)
        x = self.norm2(x)
        return x

class MockEncoder(nn.Module):
    def __init__(self, attn_layers, norm_layer):
        super().__init__()
        self.layers = nn.ModuleList(attn_layers)
        self.norm = norm_layer
    def forward(self, x, attn_mask=None):
        for layer in self.layers:
            x = layer(x, attn_mask=attn_mask)
        if self.norm is not None:
            x = self.norm(x)
        return x, None # Return None for attentions

class MockDataEmbeddingInverted(nn.Module):
    def __init__(self, c_in, d_model, embed_type, freq, dropout):
        super().__init__()
        # Project from seq_len (c_in) to d_model
        self.value_embedding = nn.Linear(c_in, d_model)
        self.dropout = nn.Dropout(dropout)
    def forward(self, x, x_mark):
        # x shape: [batch_size, seq_len, n_vars]
        # iTransformer swaps T and N, so we permute
        x = x.permute(0, 2, 1) # -> [batch_size, n_vars, seq_len]
        # Project each variate's sequence to a d_model embedding
        x = self.value_embedding(x) # -> [batch_size, n_vars, d_model]
        return self.dropout(x)

# --- Monkey-patching the dependencies ---
# This step replaces the actual complex layers with our simple, deterministic mocks
# in the namespace of the modules we are about to import.
import sys
from unittest.mock import MagicMock

# Create mock modules so the imports don't fail
mock_layers_module = MagicMock()
mock_layers_module.Transformer_EncDec = MagicMock()
mock_layers_module.SelfAttention_Family = MagicMock()
mock_layers_module.Embed = MagicMock()

# Assign our mock classes to the attributes of the mock modules
sys.modules['layers'] = mock_layers_module
sys.modules['layers.Transformer_EncDec'] = mock_layers_module.Transformer_EncDec
sys.modules['layers.SelfAttention_Family'] = mock_layers_module.SelfAttention_Family
sys.modules['layers.Embed'] = mock_layers_module.Embed

mock_layers_module.Transformer_EncDec.Encoder = MockEncoder
mock_layers_module.Transformer_EncDec.EncoderLayer = MockEncoderLayer
mock_layers_module.SelfAttention_Family.FullAttention = MockFullAttention
mock_layers_module.SelfAttention_Family.AttentionLayer = MockAttentionLayer
mock_layers_module.Embed.DataEmbedding_inverted = MockDataEmbeddingInverted


# Now, import the models. They will use the mocked dependencies.
from models.canonical import Model as CanonicalModel
from models.iTransformer import Model as GeneratedModel

class TestITransformerEquivalence(unittest.TestCase):
    """
    Test suite to verify the functional equivalence of a generated iTransformer
    implementation against a canonical ground-truth implementation.
    """

    def setUp(self):
        """
        Set up common configurations and sample data for the tests.
        This method is run before each test function.
        """
        self.base_configs = {
            'seq_len': 32,
            'pred_len': 16,
            'enc_in': 7,
            'd_model': 128,
            'embed': 'timeF',
            'freq': 'h',
            'dropout': 0.1,
            'factor': 1,
            'n_heads': 8,
            'd_ff': 256,
            'activation': 'gelu',
            'e_layers': 2,
            'num_class': 10,
            'task_name': 'long_term_forecast' # Default task
        }

        # Create small, representative input data
        self.batch_size = 4
        self.x_enc = torch.randn(self.batch_size, self.base_configs['seq_len'], self.base_configs['enc_in'])
        self.x_mark_enc = torch.randn(self.batch_size, self.base_configs['seq_len'], 4)
        
        # Decoder inputs (for forecasting)
        self.x_dec = torch.randn(self.batch_size, self.base_configs['pred_len'], self.base_configs['enc_in'])
        self.x_mark_dec = torch.randn(self.batch_size, self.base_configs['pred_len'], 4)

        # Mask (for imputation)
        self.mask = torch.ones(self.batch_size, self.base_configs['seq_len'], self.base_configs['enc_in'])

    def run_comparison_test(self, configs_update):
        """
        Helper function to run a standard comparison for a given task.
        """
        # Ensure deterministic behavior for model weight initialization
        torch.manual_seed(0)

        # Create configs for the specific task
        configs_dict = self.base_configs.copy()
        configs_dict.update(configs_update)
        configs = SimpleNamespace(**configs_dict)

        # Initialize Canonical Model
        torch.manual_seed(0) # Reset seed right before init
        canonical_model = CanonicalModel(configs)
        canonical_model.eval() # Set to evaluation mode

        # Initialize Generated Model
        torch.manual_seed(0) # Reset seed right before init
        generated_model = GeneratedModel(configs)
        generated_model.eval() # Set to evaluation mode

        # Execute both models with identical inputs
        canonical_output = canonical_model(
            x_enc=self.x_enc, x_mark_enc=self.x_mark_enc,
            x_dec=self.x_dec, x_mark_dec=self.x_mark_dec, mask=self.mask
        )
        generated_output = generated_model(
            x_enc=self.x_enc, x_mark_enc=self.x_mark_enc,
            x_dec=self.x_dec, x_mark_dec=self.x_mark_dec, mask=self.mask
        )

        # Assert that the outputs are structurally and numerically identical
        self.assertIsInstance(generated_output, torch.Tensor)
        self.assertEqual(canonical_output.shape, generated_output.shape)
        torch.testing.assert_close(canonical_output, generated_output, rtol=1e-5, atol=1e-6)

    def test_forecasting_equivalence(self):
        """
        Tests functional equivalence for the 'long_term_forecast' task.
        """
        print("\nRunning test for 'long_term_forecast'...")
        self.run_comparison_test({'task_name': 'long_term_forecast'})
        print("✅ 'long_term_forecast' test passed.")

    def test_imputation_equivalence(self):
        """
        Tests functional equivalence for the 'imputation' task.
        """
        print("\nRunning test for 'imputation'...")
        self.run_comparison_test({'task_name': 'imputation'})
        print("✅ 'imputation' test passed.")


    def test_anomaly_detection_equivalence(self):
        """
        Tests functional equivalence for the 'anomaly_detection' task.
        """
        print("\nRunning test for 'anomaly_detection'...")
        self.run_comparison_test({'task_name': 'anomaly_detection'})
        print("✅ 'anomaly_detection' test passed.")

    def test_classification_equivalence(self):
        """
        Tests functional equivalence for the 'classification' task.
        """
        print("\nRunning test for 'classification'...")
        self.run_comparison_test({'task_name': 'classification'})
        print("✅ 'classification' test passed.")

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)