File size: 8,062 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
import unittest
import torch
from types import SimpleNamespace

# Assume the provided DLinear model code is saved in 'canonical.py' and 'generation.py'
# This setup allows for direct comparison between a ground truth and a new implementation.
from models.canonical import Model as CanonicalModel
from models.Dlinear import Model as GeneratedModel

class TestDLinearFunctionalEquivalence(unittest.TestCase):
    """
    This test suite evaluates whether a generated DLinear implementation functions
    identically to a canonical (ground truth) implementation.
    
    It focuses on verifying functional equivalence by running both models with
    the same inputs and comparing their outputs.
    """

    def setUp(self):
        """
        Set up small-sized, representative sample input data and configurations
        to be used across all tests. This ensures efficiency and consistency.
        """
        self.batch_size = 4
        self.seq_len = 32
        self.pred_len = 16
        self.num_channels = 7
        self.num_classes = 5
        self.decomposition_kernel_size = 25 # An odd number as is common for moving averages

        # Create sample input tensor. No need for other inputs like x_mark_enc
        # as the core DLinear model does not use them.
        self.input_data = torch.randn(self.batch_size, self.seq_len, self.num_channels)
        
        # Define base configurations
        self.base_configs = {
            'seq_len': self.seq_len,
            'pred_len': self.pred_len,
            'enc_in': self.num_channels,
            'moving_avg': self.decomposition_kernel_size,
            'num_class': self.num_classes,
        }

    def _run_and_compare_models(self, configs, individual):
        """
        Helper function to instantiate, run, and compare the canonical and generated models.
        
        Args:
            configs (dict): Configuration parameters for the models.
            individual (bool): Flag for using individual channel layers.
        
        Returns:
            A tuple of (canonical_output, generated_output) for further specific assertions.
        """
        config_namespace = SimpleNamespace(**configs)

        # 1. Initialize models with identical configurations
        canonical_model = CanonicalModel(configs=config_namespace, individual=individual)
        generated_model = GeneratedModel(configs=config_namespace, individual=individual)

        # Ensure models are in evaluation mode
        canonical_model.eval()
        generated_model.eval()
        
        # 2. Enforce identical state
        # Although the weight initialization is deterministic, explicitly loading the state_dict
        # is a robust way to guarantee both models start from the exact same state.
        generated_model.load_state_dict(canonical_model.state_dict())

        # 3. Execute the forward pass with identical inputs
        # The DLinear model primarily uses `x_enc`. Other arguments are for broader compatibility.
        canonical_output = canonical_model(x_enc=self.input_data, x_mark_enc=None, x_dec=None, x_mark_dec=None)
        generated_output = generated_model(x_enc=self.input_data, x_mark_enc=None, x_dec=None, x_mark_dec=None)

        # 4. Assert core equivalence (type and shape)
        self.assertIsInstance(generated_output, torch.Tensor)
        self.assertEqual(canonical_output.shape, generated_output.shape, "Output shapes do not match.")
        self.assertEqual(canonical_output.dtype, generated_output.dtype, "Output data types do not match.")
        
        # 5. Assert numerical equivalence for tensors
        # Use torch.testing.assert_close for robust float comparisons.
        torch.testing.assert_close(
            canonical_output,
            generated_output,
            rtol=1e-5,
            atol=1e-8,
            msg="Tensor outputs are not numerically equivalent."
        )
        
        return canonical_output, generated_output

    def test_forecast_shared_layers(self):
        """
        Tests long-term forecasting with shared linear layers.
        """
        print("\nRunning: test_forecast_shared_layers")
        configs = self.base_configs.copy()
        configs['task_name'] = 'long_term_forecast'
        
        canonical_output, _ = self._run_and_compare_models(configs, individual=False)
        
        # Verify the output shape is correct for forecasting
        expected_shape = (self.batch_size, self.pred_len, self.num_channels)
        self.assertEqual(canonical_output.shape, expected_shape, f"Expected forecast shape {expected_shape}")
        print("✅ Passed")

    def test_forecast_individual_layers(self):
        """
        Tests long-term forecasting with individual linear layers per channel.
        """
        print("\nRunning: test_forecast_individual_layers")
        configs = self.base_configs.copy()
        configs['task_name'] = 'long_term_forecast'
        
        canonical_output, _ = self._run_and_compare_models(configs, individual=True)

        # Verify the output shape is correct for forecasting
        expected_shape = (self.batch_size, self.pred_len, self.num_channels)
        self.assertEqual(canonical_output.shape, expected_shape, f"Expected forecast shape {expected_shape}")
        print("✅ Passed")

    def test_classification_shared_layers(self):
        """
        Tests classification task with shared linear layers.
        """
        print("\nRunning: test_classification_shared_layers")
        configs = self.base_configs.copy()
        configs['task_name'] = 'classification'
        
        canonical_output, _ = self._run_and_compare_models(configs, individual=False)
        
        # Verify the output shape is correct for classification
        expected_shape = (self.batch_size, self.num_classes)
        self.assertEqual(canonical_output.shape, expected_shape, f"Expected classification shape {expected_shape}")
        print("✅ Passed")

    def test_classification_individual_layers(self):
        """
        Tests classification task with individual linear layers per channel.
        """
        print("\nRunning: test_classification_individual_layers")
        configs = self.base_configs.copy()
        configs['task_name'] = 'classification'

        canonical_output, _ = self._run_and_compare_models(configs, individual=True)
        
        # Verify the output shape is correct for classification
        expected_shape = (self.batch_size, self.num_classes)
        self.assertEqual(canonical_output.shape, expected_shape, f"Expected classification shape {expected_shape}")
        print("✅ Passed")

    def test_reconstruction_tasks(self):
        """
        Tests tasks that reconstruct the input, like imputation and anomaly detection.
        These tasks are functionally identical in the provided implementation.
        """
        for task in ['imputation', 'anomaly_detection']:
            with self.subTest(task=task):
                print(f"\nRunning: test_reconstruction_tasks (task={task})")
                configs = self.base_configs.copy()
                configs['task_name'] = task
                
                # Test both shared and individual layers for reconstruction
                canonical_output_shared, _ = self._run_and_compare_models(configs, individual=False)
                canonical_output_individual, _ = self._run_and_compare_models(configs, individual=True)
                
                # For these tasks, output length should equal input sequence length
                expected_shape = (self.batch_size, self.seq_len, self.num_channels)
                
                self.assertEqual(canonical_output_shared.shape, expected_shape, f"Expected {task} shape {expected_shape} for shared layers")
                self.assertEqual(canonical_output_individual.shape, expected_shape, f"Expected {task} shape {expected_shape} for individual layers")
                print(f"✅ Passed (task={task})")


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