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)