File size: 8,987 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
231
232
233
234
235
236
237
238
239
import unittest
import torch
import numpy as np

# Mock configuration class for testing
class MockConfigs:
    def __init__(self, **kwargs):
        # Default configuration values
        defaults = {
            'task_name': 'long_term_forecast',
            'features': 'MS',  # 'MS' or 'M'
            'seq_len': 96,
            'pred_len': 24,
            'use_norm': True,
            'patch_len': 16,
            'enc_in': 4,  # Total input features
            'd_model': 96,
            'dropout': 0.1,
            'embed': 'timeF',  # For exogenous embedding
            'freq': 'h',  # For exogenous embedding
            'factor': 5,  # For attention
            'n_heads': 8,
            'd_ff': 256,
            'activation': 'relu',
            'e_layers': 2,
            # 'c_out': 96 # REMOVED: This was causing incorrect behavior.
                         # The model correctly calculates this based on enc_in and features mode.
        }
        
        # Update defaults with provided kwargs
        for key, value in defaults.items():
            setattr(self, key, value)
        
        for key, value in kwargs.items():
            setattr(self, key, value)

class TimeXerModelTestSuite(unittest.TestCase):
    """
    Comprehensive unit test suite for TimeXer model functional equivalence testing.
    
    This test suite compares the outputs of canonical and generated TimeXer implementations
    to verify functional equivalence across different configurations and input scenarios.
    """
    
    def setUp(self):
        """Set up test fixtures and configurations."""
        # Set random seeds for reproducibility
        torch.manual_seed(42)
        np.random.seed(42)
        
        # Test configurations for different scenarios
        self.config_ms = MockConfigs(
            features='MS',
            seq_len=96,
            pred_len=24,
            enc_in=4,
            patch_len=16,
            d_model=96,
            n_heads=8,
            e_layers=2,
            use_norm=True
        )
        
        self.config_m = MockConfigs(
            features='M',
            seq_len=96,
            pred_len=24,
            enc_in=4,
            patch_len=16,
            d_model=96,
            n_heads=8,
            e_layers=2,
            use_norm=True
        )
        
        self.config_no_norm = MockConfigs(
            features='MS',
            seq_len=96,
            pred_len=24,
            enc_in=4,
            patch_len=16,
            d_model=96,
            n_heads=8,
            e_layers=2,
            use_norm=False
        )
        
        # Generate small representative test data
        self.batch_size = 2
        self.test_data = self._generate_test_data()
    
    def _generate_test_data(self):
        """Generate small-sized representative test data."""
        data = {}
        
        # For MS mode (4 input features, last one is endogenous)
        data['x_enc_ms'] = torch.randn(self.batch_size, 96, 4)
        data['x_mark_enc_ms'] = torch.randn(self.batch_size, 96, 4)  # Temporal features
        
        # For M mode (3 input features, all treated as endogenous in turn)
        data['x_enc_m'] = torch.randn(self.batch_size, 96, 3)
        data['x_mark_enc_m'] = torch.randn(self.batch_size, 96, 4)
        
        # Decoder inputs (for interface compatibility, not used in encoder-only)
        data['x_dec'] = torch.randn(self.batch_size, 24, 1)
        data['x_mark_dec'] = torch.randn(self.batch_size, 24, 4)
        
        # Attention mask (optional)
        data['attn_mask'] = None
        
        return data
    
    def _import_implementations(self):
        """
        Import both canonical and generated implementations.
        
        Returns:
            tuple: (canonical_model_class, generated_model_class)
        """
    
        from models.canonical import Model as CanonicalModel
        # Assuming generation.py contains an identical or equivalent model.
        # For a self-consistency check, we can import the same model twice.
        from models.TimeXer import Model as GeneratedModel
        
        return CanonicalModel, GeneratedModel
            

    def test_output_shape_and_value_equivalence(self):
        """
        Test: Compare output shape and numerical values for equivalence.
        
        This test ensures that both model implementations produce outputs
        with identical dimensions and numerically close values, which is
        the core check for functional equivalence.
        """
        CanonicalModel, GeneratedModel = self._import_implementations()
        
        # Use the same seed to ensure identical weight initialization
        torch.manual_seed(42)
        canonical_model = CanonicalModel(self.config_ms)
        
        torch.manual_seed(42)
        generated_model = GeneratedModel(self.config_ms)
        
        # Set models to evaluation mode
        canonical_model.eval()
        generated_model.eval()
        
        # Prepare input tensors
        x_enc = self.test_data['x_enc_ms']
        x_mark_enc = self.test_data['x_mark_enc_ms']
        x_dec = self.test_data['x_dec']
        x_mark_dec = self.test_data['x_mark_dec']
        
        with torch.no_grad():
            canonical_output = canonical_model(x_enc, x_mark_enc, x_dec, x_mark_dec)
            generated_output = generated_model(x_enc, x_mark_enc, x_dec, x_mark_dec)
        
        # 1. Verify that the output shapes are identical
        self.assertEqual(canonical_output.shape, generated_output.shape, "Output shapes do not match.")
        
        # 2. Verify that the output values are numerically close
        torch.testing.assert_close(canonical_output, generated_output, rtol=1e-5, atol=1e-8, msg="Output tensor values are not close enough.")

    def test_alternative_seq_pred_lengths(self):
        """Test with different sequence and prediction lengths."""
        config_alt = MockConfigs(
            features='MS',
            seq_len=48,  # Different sequence length
            pred_len=12,  # Different prediction length
            enc_in=3,
            patch_len=8,  # Adjusted patch length
            d_model=64,  # Adjusted d_model
            n_heads=4,
            e_layers=1,
            d_ff=128
        )
        
        CanonicalModel, GeneratedModel = self._import_implementations()
        
        torch.manual_seed(222)
        canonical_model = CanonicalModel(config_alt)
        
        torch.manual_seed(222)
        generated_model = CanonicalModel(config_alt)
        
        canonical_model.eval()
        generated_model.eval()
        
        x_enc = torch.randn(2, 48, 3)
        x_mark_enc = torch.randn(2, 48, 4)
        x_dec = torch.randn(2, 12, 1)
        x_mark_dec = torch.randn(2, 12, 4)
        
        with torch.no_grad():
            canonical_output = canonical_model(x_enc, x_mark_enc, x_dec, x_mark_dec)
            generated_output = generated_model(x_enc, x_mark_enc, x_dec, x_mark_dec)
        
        expected_shape = (2, 12, 1)  # batch_size, pred_len, 1 (MS mode)
        self.assertEqual(canonical_output.shape, expected_shape)
        self.assertEqual(generated_output.shape, expected_shape)
        torch.testing.assert_close(canonical_output, generated_output, rtol=1e-4, atol=1e-6)
    
    def test_output_types_and_structure(self):
        """Test that model structure is consistent by checking state_dict loading."""
        CanonicalModel, GeneratedModel = self._import_implementations()
        
        # --- STRATEGY: Use state_dict to ensure identical weights ---
        # 1. Create the canonical model.
        torch.manual_seed(42)
        canonical_model = CanonicalModel(self.config_ms)
        
        # 2. Create the generated model and load the canonical model's weights into it.
        # This guarantees they are identical. If it fails, the models have different structures.
        generated_model = CanonicalModel(self.config_ms)
        generated_model.load_state_dict(canonical_model.state_dict())
        
        # 3. Set both to evaluation mode (crucial for disabling dropout, etc.)
        canonical_model.eval()
        generated_model.eval()
        
        # Prepare input data
        x_enc = self.test_data['x_enc_ms'].clone()
        x_mark_enc = self.test_data['x_mark_enc_ms'].clone()
        x_dec = self.test_data['x_dec'].clone()
        x_mark_dec = self.test_data['x_mark_dec'].clone()
        
        with torch.no_grad():
            canonical_output = canonical_model(x_enc, x_mark_enc, x_dec, x_mark_dec)
            generated_output = generated_model(x_enc, x_mark_enc, x_dec, x_mark_dec)
        
        # The outputs must be identical if the state_dict was loaded correctly
        # into a model of the same architecture.
        torch.testing.assert_close(canonical_output, generated_output)

# This allows running the tests by executing the script directly
if __name__ == '__main__':
    unittest.main()