File size: 10,004 Bytes
e89a301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
223
224
225
226
227
228
229
230
import unittest
import torch
import numpy as np

# Assuming the canonical code is in a file named 'models/canonical.py'
# and the generated code is in 'models/TimeMixer.py'
# The following imports are placeholders for the actual file names.
from models.canonical import Model as CanonicalModel
from models.TimeMixer import Model as GeneratedModel


class DotDict(dict):
    """A dictionary that allows for dot notation access."""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


class TestTimeMixerEquivalence(unittest.TestCase):
    """
    Unit test suite to verify the functional equivalence of a generated TimeMixer
    model implementation against a canonical version across various tasks and configurations.
    """

    def setUp(self):
        """Set up common configurations and sample data for all tests."""
        torch.manual_seed(42)
        np.random.seed(42)

        self.base_config = {
            'seq_len': 32,
            'label_len': 16,
            'pred_len': 16,
            'down_sampling_window': 2,
            'e_layers': 2,
            'd_model': 16,
            'enc_in': 7,
            'c_out': 7,
            'd_ff': 32,
            'moving_avg': 7,
            'dft_top_k': 5,
            'dropout': 0.1,
            'embed_type': 'timeF',
            'freq': 'h',
            'use_normalization': True,
            'down_sampling_layers': 2,
            'num_class': 10,
        }
        
        self.configs = {
            'long_term_forecast_defaults': DotDict({
                **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': False,
                'decomp_method': 'moving_avg', 'downsampling_method': 'avg'
            }),
            'long_term_forecast_channel_indep': DotDict({
                **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': True,
                'decomp_method': 'moving_avg', 'downsampling_method': 'avg'
            }),
            'long_term_forecast_dft_decomp': DotDict({
                **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': False,
                'decomp_method': 'dft_decomp', 'downsampling_method': 'avg'
            }),
            'long_term_forecast_max_pool': DotDict({
                **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': False,
                'decomp_method': 'moving_avg', 'downsampling_method': 'max'
            }),
            'long_term_forecast_conv_pool': DotDict({
                **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': False,
                'decomp_method': 'moving_avg', 'downsampling_method': 'conv'
            }),
            'short_term_forecast_defaults': DotDict({
                **self.base_config, 'task_name': 'short_term_forecast', 'pred_len': 8,
                'channel_independence': False, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg'
            }),
            'imputation_defaults': DotDict({
                **self.base_config, 'task_name': 'imputation', 'channel_independence': False,
                'decomp_method': 'moving_avg', 'downsampling_method': 'avg'
            }),
            'imputation_channel_indep': DotDict({
                **self.base_config, 'task_name': 'imputation', 'channel_independence': True,
                'decomp_method': 'moving_avg', 'downsampling_method': 'avg'
            }),
            'anomaly_detection_defaults': DotDict({
                **self.base_config, 'task_name': 'anomaly_detection', 'channel_independence': False,
                'decomp_method': 'moving_avg', 'downsampling_method': 'avg'
            }),
            'anomaly_detection_channel_indep': DotDict({
                **self.base_config, 'task_name': 'anomaly_detection', 'channel_independence': True,
                'decomp_method': 'moving_avg', 'downsampling_method': 'avg'
            }),
            'classification_defaults': DotDict({
                **self.base_config, 'task_name': 'classification', 'channel_independence': False,
                'decomp_method': 'moving_avg', 'downsampling_method': 'avg'
            }),
        }

        # Generate sample data for each configuration
        self.sample_data = {}
        batch_size = 8
        for name, config in self.configs.items():
            dec_len = config.label_len + config.pred_len
            
            def create_time_features(size, is_2d=False):
                if is_2d:
                    # For classification masking, return a 2D tensor of 0s and 1s
                    return (torch.rand(size[0], size[1]) > 0.2).float()
                
                # For all other tasks, return the 3D time feature tensor
                months = torch.randint(low=1, high=13, size=(size[0], size[1], 1))
                days = torch.randint(low=1, high=32, size=(size[0], size[1], 1))
                weekdays = torch.randint(low=0, high=7, size=(size[0], size[1], 1))
                hours = torch.randint(low=0, high=24, size=(size[0], size[1], 1))
                return torch.cat([months, days, weekdays, hours], dim=-1)

            x_mark_enc_shape = (batch_size, config.seq_len)
            x_mark_dec_shape = (batch_size, dec_len)
            
            # FIX: Create a 2D mask for classification, and a 3D feature tensor for all other tasks.
            is_classification_task = (config.task_name == 'classification')
            x_mark_enc = create_time_features(x_mark_enc_shape, is_2d=is_classification_task)
            x_mark_dec = create_time_features(x_mark_dec_shape) # Decoder marks are not used in classification

            self.sample_data[name] = {
                'x_enc': torch.randn(batch_size, config.seq_len, config.enc_in),
                'x_mark_enc': x_mark_enc,
                'x_dec': torch.randn(batch_size, dec_len, config.c_out),
                'x_mark_dec': x_mark_dec,
                'mask': (torch.rand(batch_size, config.seq_len, config.enc_in) > 0.2).float(),
            }
            
    def _are_models_equal(self, model1, model2):
        """Helper function to check if two models have identical parameters."""
        for p1, p2 in zip(model1.parameters(), model2.parameters()):
            if p1.data.ne(p2.data).sum() > 0:
                # For debugging: print which parameters differ
                # print(f"Parameter mismatch: {p1.data} vs {p2.data}")
                return False
        return True

    def _run_equivalence_test(self, config_key):
        """
        A generic helper function to run an equivalence test for a given configuration.
        It initializes, runs, and compares the canonical and generated models.
        """
        config = self.configs[config_key]
        data = self.sample_data[config_key]
        task_name = config.task_name

        # 1. Initialize models with identical configurations and seeds
        torch.manual_seed(42)
        canonical_model = CanonicalModel(config)

        torch.manual_seed(42)
        generated_model = GeneratedModel(config)

        # Ensure model parameters are the same after initialization
        self.assertTrue(
            self._are_models_equal(canonical_model, generated_model),
            f"Model parameters are not equal for config: {config_key}"
        )

        canonical_model.eval()
        generated_model.eval()

        # 2. Execute forward pass with identical inputs
        with torch.no_grad():
            canonical_output = canonical_model(
                x_enc=data['x_enc'], x_mark_enc=data['x_mark_enc'],
                x_dec=data['x_dec'], x_mark_dec=data['x_mark_dec'],
                mask=data.get('mask')
            )
            generated_output = generated_model(
                x_enc=data['x_enc'], x_mark_enc=data['x_mark_enc'],
                x_dec=data['x_dec'], x_mark_dec=data['x_mark_dec'],
                mask=data.get('mask')
            )

        # 3. Compare outputs for shape and value
        self.assertEqual(
            canonical_output.shape, generated_output.shape,
            f"Output shape mismatch for config: {config_key}"
        )
        torch.testing.assert_close(
            canonical_output, generated_output,
            rtol=1e-5, atol=1e-7,
            msg=f"Output tensors are not close for config: {config_key}"
        )
        print(f"✅ Test passed for configuration: {config_key}")


    # --- Test Methods for Each Scenario ---

    def test_long_term_forecast_defaults(self):
        self._run_equivalence_test('long_term_forecast_defaults')

    def test_long_term_forecast_channel_indep(self):
        self._run_equivalence_test('long_term_forecast_channel_indep')
        
    def test_long_term_forecast_dft_decomp(self):
        self._run_equivalence_test('long_term_forecast_dft_decomp')

    def test_long_term_forecast_max_pool(self):
        self._run_equivalence_test('long_term_forecast_max_pool')

    def test_long_term_forecast_conv_pool(self):
        self._run_equivalence_test('long_term_forecast_conv_pool')
        
    def test_short_term_forecast_defaults(self):
        self._run_equivalence_test('short_term_forecast_defaults')

    def test_imputation_defaults(self):
        self._run_equivalence_test('imputation_defaults')

    def test_imputation_channel_indep(self):
        self._run_equivalence_test('imputation_channel_indep')

    def test_anomaly_detection_defaults(self):
        self._run_equivalence_test('anomaly_detection_defaults')
        
    def test_anomaly_detection_channel_indep(self):
        self._run_equivalence_test('anomaly_detection_channel_indep')

    def test_classification_defaults(self):
        self._run_equivalence_test('classification_defaults')


if __name__ == '__main__':
    # To run this test, ensure the canonical and generated model code
    # are accessible via the specified import paths.
    unittest.main(argv=['first-arg-is-ignored'], exit=False, verbosity=2)