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

# Ensure reproducibility of any random operations (e.g., initial weights)
# by setting a global seed.
torch.manual_seed(42)

# --- Import the models to be compared ---
# The canonical implementation (ground truth)
from models.canonical import Model as CanonicalModel
# The generated implementation (to be evaluated)
from models.PatchTST import Model as GeneratedModel

class TestPatchTSTEquivalence(unittest.TestCase):
    """
    A unit test suite to evaluate whether a generated PatchTST implementation
    functions identically to a canonical (ground truth) implementation.
    """

    def setUp(self):
        """
        Set up common configurations and sample data for the tests.
        This method runs before each test function.
        """
        self.patch_len = 16
        self.stride = 8
        self.batch_size = 4
        self.seq_len = 96 # A common sequence length for testing
        
        # Configuration for a typical long-term forecasting task
        self.long_forecast_config = SimpleNamespace(
            task_name='long_term_forecast',
            seq_len=self.seq_len,
            pred_len=96,
            d_model=128,
            n_heads=8,
            e_layers=3,
            d_ff=256,
            dropout=0.1,
            activation='relu',
            enc_in=7,  # Number of variables/channels
            factor=1,
            num_class=None
        )

        # Configuration for a single-variable forecasting task
        self.univariate_config = SimpleNamespace(
            **vars(self.long_forecast_config), # Copy from long_forecast_config
        )
        
        # --- Create Representative Sample Input Data ---
        self.multi_variable_input = torch.randn(
            self.batch_size, self.seq_len, self.long_forecast_config.enc_in
        )
        self.single_variable_input = torch.randn(
            self.batch_size, self.seq_len, self.univariate_config.enc_in
        )

    def _run_and_compare_models(self, config, input_data):
        """
        Helper function to instantiate, run, and compare the models.
        
        Args:
            config (SimpleNamespace): The model configuration.
            input_data (torch.Tensor): The input tensor for the forward pass.
        """
        # 1. Initialize models with identical configurations
        canonical_model = CanonicalModel(config, patch_len=self.patch_len, stride=self.stride)
        generated_model = GeneratedModel(config, patch_len=self.patch_len, stride=self.stride)

        # Ensure model weights are identical by loading the canonical state into the generated model
        generated_model.load_state_dict(canonical_model.state_dict())

        # 2. Set models to evaluation mode
        # This is CRITICAL to disable dropout and use learned stats in BatchNorm,
        # making the model's output deterministic.
        canonical_model.eval()
        generated_model.eval()

        # 3. Execute the forward pass with identical inputs
        # The other arguments (x_mark_enc, etc.) are not used by the core logic.
        with torch.no_grad(): # Disable gradient calculations for efficiency
            canonical_output = canonical_model(input_data, None, None, None)
            generated_output = generated_model(input_data, None, None, None)
            
        # 4. Compare the outputs
        self.assertIsNotNone(canonical_output, "Canonical model returned None.")
        self.assertIsNotNone(generated_output, "Generated model returned None.")
        
        # Check that output shapes are identical
        self.assertEqual(
            canonical_output.shape, 
            generated_output.shape,
            f"Output shape mismatch: Canonical={canonical_output.shape}, Generated={generated_output.shape}"
        )

        # Check that output data types are identical
        self.assertEqual(
            canonical_output.dtype,
            generated_output.dtype,
            f"Output dtype mismatch: Canonical={canonical_output.dtype}, Generated={generated_output.dtype}"
        )

        # Assert that the output tensors are numerically close.
        # This is the core test for functional equivalence.
        torch.testing.assert_close(
            canonical_output,
            generated_output,
            rtol=1e-5, # Relative tolerance
            atol=1e-8, # Absolute tolerance
            msg="Mismatch in tensor values between canonical and generated model outputs."
        )

    def test_initialization_and_parameters(self):
        """
        Tests that both models initialize with the same number of parameters
        and that their parameter names match.
        """
        canonical_model = CanonicalModel(self.long_forecast_config, self.patch_len, self.stride)
        generated_model = GeneratedModel(self.long_forecast_config, self.patch_len, self.stride)

        canon_params = list(canonical_model.named_parameters())
        gen_params = list(generated_model.named_parameters())

        self.assertEqual(len(canon_params), len(gen_params), "Mismatch in the number of model parameters.")

        for (canon_name, _), (gen_name, _) in zip(canon_params, gen_params):
            self.assertEqual(canon_name, gen_name, f"Parameter name mismatch: {canon_name} vs {gen_name}")

    def test_long_term_forecast_equivalence(self):
        """
        Tests functional equivalence on a standard multi-variable, long-term forecasting task.
        """
        print("\nRunning: Long-Term Forecast Equivalence Test (Multi-Variable)")
        self._run_and_compare_models(self.long_forecast_config, self.multi_variable_input)
        print("...PASSED")


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