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)