import unittest import torch from types import SimpleNamespace # Import the Model class from both the canonical and generated implementations # These files (canonical.py, generation.py) must be in the same directory # or in the Python path. from models.canonical import Model as CanonicalModel from models.FreTS import Model as GeneratedModel class TestFreTSFunctionalEquivalence(unittest.TestCase): """ Test suite to verify that the generated FreTS model implementation is functionally identical to the canonical implementation. Tests cover two main areas: 1. Model Initialization: Ensures that both models are constructed with parameters of the same shape and structure. 2. Forward Pass: Ensures that given identical inputs and initial weights, both models produce identical output forecasts. This is tested for both channel-dependent and channel-independent configurations. """ def setUp(self): """ Set up common configuration and sample data for the tests. This method runs before each test function. """ # 1. Define base configurations for the model # These parameters are small for efficient testing. self.base_configs = { 'task_name': 'long_term_forecast', 'seq_len': 16, 'pred_len': 8, 'enc_in': 4, # Number of features/channels 'channel_independence': '0' # Default to channel-dependent } # 2. Create small, representative input tensors self.batch_size = 2 self.input_x_enc = torch.randn(self.batch_size, self.base_configs['seq_len'], self.base_configs['enc_in']) # Dummy tensors for other forward pass arguments, as they are not used # in the core logic but are required by the function signature. self.input_x_mark_enc = torch.randn(self.batch_size, self.base_configs['seq_len'], 2) self.input_x_dec = torch.randn(self.batch_size, self.base_configs['pred_len'], self.base_configs['enc_in']) self.input_x_mark_dec = torch.randn(self.batch_size, self.base_configs['pred_len'], 2) def test_model_initialization_equivalence(self): """ Verifies that both models initialize with identical parameter shapes. This test does not compare the parameter values, which are expected to be different due to random initialization. Instead, it confirms that the architecture (shapes of weights, biases, and embeddings) is the same. """ configs = SimpleNamespace(**self.base_configs) # Instantiate both models canonical_model = CanonicalModel(configs) generated_model = GeneratedModel(configs) # Get the state dictionaries which contain all learnable parameters canonical_params = dict(canonical_model.named_parameters()) generated_params = dict(generated_model.named_parameters()) # Assert that both models have the same set of named parameters self.assertSetEqual(set(canonical_params.keys()), set(generated_params.keys()), "Models have different sets of learnable parameters.") # Assert that each corresponding parameter has the same shape for name, canonical_p in canonical_params.items(): generated_p = generated_params[name] self.assertEqual(canonical_p.shape, generated_p.shape, f"Shape mismatch for parameter '{name}': " f"Canonical={canonical_p.shape}, Generated={generated_p.shape}") def _run_forward_pass_test(self, configs): """Helper function to run a forward pass comparison.""" # 1. Instantiate both models with the same configuration canonical_model = CanonicalModel(configs) generated_model = GeneratedModel(configs) # 2. CRITICAL: Synchronize model weights. # This ensures that any difference in output is due to functional # implementation, not random initialization. generated_model.load_state_dict(canonical_model.state_dict()) # 3. Set models to evaluation mode canonical_model.eval() generated_model.eval() # 4. Execute the forward pass for both models with identical inputs with torch.no_grad(): # Disable gradient calculation for efficiency canonical_output = canonical_model( self.input_x_enc, self.input_x_mark_enc, self.input_x_dec, self.input_x_mark_dec ) generated_output = generated_model( self.input_x_enc, self.input_x_mark_enc, self.input_x_dec, self.input_x_mark_dec ) # 5. Assert that the outputs are numerically close # Using torch.testing.assert_close is robust to minor floating-point discrepancies. self.assertIsInstance(generated_output, torch.Tensor, "Generated output is not a torch.Tensor.") self.assertEqual(canonical_output.shape, generated_output.shape, f"Output shape mismatch: Canonical={canonical_output.shape}, Generated={generated_output.shape}") torch.testing.assert_close( canonical_output, generated_output, rtol=1e-5, atol=1e-8, msg="Mismatch in forward pass output values." ) def test_forward_pass_equivalence_channel_dependent(self): """ Tests functional equivalence of the forward pass when the Frequency Channel Learner is ENABLED (channel_independence='0'). """ configs = self.base_configs.copy() configs['channel_independence'] = '0' self._run_forward_pass_test(SimpleNamespace(**configs)) def test_forward_pass_equivalence_channel_independent(self): """ Tests functional equivalence of the forward pass when the Frequency Channel Learner is DISABLED (channel_independence='1'). """ configs = self.base_configs.copy() configs['channel_independence'] = '1' self._run_forward_pass_test(SimpleNamespace(**configs)) if __name__ == '__main__': unittest.main(argv=['first-arg-is-ignored'], exit=False)