|
| 1 | +import unittest |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import torch |
| 5 | +import os |
| 6 | +import sys |
| 7 | + |
| 8 | +# Get the directory of the current file |
| 9 | +current_file_path = os.path.abspath(__file__) |
| 10 | +sys.path.append(os.path.dirname(os.path.dirname(current_file_path))) |
| 11 | + |
| 12 | +from easy_tpp.model import TorchNHP as NHP |
| 13 | +from easy_tpp.preprocess.dataset import get_data_loader |
| 14 | +from easy_tpp.config_factory import DataSpecConfig, ModelConfig |
| 15 | +from easy_tpp.utils import load_json |
| 16 | +from easy_tpp.preprocess.dataset import TPPDataset, EventTokenizer |
| 17 | + |
| 18 | + |
| 19 | +class TestNeuralHawkesProcess(unittest.TestCase): |
| 20 | + def setUp(self): |
| 21 | + """Set up the test environment.""" |
| 22 | + # Assuming the data is already generated and saved in 'synthetic_hf_data.json' |
| 23 | + self.data_file = 'synthetic_data.json' |
| 24 | + self.batch_size = 4 |
| 25 | + self.input_data = self._make_json_2_dict(self.data_file) |
| 26 | + self.dataset = TPPDataset(self.input_data) |
| 27 | + |
| 28 | + config = DataSpecConfig.parse_from_yaml_config({'num_event_types': 3, |
| 29 | + 'batch_size': self.batch_size, |
| 30 | + 'pad_token_id': 3}) |
| 31 | + |
| 32 | + self.tokenizer = EventTokenizer(config) |
| 33 | + |
| 34 | + self.data_loader = get_data_loader(self.dataset, 'torch', self.tokenizer, batch_size=self.batch_size) |
| 35 | + |
| 36 | + model_config = ModelConfig.parse_from_yaml_config({'hidden_size': 32, |
| 37 | + 'loss_integral_num_sample_per_step': 20, |
| 38 | + 'num_event_types': 3, |
| 39 | + 'num_event_types_pad': 4, |
| 40 | + 'event_pad_index': 3}) |
| 41 | + self.model = NHP(model_config) |
| 42 | + |
| 43 | + def _make_json_2_dict(self, json_dir): |
| 44 | + json_data = load_json(json_dir) |
| 45 | + res = dict() |
| 46 | + res['time_seqs'] = [x['time_since_start'] for x in json_data] |
| 47 | + res['time_delta_seqs'] = ([np.array(x['time_since_last_event'], dtype=np.float32) for x in json_data]) |
| 48 | + res['type_seqs'] = [x['type_event'] for x in json_data] |
| 49 | + return res |
| 50 | + |
| 51 | + def test_model_initialization(self): |
| 52 | + """Test if the model is initialized correctly.""" |
| 53 | + self.assertIsInstance(self.model, NHP) |
| 54 | + self.assertEqual(self.model.hidden_size, 32) |
| 55 | + |
| 56 | + def test_forward_pass(self): |
| 57 | + """Test the forward pass of the model.""" |
| 58 | + batch = next(iter(self.data_loader)).values() |
| 59 | + output = self.model(batch) |
| 60 | + self.assertIsInstance(output[0], torch.Tensor) |
| 61 | + self.assertIsInstance(output[1], torch.Tensor) |
| 62 | + |
| 63 | + def test_loss_computation(self): |
| 64 | + """Test if the model computes loss correctly.""" |
| 65 | + batch = next(iter(self.data_loader)).values() |
| 66 | + loss = self.model.loglike_loss(batch) |
| 67 | + self.assertGreater(loss[0].item(), 0) # Loss should be positive |
| 68 | + |
| 69 | + def test_backward_pass(self): |
| 70 | + """Test if the model can perform a backward pass.""" |
| 71 | + batch = next(iter(self.data_loader)).values() |
| 72 | + loss = self.model.loglike_loss(batch) |
| 73 | + loss[0].backward() |
| 74 | + for param in self.model.parameters(): |
| 75 | + self.assertIsNotNone(param.grad) # Ensure gradients are computed |
| 76 | + |
| 77 | + def test_training_step(self): |
| 78 | + """Test a single training step.""" |
| 79 | + optimizer = torch.optim.Adam(self.model.parameters(), lr=0.001) |
| 80 | + self.model.train() |
| 81 | + for batch in self.data_loader: |
| 82 | + optimizer.zero_grad() |
| 83 | + loss = self.model.loglike_loss(batch.values()) |
| 84 | + loss[0].backward() |
| 85 | + optimizer.step() |
| 86 | + self.assertIsNotNone(loss[0]) # Ensure loss is computed |
| 87 | + break # Only run one step for the test |
| 88 | + |
| 89 | + |
| 90 | +if __name__ == '__main__': |
| 91 | + unittest.main() |
0 commit comments