import unittest import torch import numpy as np # Assuming the canonical code is in a file named 'models/canonical.py' # and the generated code is in 'models/TimeMixer.py' # The following imports are placeholders for the actual file names. from models.canonical import Model as CanonicalModel from models.TimeMixer import Model as GeneratedModel class DotDict(dict): """A dictionary that allows for dot notation access.""" __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class TestTimeMixerEquivalence(unittest.TestCase): """ Unit test suite to verify the functional equivalence of a generated TimeMixer model implementation against a canonical version across various tasks and configurations. """ def setUp(self): """Set up common configurations and sample data for all tests.""" torch.manual_seed(42) np.random.seed(42) self.base_config = { 'seq_len': 32, 'label_len': 16, 'pred_len': 16, 'down_sampling_window': 2, 'e_layers': 2, 'd_model': 16, 'enc_in': 7, 'c_out': 7, 'd_ff': 32, 'moving_avg': 7, 'dft_top_k': 5, 'dropout': 0.1, 'embed_type': 'timeF', 'freq': 'h', 'use_normalization': True, 'down_sampling_layers': 2, 'num_class': 10, } self.configs = { 'long_term_forecast_defaults': DotDict({ **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': False, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg' }), 'long_term_forecast_channel_indep': DotDict({ **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': True, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg' }), 'long_term_forecast_dft_decomp': DotDict({ **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': False, 'decomp_method': 'dft_decomp', 'downsampling_method': 'avg' }), 'long_term_forecast_max_pool': DotDict({ **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': False, 'decomp_method': 'moving_avg', 'downsampling_method': 'max' }), 'long_term_forecast_conv_pool': DotDict({ **self.base_config, 'task_name': 'long_term_forecast', 'channel_independence': False, 'decomp_method': 'moving_avg', 'downsampling_method': 'conv' }), 'short_term_forecast_defaults': DotDict({ **self.base_config, 'task_name': 'short_term_forecast', 'pred_len': 8, 'channel_independence': False, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg' }), 'imputation_defaults': DotDict({ **self.base_config, 'task_name': 'imputation', 'channel_independence': False, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg' }), 'imputation_channel_indep': DotDict({ **self.base_config, 'task_name': 'imputation', 'channel_independence': True, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg' }), 'anomaly_detection_defaults': DotDict({ **self.base_config, 'task_name': 'anomaly_detection', 'channel_independence': False, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg' }), 'anomaly_detection_channel_indep': DotDict({ **self.base_config, 'task_name': 'anomaly_detection', 'channel_independence': True, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg' }), 'classification_defaults': DotDict({ **self.base_config, 'task_name': 'classification', 'channel_independence': False, 'decomp_method': 'moving_avg', 'downsampling_method': 'avg' }), } # Generate sample data for each configuration self.sample_data = {} batch_size = 8 for name, config in self.configs.items(): dec_len = config.label_len + config.pred_len def create_time_features(size, is_2d=False): if is_2d: # For classification masking, return a 2D tensor of 0s and 1s return (torch.rand(size[0], size[1]) > 0.2).float() # For all other tasks, return the 3D time feature tensor months = torch.randint(low=1, high=13, size=(size[0], size[1], 1)) days = torch.randint(low=1, high=32, size=(size[0], size[1], 1)) weekdays = torch.randint(low=0, high=7, size=(size[0], size[1], 1)) hours = torch.randint(low=0, high=24, size=(size[0], size[1], 1)) return torch.cat([months, days, weekdays, hours], dim=-1) x_mark_enc_shape = (batch_size, config.seq_len) x_mark_dec_shape = (batch_size, dec_len) # FIX: Create a 2D mask for classification, and a 3D feature tensor for all other tasks. is_classification_task = (config.task_name == 'classification') x_mark_enc = create_time_features(x_mark_enc_shape, is_2d=is_classification_task) x_mark_dec = create_time_features(x_mark_dec_shape) # Decoder marks are not used in classification self.sample_data[name] = { 'x_enc': torch.randn(batch_size, config.seq_len, config.enc_in), 'x_mark_enc': x_mark_enc, 'x_dec': torch.randn(batch_size, dec_len, config.c_out), 'x_mark_dec': x_mark_dec, 'mask': (torch.rand(batch_size, config.seq_len, config.enc_in) > 0.2).float(), } def _are_models_equal(self, model1, model2): """Helper function to check if two models have identical parameters.""" for p1, p2 in zip(model1.parameters(), model2.parameters()): if p1.data.ne(p2.data).sum() > 0: # For debugging: print which parameters differ # print(f"Parameter mismatch: {p1.data} vs {p2.data}") return False return True def _run_equivalence_test(self, config_key): """ A generic helper function to run an equivalence test for a given configuration. It initializes, runs, and compares the canonical and generated models. """ config = self.configs[config_key] data = self.sample_data[config_key] task_name = config.task_name # 1. Initialize models with identical configurations and seeds torch.manual_seed(42) canonical_model = CanonicalModel(config) torch.manual_seed(42) generated_model = GeneratedModel(config) # Ensure model parameters are the same after initialization self.assertTrue( self._are_models_equal(canonical_model, generated_model), f"Model parameters are not equal for config: {config_key}" ) canonical_model.eval() generated_model.eval() # 2. Execute forward pass with identical inputs with torch.no_grad(): canonical_output = canonical_model( x_enc=data['x_enc'], x_mark_enc=data['x_mark_enc'], x_dec=data['x_dec'], x_mark_dec=data['x_mark_dec'], mask=data.get('mask') ) generated_output = generated_model( x_enc=data['x_enc'], x_mark_enc=data['x_mark_enc'], x_dec=data['x_dec'], x_mark_dec=data['x_mark_dec'], mask=data.get('mask') ) # 3. Compare outputs for shape and value self.assertEqual( canonical_output.shape, generated_output.shape, f"Output shape mismatch for config: {config_key}" ) torch.testing.assert_close( canonical_output, generated_output, rtol=1e-5, atol=1e-7, msg=f"Output tensors are not close for config: {config_key}" ) print(f"✅ Test passed for configuration: {config_key}") # --- Test Methods for Each Scenario --- def test_long_term_forecast_defaults(self): self._run_equivalence_test('long_term_forecast_defaults') def test_long_term_forecast_channel_indep(self): self._run_equivalence_test('long_term_forecast_channel_indep') def test_long_term_forecast_dft_decomp(self): self._run_equivalence_test('long_term_forecast_dft_decomp') def test_long_term_forecast_max_pool(self): self._run_equivalence_test('long_term_forecast_max_pool') def test_long_term_forecast_conv_pool(self): self._run_equivalence_test('long_term_forecast_conv_pool') def test_short_term_forecast_defaults(self): self._run_equivalence_test('short_term_forecast_defaults') def test_imputation_defaults(self): self._run_equivalence_test('imputation_defaults') def test_imputation_channel_indep(self): self._run_equivalence_test('imputation_channel_indep') def test_anomaly_detection_defaults(self): self._run_equivalence_test('anomaly_detection_defaults') def test_anomaly_detection_channel_indep(self): self._run_equivalence_test('anomaly_detection_channel_indep') def test_classification_defaults(self): self._run_equivalence_test('classification_defaults') if __name__ == '__main__': # To run this test, ensure the canonical and generated model code # are accessible via the specified import paths. unittest.main(argv=['first-arg-is-ignored'], exit=False, verbosity=2)