|
| 1 | +import os |
| 2 | + |
1 | 3 | import numpy as np |
2 | 4 | import pytest |
| 5 | +from absl.testing import parameterized |
3 | 6 |
|
4 | 7 | from keras.src import callbacks |
5 | 8 | from keras.src import initializers |
6 | 9 | from keras.src import layers |
| 10 | +from keras.src import models |
7 | 11 | from keras.src import testing |
| 12 | +from keras.src.callbacks import BackupAndRestore |
| 13 | +from keras.src.callbacks import TerminateOnNaN |
8 | 14 | from keras.src.models import Sequential |
9 | 15 | from keras.src.utils import numerical_utils |
10 | 16 |
|
11 | 17 |
|
| 18 | +@pytest.mark.requires_trainable_backend |
12 | 19 | class TerminateOnNaNTest(testing.TestCase): |
13 | | - @pytest.mark.requires_trainable_backend |
| 20 | + """Test suite for TerminateOnNaN callback.""" |
| 21 | + |
14 | 22 | def test_TerminateOnNaN(self): |
15 | 23 | TRAIN_SAMPLES = 10 |
16 | 24 | TEST_SAMPLES = 10 |
@@ -50,3 +58,161 @@ def test_TerminateOnNaN(self): |
50 | 58 | loss = history.history["loss"] |
51 | 59 | self.assertEqual(len(loss), 1) |
52 | 60 | self.assertTrue(np.isnan(loss[0]) or np.isinf(loss[0])) |
| 61 | + |
| 62 | + def test_terminate_on_nan_graceful_stop(self): |
| 63 | + """Test that TerminateOnNaN (default) gracefully stops training.""" |
| 64 | + model = models.Sequential([layers.Dense(1, input_shape=(1,))]) |
| 65 | + model.compile(optimizer="sgd", loss="mse") |
| 66 | + |
| 67 | + x = np.array([[1.0], [2.0]]) |
| 68 | + y = np.array([[np.inf], [np.inf]]) |
| 69 | + |
| 70 | + callback = TerminateOnNaN(raise_error=False) |
| 71 | + |
| 72 | + # Training should complete without raising RuntimeError |
| 73 | + history = model.fit( |
| 74 | + x, y, epochs=2, batch_size=1, callbacks=[callback], verbose=0 |
| 75 | + ) |
| 76 | + |
| 77 | + # Training should stop early |
| 78 | + self.assertLess(len(history.history["loss"]), 4) |
| 79 | + |
| 80 | + def test_terminate_on_nan_raise_error_raises_error(self): |
| 81 | + """Test that TerminateOnNaN(raise_error=True) raises |
| 82 | + RuntimeError on NaN loss. |
| 83 | + """ |
| 84 | + model = models.Sequential([layers.Dense(1, input_shape=(1,))]) |
| 85 | + model.compile(optimizer="sgd", loss="mse") |
| 86 | + |
| 87 | + x = np.array([[1.0], [2.0]]) |
| 88 | + y = np.array([[np.inf], [np.inf]]) |
| 89 | + |
| 90 | + callback = TerminateOnNaN(raise_error=True) |
| 91 | + |
| 92 | + # Training should raise RuntimeError |
| 93 | + with self.assertRaisesRegex( |
| 94 | + RuntimeError, |
| 95 | + "NaN or Inf loss encountered", |
| 96 | + ): |
| 97 | + model.fit( |
| 98 | + x, y, epochs=1, batch_size=1, callbacks=[callback], verbose=0 |
| 99 | + ) |
| 100 | + |
| 101 | + def test_raise_error_terminate_does_not_trigger_on_train_end(self): |
| 102 | + """Test that on_train_end is NOT called when |
| 103 | + TerminateOnNaN(raise_error=True) raises. |
| 104 | + """ |
| 105 | + |
| 106 | + class TrackingCallback(callbacks.Callback): |
| 107 | + def __init__(self): |
| 108 | + super().__init__() |
| 109 | + self.train_end_called = False |
| 110 | + |
| 111 | + def on_train_end(self, logs=None): |
| 112 | + self.train_end_called = True |
| 113 | + |
| 114 | + model = models.Sequential([layers.Dense(1, input_shape=(1,))]) |
| 115 | + model.compile(optimizer="sgd", loss="mse") |
| 116 | + |
| 117 | + x = np.array([[1.0]]) |
| 118 | + y = np.array([[np.inf]]) |
| 119 | + |
| 120 | + tracking_callback = TrackingCallback() |
| 121 | + raise_error_terminate_callback = TerminateOnNaN(raise_error=True) |
| 122 | + |
| 123 | + # Should raise RuntimeError |
| 124 | + with self.assertRaises(RuntimeError): |
| 125 | + model.fit( |
| 126 | + x, |
| 127 | + y, |
| 128 | + epochs=1, |
| 129 | + callbacks=[tracking_callback, raise_error_terminate_callback], |
| 130 | + verbose=0, |
| 131 | + ) |
| 132 | + |
| 133 | + # on_train_end should NOT have been called |
| 134 | + self.assertFalse(tracking_callback.train_end_called) |
| 135 | + |
| 136 | + def test_raise_error_terminate_preserves_backup(self): |
| 137 | + """Ensure BackupAndRestore directory is preserved when |
| 138 | + TerminateOnNaN(raise_error=True) triggers. |
| 139 | + """ |
| 140 | + tmpdir = self.get_temp_dir() |
| 141 | + backup_dir = os.path.join(tmpdir, "backups") |
| 142 | + os.makedirs(backup_dir, exist_ok=True) |
| 143 | + |
| 144 | + fake_file = os.path.join(backup_dir, "checkpoint.txt") |
| 145 | + with open(fake_file, "w") as f: |
| 146 | + f.write("dummy checkpoint") |
| 147 | + |
| 148 | + model = models.Sequential([layers.Dense(1, input_shape=(1,))]) |
| 149 | + model.compile(optimizer="sgd", loss="mse") |
| 150 | + |
| 151 | + x_nan = np.array([[1.0]]) |
| 152 | + y_nan = np.array([[np.inf]]) |
| 153 | + |
| 154 | + raise_error_terminate_callback = TerminateOnNaN(raise_error=True) |
| 155 | + backup_callback = BackupAndRestore(backup_dir=backup_dir) |
| 156 | + |
| 157 | + # Monkeypatch BackupAndRestore to prevent cleanup on train_end |
| 158 | + backup_callback.on_train_end = lambda logs=None: None |
| 159 | + |
| 160 | + # Training should raise RuntimeError |
| 161 | + with self.assertRaises(RuntimeError): |
| 162 | + model.fit( |
| 163 | + x_nan, |
| 164 | + y_nan, |
| 165 | + epochs=1, |
| 166 | + callbacks=[backup_callback, raise_error_terminate_callback], |
| 167 | + verbose=0, |
| 168 | + ) |
| 169 | + |
| 170 | + # Verify backup directory still exists and file inside is untouched |
| 171 | + self.assertTrue( |
| 172 | + os.path.exists(backup_dir), |
| 173 | + f"Backup dir deleted: {backup_dir}", |
| 174 | + ) |
| 175 | + self.assertTrue( |
| 176 | + os.path.exists(fake_file), |
| 177 | + "Backup file missing unexpectedly.", |
| 178 | + ) |
| 179 | + |
| 180 | + @parameterized.named_parameters( |
| 181 | + ("raise_error_false", False), |
| 182 | + ("raise_error_true", True), |
| 183 | + ) |
| 184 | + def test_normal_training_does_not_raise(self, raise_error): |
| 185 | + """Test that TerminateOnNaN does not raise on normal training.""" |
| 186 | + model = models.Sequential([layers.Dense(1, input_shape=(1,))]) |
| 187 | + model.compile(optimizer="sgd", loss="mse") |
| 188 | + |
| 189 | + x = np.array([[1.0], [2.0]]) |
| 190 | + y = np.array([[1.0], [2.0]]) |
| 191 | + |
| 192 | + callback = TerminateOnNaN(raise_error=raise_error) |
| 193 | + |
| 194 | + # Should complete without raising RuntimeError |
| 195 | + history = model.fit(x, y, epochs=2, callbacks=[callback], verbose=0) |
| 196 | + |
| 197 | + # Should have completed 2 epochs |
| 198 | + self.assertEqual(len(history.history["loss"]), 2) |
| 199 | + |
| 200 | + def test_raise_error_terminate_stops_on_later_batch(self): |
| 201 | + """Ensure TerminateOnNaN(raise_error=True) stops training |
| 202 | + if NaN appears in later batch. |
| 203 | + """ |
| 204 | + model = models.Sequential([layers.Dense(1, input_shape=(1,))]) |
| 205 | + model.compile(optimizer="sgd", loss="mse") |
| 206 | + |
| 207 | + # Batch 1: normal loss, Batch 2: NaN loss |
| 208 | + x = np.array([[1.0], [2.0]]) |
| 209 | + y = np.array([[1.0], [np.inf]]) # NaN/Inf appears only in 2nd batch |
| 210 | + |
| 211 | + callback = TerminateOnNaN(raise_error=True) |
| 212 | + |
| 213 | + with self.assertRaises(RuntimeError) as exc: |
| 214 | + model.fit( |
| 215 | + x, y, epochs=1, batch_size=1, callbacks=[callback], verbose=0 |
| 216 | + ) |
| 217 | + |
| 218 | + self.assertTrue(any(f"batch {i}" in str(exc.exception) for i in [0, 1])) |
0 commit comments