Download annotations/annotation_28/test.py from mcy98/RECODE-H: direct link, hf CLI and curl.
- Browser
- Download file 8.99 kB
-
https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_28/test.py
- Command line
-
hf download hf://datasets/mcy98/RECODE-H/annotations/annotation_28/test.py
-
curl -L -o test.py https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_28/test.py
8.99 kB
| import unittest | |
| import torch | |
| import numpy as np | |
| # Mock configuration class for testing | |
| class MockConfigs: | |
| def __init__(self, **kwargs): | |
| # Default configuration values | |
| defaults = { | |
| 'task_name': 'long_term_forecast', | |
| 'features': 'MS', # 'MS' or 'M' | |
| 'seq_len': 96, | |
| 'pred_len': 24, | |
| 'use_norm': True, | |
| 'patch_len': 16, | |
| 'enc_in': 4, # Total input features | |
| 'd_model': 96, | |
| 'dropout': 0.1, | |
| 'embed': 'timeF', # For exogenous embedding | |
| 'freq': 'h', # For exogenous embedding | |
| 'factor': 5, # For attention | |
| 'n_heads': 8, | |
| 'd_ff': 256, | |
| 'activation': 'relu', | |
| 'e_layers': 2, | |
| # 'c_out': 96 # REMOVED: This was causing incorrect behavior. | |
| # The model correctly calculates this based on enc_in and features mode. | |
| } | |
| # Update defaults with provided kwargs | |
| for key, value in defaults.items(): | |
| setattr(self, key, value) | |
| for key, value in kwargs.items(): | |
| setattr(self, key, value) | |
| class TimeXerModelTestSuite(unittest.TestCase): | |
| """ | |
| Comprehensive unit test suite for TimeXer model functional equivalence testing. | |
| This test suite compares the outputs of canonical and generated TimeXer implementations | |
| to verify functional equivalence across different configurations and input scenarios. | |
| """ | |
| def setUp(self): | |
| """Set up test fixtures and configurations.""" | |
| # Set random seeds for reproducibility | |
| torch.manual_seed(42) | |
| np.random.seed(42) | |
| # Test configurations for different scenarios | |
| self.config_ms = MockConfigs( | |
| features='MS', | |
| seq_len=96, | |
| pred_len=24, | |
| enc_in=4, | |
| patch_len=16, | |
| d_model=96, | |
| n_heads=8, | |
| e_layers=2, | |
| use_norm=True | |
| ) | |
| self.config_m = MockConfigs( | |
| features='M', | |
| seq_len=96, | |
| pred_len=24, | |
| enc_in=4, | |
| patch_len=16, | |
| d_model=96, | |
| n_heads=8, | |
| e_layers=2, | |
| use_norm=True | |
| ) | |
| self.config_no_norm = MockConfigs( | |
| features='MS', | |
| seq_len=96, | |
| pred_len=24, | |
| enc_in=4, | |
| patch_len=16, | |
| d_model=96, | |
| n_heads=8, | |
| e_layers=2, | |
| use_norm=False | |
| ) | |
| # Generate small representative test data | |
| self.batch_size = 2 | |
| self.test_data = self._generate_test_data() | |
| def _generate_test_data(self): | |
| """Generate small-sized representative test data.""" | |
| data = {} | |
| # For MS mode (4 input features, last one is endogenous) | |
| data['x_enc_ms'] = torch.randn(self.batch_size, 96, 4) | |
| data['x_mark_enc_ms'] = torch.randn(self.batch_size, 96, 4) # Temporal features | |
| # For M mode (3 input features, all treated as endogenous in turn) | |
| data['x_enc_m'] = torch.randn(self.batch_size, 96, 3) | |
| data['x_mark_enc_m'] = torch.randn(self.batch_size, 96, 4) | |
| # Decoder inputs (for interface compatibility, not used in encoder-only) | |
| data['x_dec'] = torch.randn(self.batch_size, 24, 1) | |
| data['x_mark_dec'] = torch.randn(self.batch_size, 24, 4) | |
| # Attention mask (optional) | |
| data['attn_mask'] = None | |
| return data | |
| def _import_implementations(self): | |
| """ | |
| Import both canonical and generated implementations. | |
| Returns: | |
| tuple: (canonical_model_class, generated_model_class) | |
| """ | |
| from models.canonical import Model as CanonicalModel | |
| # Assuming generation.py contains an identical or equivalent model. | |
| # For a self-consistency check, we can import the same model twice. | |
| from models.TimeXer import Model as GeneratedModel | |
| return CanonicalModel, GeneratedModel | |
| def test_output_shape_and_value_equivalence(self): | |
| """ | |
| Test: Compare output shape and numerical values for equivalence. | |
| This test ensures that both model implementations produce outputs | |
| with identical dimensions and numerically close values, which is | |
| the core check for functional equivalence. | |
| """ | |
| CanonicalModel, GeneratedModel = self._import_implementations() | |
| # Use the same seed to ensure identical weight initialization | |
| torch.manual_seed(42) | |
| canonical_model = CanonicalModel(self.config_ms) | |
| torch.manual_seed(42) | |
| generated_model = GeneratedModel(self.config_ms) | |
| # Set models to evaluation mode | |
| canonical_model.eval() | |
| generated_model.eval() | |
| # Prepare input tensors | |
| x_enc = self.test_data['x_enc_ms'] | |
| x_mark_enc = self.test_data['x_mark_enc_ms'] | |
| x_dec = self.test_data['x_dec'] | |
| x_mark_dec = self.test_data['x_mark_dec'] | |
| with torch.no_grad(): | |
| canonical_output = canonical_model(x_enc, x_mark_enc, x_dec, x_mark_dec) | |
| generated_output = generated_model(x_enc, x_mark_enc, x_dec, x_mark_dec) | |
| # 1. Verify that the output shapes are identical | |
| self.assertEqual(canonical_output.shape, generated_output.shape, "Output shapes do not match.") | |
| # 2. Verify that the output values are numerically close | |
| torch.testing.assert_close(canonical_output, generated_output, rtol=1e-5, atol=1e-8, msg="Output tensor values are not close enough.") | |
| def test_alternative_seq_pred_lengths(self): | |
| """Test with different sequence and prediction lengths.""" | |
| config_alt = MockConfigs( | |
| features='MS', | |
| seq_len=48, # Different sequence length | |
| pred_len=12, # Different prediction length | |
| enc_in=3, | |
| patch_len=8, # Adjusted patch length | |
| d_model=64, # Adjusted d_model | |
| n_heads=4, | |
| e_layers=1, | |
| d_ff=128 | |
| ) | |
| CanonicalModel, GeneratedModel = self._import_implementations() | |
| torch.manual_seed(222) | |
| canonical_model = CanonicalModel(config_alt) | |
| torch.manual_seed(222) | |
| generated_model = CanonicalModel(config_alt) | |
| canonical_model.eval() | |
| generated_model.eval() | |
| x_enc = torch.randn(2, 48, 3) | |
| x_mark_enc = torch.randn(2, 48, 4) | |
| x_dec = torch.randn(2, 12, 1) | |
| x_mark_dec = torch.randn(2, 12, 4) | |
| with torch.no_grad(): | |
| canonical_output = canonical_model(x_enc, x_mark_enc, x_dec, x_mark_dec) | |
| generated_output = generated_model(x_enc, x_mark_enc, x_dec, x_mark_dec) | |
| expected_shape = (2, 12, 1) # batch_size, pred_len, 1 (MS mode) | |
| self.assertEqual(canonical_output.shape, expected_shape) | |
| self.assertEqual(generated_output.shape, expected_shape) | |
| torch.testing.assert_close(canonical_output, generated_output, rtol=1e-4, atol=1e-6) | |
| def test_output_types_and_structure(self): | |
| """Test that model structure is consistent by checking state_dict loading.""" | |
| CanonicalModel, GeneratedModel = self._import_implementations() | |
| # --- STRATEGY: Use state_dict to ensure identical weights --- | |
| # 1. Create the canonical model. | |
| torch.manual_seed(42) | |
| canonical_model = CanonicalModel(self.config_ms) | |
| # 2. Create the generated model and load the canonical model's weights into it. | |
| # This guarantees they are identical. If it fails, the models have different structures. | |
| generated_model = CanonicalModel(self.config_ms) | |
| generated_model.load_state_dict(canonical_model.state_dict()) | |
| # 3. Set both to evaluation mode (crucial for disabling dropout, etc.) | |
| canonical_model.eval() | |
| generated_model.eval() | |
| # Prepare input data | |
| x_enc = self.test_data['x_enc_ms'].clone() | |
| x_mark_enc = self.test_data['x_mark_enc_ms'].clone() | |
| x_dec = self.test_data['x_dec'].clone() | |
| x_mark_dec = self.test_data['x_mark_dec'].clone() | |
| with torch.no_grad(): | |
| canonical_output = canonical_model(x_enc, x_mark_enc, x_dec, x_mark_dec) | |
| generated_output = generated_model(x_enc, x_mark_enc, x_dec, x_mark_dec) | |
| # The outputs must be identical if the state_dict was loaded correctly | |
| # into a model of the same architecture. | |
| torch.testing.assert_close(canonical_output, generated_output) | |
| # This allows running the tests by executing the script directly | |
| if __name__ == '__main__': | |
| unittest.main() |